/db/sqlite3/src/sqlite3.c

https://bitbucket.org/mkato/mozilla-1.9.0-win64 · C · 102890 lines · 68690 code · 5311 blank · 28889 comment · 7745 complexity · d8171ee7d693017778d52b17b26a1b22 MD5 · raw file

  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.6.10. By combining all the individual C code files into this
  4. ** single large file, the entire code can be compiled as a one 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% are 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 in the first
  14. ** 6736 lines past this header comment.) Additional code files may be
  15. ** needed if you want a wrapper to interface SQLite with your choice of
  16. ** programming language. The code for the "sqlite3" command-line shell
  17. ** is also in a separate file. This file contains only code for the core
  18. ** SQLite library.
  19. **
  20. ** This amalgamation was generated on 2009-01-15 16:00:39 UTC.
  21. */
  22. #define SQLITE_CORE 1
  23. #define SQLITE_AMALGAMATION 1
  24. #ifndef SQLITE_PRIVATE
  25. # define SQLITE_PRIVATE static
  26. #endif
  27. #ifndef SQLITE_API
  28. # define SQLITE_API
  29. #endif
  30. /************** Begin file sqliteInt.h ***************************************/
  31. /*
  32. ** 2001 September 15
  33. **
  34. ** The author disclaims copyright to this source code. In place of
  35. ** a legal notice, here is a blessing:
  36. **
  37. ** May you do good and not evil.
  38. ** May you find forgiveness for yourself and forgive others.
  39. ** May you share freely, never taking more than you give.
  40. **
  41. *************************************************************************
  42. ** Internal interface definitions for SQLite.
  43. **
  44. ** @(#) $Id: sqliteInt.h,v 1.824 2009/01/14 23:03:41 drh Exp $
  45. */
  46. #ifndef _SQLITEINT_H_
  47. #define _SQLITEINT_H_
  48. /*
  49. ** Include the configuration header output by 'configure' if we're using the
  50. ** autoconf-based build
  51. */
  52. #ifdef _HAVE_SQLITE_CONFIG_H
  53. #include "config.h"
  54. #endif
  55. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  56. /************** Begin file sqliteLimit.h *************************************/
  57. /*
  58. ** 2007 May 7
  59. **
  60. ** The author disclaims copyright to this source code. In place of
  61. ** a legal notice, here is a blessing:
  62. **
  63. ** May you do good and not evil.
  64. ** May you find forgiveness for yourself and forgive others.
  65. ** May you share freely, never taking more than you give.
  66. **
  67. *************************************************************************
  68. **
  69. ** This file defines various limits of what SQLite can process.
  70. **
  71. ** @(#) $Id: sqliteLimit.h,v 1.10 2009/01/10 16:15:09 danielk1977 Exp $
  72. */
  73. /*
  74. ** The maximum length of a TEXT or BLOB in bytes. This also
  75. ** limits the size of a row in a table or index.
  76. **
  77. ** The hard limit is the ability of a 32-bit signed integer
  78. ** to count the size: 2^31-1 or 2147483647.
  79. */
  80. #ifndef SQLITE_MAX_LENGTH
  81. # define SQLITE_MAX_LENGTH 1000000000
  82. #endif
  83. /*
  84. ** This is the maximum number of
  85. **
  86. ** * Columns in a table
  87. ** * Columns in an index
  88. ** * Columns in a view
  89. ** * Terms in the SET clause of an UPDATE statement
  90. ** * Terms in the result set of a SELECT statement
  91. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  92. ** * Terms in the VALUES clause of an INSERT statement
  93. **
  94. ** The hard upper limit here is 32676. Most database people will
  95. ** tell you that in a well-normalized database, you usually should
  96. ** not have more than a dozen or so columns in any table. And if
  97. ** that is the case, there is no point in having more than a few
  98. ** dozen values in any of the other situations described above.
  99. */
  100. #ifndef SQLITE_MAX_COLUMN
  101. # define SQLITE_MAX_COLUMN 2000
  102. #endif
  103. /*
  104. ** The maximum length of a single SQL statement in bytes.
  105. **
  106. ** It used to be the case that setting this value to zero would
  107. ** turn the limit off. That is no longer true. It is not possible
  108. ** to turn this limit off.
  109. */
  110. #ifndef SQLITE_MAX_SQL_LENGTH
  111. # define SQLITE_MAX_SQL_LENGTH 1000000000
  112. #endif
  113. /*
  114. ** The maximum depth of an expression tree. This is limited to
  115. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  116. ** want to place more severe limits on the complexity of an
  117. ** expression.
  118. **
  119. ** A value of 0 used to mean that the limit was not enforced.
  120. ** But that is no longer true. The limit is now strictly enforced
  121. ** at all times.
  122. */
  123. #ifndef SQLITE_MAX_EXPR_DEPTH
  124. # define SQLITE_MAX_EXPR_DEPTH 1000
  125. #endif
  126. /*
  127. ** The maximum number of terms in a compound SELECT statement.
  128. ** The code generator for compound SELECT statements does one
  129. ** level of recursion for each term. A stack overflow can result
  130. ** if the number of terms is too large. In practice, most SQL
  131. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  132. ** any limit on the number of terms in a compount SELECT.
  133. */
  134. #ifndef SQLITE_MAX_COMPOUND_SELECT
  135. # define SQLITE_MAX_COMPOUND_SELECT 500
  136. #endif
  137. /*
  138. ** The maximum number of opcodes in a VDBE program.
  139. ** Not currently enforced.
  140. */
  141. #ifndef SQLITE_MAX_VDBE_OP
  142. # define SQLITE_MAX_VDBE_OP 25000
  143. #endif
  144. /*
  145. ** The maximum number of arguments to an SQL function.
  146. */
  147. #ifndef SQLITE_MAX_FUNCTION_ARG
  148. # define SQLITE_MAX_FUNCTION_ARG 127
  149. #endif
  150. /*
  151. ** The maximum number of in-memory pages to use for the main database
  152. ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
  153. */
  154. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  155. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  156. #endif
  157. #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  158. # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
  159. #endif
  160. /*
  161. ** The maximum number of attached databases. This must be between 0
  162. ** and 30. The upper bound on 30 is because a 32-bit integer bitmap
  163. ** is used internally to track attached databases.
  164. */
  165. #ifndef SQLITE_MAX_ATTACHED
  166. # define SQLITE_MAX_ATTACHED 10
  167. #endif
  168. /*
  169. ** The maximum value of a ?nnn wildcard that the parser will accept.
  170. */
  171. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  172. # define SQLITE_MAX_VARIABLE_NUMBER 999
  173. #endif
  174. /* Maximum page size. The upper bound on this value is 32768. This a limit
  175. ** imposed by the necessity of storing the value in a 2-byte unsigned integer
  176. ** and the fact that the page size must be a power of 2.
  177. **
  178. ** If this limit is changed, then the compiled library is technically
  179. ** incompatible with an SQLite library compiled with a different limit. If
  180. ** a process operating on a database with a page-size of 65536 bytes
  181. ** crashes, then an instance of SQLite compiled with the default page-size
  182. ** limit will not be able to rollback the aborted transaction. This could
  183. ** lead to database corruption.
  184. */
  185. #ifndef SQLITE_MAX_PAGE_SIZE
  186. # define SQLITE_MAX_PAGE_SIZE 32768
  187. #endif
  188. /*
  189. ** The default size of a database page.
  190. */
  191. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  192. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  193. #endif
  194. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  195. # undef SQLITE_DEFAULT_PAGE_SIZE
  196. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  197. #endif
  198. /*
  199. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  200. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  201. ** device characteristics (sector-size and atomic write() support),
  202. ** SQLite may choose a larger value. This constant is the maximum value
  203. ** SQLite will choose on its own.
  204. */
  205. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  206. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  207. #endif
  208. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  209. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  210. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  211. #endif
  212. /*
  213. ** Maximum number of pages in one database file.
  214. **
  215. ** This is really just the default value for the max_page_count pragma.
  216. ** This value can be lowered (or raised) at run-time using that the
  217. ** max_page_count macro.
  218. */
  219. #ifndef SQLITE_MAX_PAGE_COUNT
  220. # define SQLITE_MAX_PAGE_COUNT 1073741823
  221. #endif
  222. /*
  223. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  224. ** operator.
  225. */
  226. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  227. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  228. #endif
  229. /************** End of sqliteLimit.h *****************************************/
  230. /************** Continuing where we left off in sqliteInt.h ******************/
  231. /* Disable nuisance warnings on Borland compilers */
  232. #if defined(__BORLANDC__)
  233. #pragma warn -rch /* unreachable code */
  234. #pragma warn -ccc /* Condition is always true or false */
  235. #pragma warn -aus /* Assigned value is never used */
  236. #pragma warn -csu /* Comparing signed and unsigned */
  237. #pragma warn -spa /* Suspicious pointer arithmetic */
  238. #endif
  239. /* Needed for various definitions... */
  240. #ifndef _GNU_SOURCE
  241. # define _GNU_SOURCE
  242. #endif
  243. /*
  244. ** Include standard header files as necessary
  245. */
  246. #ifdef HAVE_STDINT_H
  247. #include <stdint.h>
  248. #endif
  249. #ifdef HAVE_INTTYPES_H
  250. #include <inttypes.h>
  251. #endif
  252. /*
  253. * This macro is used to "hide" some ugliness in casting an int
  254. * value to a ptr value under the MSVC 64-bit compiler. Casting
  255. * non 64-bit values to ptr types results in a "hard" error with
  256. * the MSVC 64-bit compiler which this attempts to avoid.
  257. *
  258. * A simple compiler pragma or casting sequence could not be found
  259. * to correct this in all situations, so this macro was introduced.
  260. *
  261. * It could be argued that the intptr_t type could be used in this
  262. * case, but that type is not available on all compilers, or
  263. * requires the #include of specific headers which differs between
  264. * platforms.
  265. */
  266. #define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  267. #define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  268. /*
  269. ** These #defines should enable >2GB file support on POSIX if the
  270. ** underlying operating system supports it. If the OS lacks
  271. ** large file support, or if the OS is windows, these should be no-ops.
  272. **
  273. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  274. ** system #includes. Hence, this block of code must be the very first
  275. ** code in all source files.
  276. **
  277. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  278. ** on the compiler command line. This is necessary if you are compiling
  279. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  280. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  281. ** without this option, LFS is enable. But LFS does not exist in the kernel
  282. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  283. ** portability you should omit LFS.
  284. **
  285. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  286. */
  287. #ifndef SQLITE_DISABLE_LFS
  288. # define _LARGE_FILE 1
  289. # ifndef _FILE_OFFSET_BITS
  290. # define _FILE_OFFSET_BITS 64
  291. # endif
  292. # define _LARGEFILE_SOURCE 1
  293. #endif
  294. /*
  295. ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
  296. ** Older versions of SQLite used an optional THREADSAFE macro.
  297. ** We support that for legacy
  298. */
  299. #if !defined(SQLITE_THREADSAFE)
  300. #if defined(THREADSAFE)
  301. # define SQLITE_THREADSAFE THREADSAFE
  302. #else
  303. # define SQLITE_THREADSAFE 1
  304. #endif
  305. #endif
  306. /*
  307. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  308. ** It determines whether or not the features related to
  309. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  310. ** be overridden at runtime using the sqlite3_config() API.
  311. */
  312. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  313. # define SQLITE_DEFAULT_MEMSTATUS 1
  314. #endif
  315. /*
  316. ** Exactly one of the following macros must be defined in order to
  317. ** specify which memory allocation subsystem to use.
  318. **
  319. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  320. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  321. ** SQLITE_MEMORY_SIZE // internal allocator #1
  322. ** SQLITE_MMAP_HEAP_SIZE // internal mmap() allocator
  323. ** SQLITE_POW2_MEMORY_SIZE // internal power-of-two allocator
  324. **
  325. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  326. ** the default.
  327. */
  328. #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
  329. defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
  330. defined(SQLITE_POW2_MEMORY_SIZE)>1
  331. # error "At most one of the following compile-time configuration options\
  332. is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
  333. SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
  334. #endif
  335. #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
  336. defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
  337. defined(SQLITE_POW2_MEMORY_SIZE)==0
  338. # define SQLITE_SYSTEM_MALLOC 1
  339. #endif
  340. /*
  341. ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
  342. ** sizes of memory allocations below this value where possible.
  343. */
  344. #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
  345. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  346. #endif
  347. /*
  348. ** We need to define _XOPEN_SOURCE as follows in order to enable
  349. ** recursive mutexes on most Unix systems. But Mac OS X is different.
  350. ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
  351. ** so it is omitted there. See ticket #2673.
  352. **
  353. ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
  354. ** implemented on some systems. So we avoid defining it at all
  355. ** if it is already defined or if it is unneeded because we are
  356. ** not doing a threadsafe build. Ticket #2681.
  357. **
  358. ** See also ticket #2741.
  359. */
  360. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
  361. # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
  362. #endif
  363. /*
  364. ** The TCL headers are only needed when compiling the TCL bindings.
  365. */
  366. #if defined(SQLITE_TCL) || defined(TCLSH)
  367. # include <tcl.h>
  368. #endif
  369. /*
  370. ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
  371. ** Setting NDEBUG makes the code smaller and run faster. So the following
  372. ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
  373. ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  374. ** feature.
  375. */
  376. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  377. # define NDEBUG 1
  378. #endif
  379. /*
  380. ** The testcase() macro is used to aid in coverage testing. When
  381. ** doing coverage testing, the condition inside the argument to
  382. ** testcase() must be evaluated both true and false in order to
  383. ** get full branch coverage. The testcase() macro is inserted
  384. ** to help ensure adequate test coverage in places where simple
  385. ** condition/decision coverage is inadequate. For example, testcase()
  386. ** can be used to make sure boundary values are tested. For
  387. ** bitmask tests, testcase() can be used to make sure each bit
  388. ** is significant and used at least once. On switch statements
  389. ** where multiple cases go to the same block of code, testcase()
  390. ** can insure that all cases are evaluated.
  391. **
  392. */
  393. #ifdef SQLITE_COVERAGE_TEST
  394. SQLITE_PRIVATE void sqlite3Coverage(int);
  395. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  396. #else
  397. # define testcase(X)
  398. #endif
  399. /*
  400. ** The TESTONLY macro is used to enclose variable declarations or
  401. ** other bits of code that are needed to support the arguments
  402. ** within testcase() and assert() macros.
  403. */
  404. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  405. # define TESTONLY(X) X
  406. #else
  407. # define TESTONLY(X)
  408. #endif
  409. /*
  410. ** The ALWAYS and NEVER macros surround boolean expressions which
  411. ** are intended to always be true or false, respectively. Such
  412. ** expressions could be omitted from the code completely. But they
  413. ** are included in a few cases in order to enhance the resilience
  414. ** of SQLite to unexpected behavior - to make the code "self-healing"
  415. ** or "ductile" rather than being "brittle" and crashing at the first
  416. ** hint of unplanned behavior.
  417. **
  418. ** In other words, ALWAYS and NEVER are added for defensive code.
  419. **
  420. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  421. ** be true and false so that the unreachable code then specify will
  422. ** not be counted as untested code.
  423. */
  424. #if defined(SQLITE_COVERAGE_TEST)
  425. # define ALWAYS(X) (1)
  426. # define NEVER(X) (0)
  427. #elif !defined(NDEBUG)
  428. SQLITE_PRIVATE int sqlite3Assert(void);
  429. # define ALWAYS(X) ((X)?1:sqlite3Assert())
  430. # define NEVER(X) ((X)?sqlite3Assert():0)
  431. #else
  432. # define ALWAYS(X) (X)
  433. # define NEVER(X) (X)
  434. #endif
  435. /*
  436. ** The macro unlikely() is a hint that surrounds a boolean
  437. ** expression that is usually false. Macro likely() surrounds
  438. ** a boolean expression that is usually true. GCC is able to
  439. ** use these hints to generate better code, sometimes.
  440. */
  441. #if defined(__GNUC__) && 0
  442. # define likely(X) __builtin_expect((X),1)
  443. # define unlikely(X) __builtin_expect((X),0)
  444. #else
  445. # define likely(X) !!(X)
  446. # define unlikely(X) !!(X)
  447. #endif
  448. /*
  449. ** Sometimes we need a small amount of code such as a variable initialization
  450. ** to setup for a later assert() statement. We do not want this code to
  451. ** appear when assert() is disabled. The following macro is therefore
  452. ** used to contain that setup code. The "VVA" acronym stands for
  453. ** "Verification, Validation, and Accreditation". In other words, the
  454. ** code within VVA_ONLY() will only run during verification processes.
  455. */
  456. #ifndef NDEBUG
  457. # define VVA_ONLY(X) X
  458. #else
  459. # define VVA_ONLY(X)
  460. #endif
  461. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  462. /************** Begin file sqlite3.h *****************************************/
  463. /*
  464. ** 2001 September 15
  465. **
  466. ** The author disclaims copyright to this source code. In place of
  467. ** a legal notice, here is a blessing:
  468. **
  469. ** May you do good and not evil.
  470. ** May you find forgiveness for yourself and forgive others.
  471. ** May you share freely, never taking more than you give.
  472. **
  473. *************************************************************************
  474. ** This header file defines the interface that the SQLite library
  475. ** presents to client programs. If a C-function, structure, datatype,
  476. ** or constant definition does not appear in this file, then it is
  477. ** not a published API of SQLite, is subject to change without
  478. ** notice, and should not be referenced by programs that use SQLite.
  479. **
  480. ** Some of the definitions that are in this file are marked as
  481. ** "experimental". Experimental interfaces are normally new
  482. ** features recently added to SQLite. We do not anticipate changes
  483. ** to experimental interfaces but reserve to make minor changes if
  484. ** experience from use "in the wild" suggest such changes are prudent.
  485. **
  486. ** The official C-language API documentation for SQLite is derived
  487. ** from comments in this file. This file is the authoritative source
  488. ** on how SQLite interfaces are suppose to operate.
  489. **
  490. ** The name of this file under configuration management is "sqlite.h.in".
  491. ** The makefile makes some minor changes to this file (such as inserting
  492. ** the version number) and changes its name to "sqlite3.h" as
  493. ** part of the build process.
  494. **
  495. ** @(#) $Id: sqlite.h.in,v 1.421 2008/12/30 06:24:58 danielk1977 Exp $
  496. */
  497. #ifndef _SQLITE3_H_
  498. #define _SQLITE3_H_
  499. #include <stdarg.h> /* Needed for the definition of va_list */
  500. /*
  501. ** Make sure we can call this stuff from C++.
  502. */
  503. #if 0
  504. extern "C" {
  505. #endif
  506. /*
  507. ** Add the ability to override 'extern'
  508. */
  509. #ifndef SQLITE_EXTERN
  510. # define SQLITE_EXTERN extern
  511. #endif
  512. /*
  513. ** These no-op macros are used in front of interfaces to mark those
  514. ** interfaces as either deprecated or experimental. New applications
  515. ** should not use deprecated intrfaces - they are support for backwards
  516. ** compatibility only. Application writers should be aware that
  517. ** experimental interfaces are subject to change in point releases.
  518. **
  519. ** These macros used to resolve to various kinds of compiler magic that
  520. ** would generate warning messages when they were used. But that
  521. ** compiler magic ended up generating such a flurry of bug reports
  522. ** that we have taken it all out and gone back to using simple
  523. ** noop macros.
  524. */
  525. #define SQLITE_DEPRECATED
  526. #define SQLITE_EXPERIMENTAL
  527. /*
  528. ** Ensure these symbols were not defined by some previous header file.
  529. */
  530. #ifdef SQLITE_VERSION
  531. # undef SQLITE_VERSION
  532. #endif
  533. #ifdef SQLITE_VERSION_NUMBER
  534. # undef SQLITE_VERSION_NUMBER
  535. #endif
  536. /*
  537. ** CAPI3REF: Compile-Time Library Version Numbers {H10010} <S60100>
  538. **
  539. ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in
  540. ** the sqlite3.h file specify the version of SQLite with which
  541. ** that header file is associated.
  542. **
  543. ** The "version" of SQLite is a string of the form "X.Y.Z".
  544. ** The phrase "alpha" or "beta" might be appended after the Z.
  545. ** The X value is major version number always 3 in SQLite3.
  546. ** The X value only changes when backwards compatibility is
  547. ** broken and we intend to never break backwards compatibility.
  548. ** The Y value is the minor version number and only changes when
  549. ** there are major feature enhancements that are forwards compatible
  550. ** but not backwards compatible.
  551. ** The Z value is the release number and is incremented with
  552. ** each release but resets back to 0 whenever Y is incremented.
  553. **
  554. ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
  555. **
  556. ** INVARIANTS:
  557. **
  558. ** {H10011} The SQLITE_VERSION #define in the sqlite3.h header file shall
  559. ** evaluate to a string literal that is the SQLite version
  560. ** with which the header file is associated.
  561. **
  562. ** {H10014} The SQLITE_VERSION_NUMBER #define shall resolve to an integer
  563. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z
  564. ** are the major version, minor version, and release number.
  565. */
  566. #define SQLITE_VERSION "3.6.10"
  567. #define SQLITE_VERSION_NUMBER 3006010
  568. /*
  569. ** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
  570. ** KEYWORDS: sqlite3_version
  571. **
  572. ** These features provide the same information as the [SQLITE_VERSION]
  573. ** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated
  574. ** with the library instead of the header file. Cautious programmers might
  575. ** include a check in their application to verify that
  576. ** sqlite3_libversion_number() always returns the value
  577. ** [SQLITE_VERSION_NUMBER].
  578. **
  579. ** The sqlite3_libversion() function returns the same information as is
  580. ** in the sqlite3_version[] string constant. The function is provided
  581. ** for use in DLLs since DLL users usually do not have direct access to string
  582. ** constants within the DLL.
  583. **
  584. ** INVARIANTS:
  585. **
  586. ** {H10021} The [sqlite3_libversion_number()] interface shall return
  587. ** an integer equal to [SQLITE_VERSION_NUMBER].
  588. **
  589. ** {H10022} The [sqlite3_version] string constant shall contain
  590. ** the text of the [SQLITE_VERSION] string.
  591. **
  592. ** {H10023} The [sqlite3_libversion()] function shall return
  593. ** a pointer to the [sqlite3_version] string constant.
  594. */
  595. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  596. SQLITE_API const char *sqlite3_libversion(void);
  597. SQLITE_API int sqlite3_libversion_number(void);
  598. /*
  599. ** CAPI3REF: Test To See If The Library Is Threadsafe {H10100} <S60100>
  600. **
  601. ** SQLite can be compiled with or without mutexes. When
  602. ** the [SQLITE_THREADSAFE] C preprocessor macro 1 or 2, mutexes
  603. ** are enabled and SQLite is threadsafe. When the
  604. ** [SQLITE_THREADSAFE] macro is 0,
  605. ** the mutexes are omitted. Without the mutexes, it is not safe
  606. ** to use SQLite concurrently from more than one thread.
  607. **
  608. ** Enabling mutexes incurs a measurable performance penalty.
  609. ** So if speed is of utmost importance, it makes sense to disable
  610. ** the mutexes. But for maximum safety, mutexes should be enabled.
  611. ** The default behavior is for mutexes to be enabled.
  612. **
  613. ** This interface can be used by a program to make sure that the
  614. ** version of SQLite that it is linking against was compiled with
  615. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  616. **
  617. ** This interface only reports on the compile-time mutex setting
  618. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  619. ** SQLITE_THREADSAFE=1 then mutexes are enabled by default but
  620. ** can be fully or partially disabled using a call to [sqlite3_config()]
  621. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  622. ** or [SQLITE_CONFIG_MUTEX]. The return value of this function shows
  623. ** only the default compile-time setting, not any run-time changes
  624. ** to that setting.
  625. **
  626. ** See the [threading mode] documentation for additional information.
  627. **
  628. ** INVARIANTS:
  629. **
  630. ** {H10101} The [sqlite3_threadsafe()] function shall return zero if
  631. ** and only if SQLite was compiled with mutexing code omitted.
  632. **
  633. ** {H10102} The value returned by the [sqlite3_threadsafe()] function
  634. ** shall remain the same across calls to [sqlite3_config()].
  635. */
  636. SQLITE_API int sqlite3_threadsafe(void);
  637. /*
  638. ** CAPI3REF: Database Connection Handle {H12000} <S40200>
  639. ** KEYWORDS: {database connection} {database connections}
  640. **
  641. ** Each open SQLite database is represented by a pointer to an instance of
  642. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  643. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  644. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  645. ** is its destructor. There are many other interfaces (such as
  646. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  647. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  648. ** sqlite3 object.
  649. */
  650. typedef struct sqlite3 sqlite3;
  651. /*
  652. ** CAPI3REF: 64-Bit Integer Types {H10200} <S10110>
  653. ** KEYWORDS: sqlite_int64 sqlite_uint64
  654. **
  655. ** Because there is no cross-platform way to specify 64-bit integer types
  656. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  657. **
  658. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  659. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  660. ** compatibility only.
  661. **
  662. ** INVARIANTS:
  663. **
  664. ** {H10201} The [sqlite_int64] and [sqlite3_int64] type shall specify
  665. ** a 64-bit signed integer.
  666. **
  667. ** {H10202} The [sqlite_uint64] and [sqlite3_uint64] type shall specify
  668. ** a 64-bit unsigned integer.
  669. */
  670. #ifdef SQLITE_INT64_TYPE
  671. typedef SQLITE_INT64_TYPE sqlite_int64;
  672. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  673. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  674. typedef __int64 sqlite_int64;
  675. typedef unsigned __int64 sqlite_uint64;
  676. #else
  677. typedef long long int sqlite_int64;
  678. typedef unsigned long long int sqlite_uint64;
  679. #endif
  680. typedef sqlite_int64 sqlite3_int64;
  681. typedef sqlite_uint64 sqlite3_uint64;
  682. /*
  683. ** If compiling for a processor that lacks floating point support,
  684. ** substitute integer for floating-point.
  685. */
  686. #ifdef SQLITE_OMIT_FLOATING_POINT
  687. # define double sqlite3_int64
  688. #endif
  689. /*
  690. ** CAPI3REF: Closing A Database Connection {H12010} <S30100><S40200>
  691. **
  692. ** This routine is the destructor for the [sqlite3] object.
  693. **
  694. ** Applications should [sqlite3_finalize | finalize] all [prepared statements]
  695. ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
  696. ** the [sqlite3] object prior to attempting to close the object.
  697. ** The [sqlite3_next_stmt()] interface can be used to locate all
  698. ** [prepared statements] associated with a [database connection] if desired.
  699. ** Typical code might look like this:
  700. **
  701. ** <blockquote><pre>
  702. ** sqlite3_stmt *pStmt;
  703. ** while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
  704. ** &nbsp; sqlite3_finalize(pStmt);
  705. ** }
  706. ** </pre></blockquote>
  707. **
  708. ** If [sqlite3_close()] is invoked while a transaction is open,
  709. ** the transaction is automatically rolled back.
  710. **
  711. ** INVARIANTS:
  712. **
  713. ** {H12011} A successful call to [sqlite3_close(C)] shall destroy the
  714. ** [database connection] object C.
  715. **
  716. ** {H12012} A successful call to [sqlite3_close(C)] shall return SQLITE_OK.
  717. **
  718. ** {H12013} A successful call to [sqlite3_close(C)] shall release all
  719. ** memory and system resources associated with [database connection]
  720. ** C.
  721. **
  722. ** {H12014} A call to [sqlite3_close(C)] on a [database connection] C that
  723. ** has one or more open [prepared statements] shall fail with
  724. ** an [SQLITE_BUSY] error code.
  725. **
  726. ** {H12015} A call to [sqlite3_close(C)] where C is a NULL pointer shall
  727. ** be a harmless no-op returning SQLITE_OK.
  728. **
  729. ** {H12019} When [sqlite3_close(C)] is invoked on a [database connection] C
  730. ** that has a pending transaction, the transaction shall be
  731. ** rolled back.
  732. **
  733. ** ASSUMPTIONS:
  734. **
  735. ** {A12016} The C parameter to [sqlite3_close(C)] must be either a NULL
  736. ** pointer or an [sqlite3] object pointer obtained
  737. ** from [sqlite3_open()], [sqlite3_open16()], or
  738. ** [sqlite3_open_v2()], and not previously closed.
  739. */
  740. SQLITE_API int sqlite3_close(sqlite3 *);
  741. /*
  742. ** The type for a callback function.
  743. ** This is legacy and deprecated. It is included for historical
  744. ** compatibility and is not documented.
  745. */
  746. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  747. /*
  748. ** CAPI3REF: One-Step Query Execution Interface {H12100} <S10000>
  749. **
  750. ** The sqlite3_exec() interface is a convenient way of running one or more
  751. ** SQL statements without having to write a lot of C code. The UTF-8 encoded
  752. ** SQL statements are passed in as the second parameter to sqlite3_exec().
  753. ** The statements are evaluated one by one until either an error or
  754. ** an interrupt is encountered, or until they are all done. The 3rd parameter
  755. ** is an optional callback that is invoked once for each row of any query
  756. ** results produced by the SQL statements. The 5th parameter tells where
  757. ** to write any error messages.
  758. **
  759. ** The error message passed back through the 5th parameter is held
  760. ** in memory obtained from [sqlite3_malloc()]. To avoid a memory leak,
  761. ** the calling application should call [sqlite3_free()] on any error
  762. ** message returned through the 5th parameter when it has finished using
  763. ** the error message.
  764. **
  765. ** If the SQL statement in the 2nd parameter is NULL or an empty string
  766. ** or a string containing only whitespace and comments, then no SQL
  767. ** statements are evaluated and the database is not changed.
  768. **
  769. ** The sqlite3_exec() interface is implemented in terms of
  770. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
  771. ** The sqlite3_exec() routine does nothing to the database that cannot be done
  772. ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
  773. **
  774. ** INVARIANTS:
  775. **
  776. ** {H12101} A successful invocation of [sqlite3_exec(D,S,C,A,E)]
  777. ** shall sequentially evaluate all of the UTF-8 encoded,
  778. ** semicolon-separated SQL statements in the zero-terminated
  779. ** string S within the context of the [database connection] D.
  780. **
  781. ** {H12102} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL then
  782. ** the actions of the interface shall be the same as if the
  783. ** S parameter were an empty string.
  784. **
  785. ** {H12104} The return value of [sqlite3_exec()] shall be [SQLITE_OK] if all
  786. ** SQL statements run successfully and to completion.
  787. **
  788. ** {H12105} The return value of [sqlite3_exec()] shall be an appropriate
  789. ** non-zero [error code] if any SQL statement fails.
  790. **
  791. ** {H12107} If one or more of the SQL statements handed to [sqlite3_exec()]
  792. ** return results and the 3rd parameter is not NULL, then
  793. ** the callback function specified by the 3rd parameter shall be
  794. ** invoked once for each row of result.
  795. **
  796. ** {H12110} If the callback returns a non-zero value then [sqlite3_exec()]
  797. ** shall abort the SQL statement it is currently evaluating,
  798. ** skip all subsequent SQL statements, and return [SQLITE_ABORT].
  799. **
  800. ** {H12113} The [sqlite3_exec()] routine shall pass its 4th parameter through
  801. ** as the 1st parameter of the callback.
  802. **
  803. ** {H12116} The [sqlite3_exec()] routine shall set the 2nd parameter of its
  804. ** callback to be the number of columns in the current row of
  805. ** result.
  806. **
  807. ** {H12119} The [sqlite3_exec()] routine shall set the 3rd parameter of its
  808. ** callback to be an array of pointers to strings holding the
  809. ** values for each column in the current result set row as
  810. ** obtained from [sqlite3_column_text()].
  811. **
  812. ** {H12122} The [sqlite3_exec()] routine shall set the 4th parameter of its
  813. ** callback to be an array of pointers to strings holding the
  814. ** names of result columns as obtained from [sqlite3_column_name()].
  815. **
  816. ** {H12125} If the 3rd parameter to [sqlite3_exec()] is NULL then
  817. ** [sqlite3_exec()] shall silently discard query results.
  818. **
  819. ** {H12131} If an error occurs while parsing or evaluating any of the SQL
  820. ** statements in the S parameter of [sqlite3_exec(D,S,C,A,E)] and if
  821. ** the E parameter is not NULL, then [sqlite3_exec()] shall store
  822. ** in *E an appropriate error message written into memory obtained
  823. ** from [sqlite3_malloc()].
  824. **
  825. ** {H12134} The [sqlite3_exec(D,S,C,A,E)] routine shall set the value of
  826. ** *E to NULL if E is not NULL and there are no errors.
  827. **
  828. ** {H12137} The [sqlite3_exec(D,S,C,A,E)] function shall set the [error code]
  829. ** and message accessible via [sqlite3_errcode()],
  830. ** [sqlite3_extended_errcode()],
  831. ** [sqlite3_errmsg()], and [sqlite3_errmsg16()].
  832. **
  833. ** {H12138} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL or an
  834. ** empty string or contains nothing other than whitespace, comments,
  835. ** and/or semicolons, then results of [sqlite3_errcode()],
  836. ** [sqlite3_extended_errcode()],
  837. ** [sqlite3_errmsg()], and [sqlite3_errmsg16()]
  838. ** shall reset to indicate no errors.
  839. **
  840. ** ASSUMPTIONS:
  841. **
  842. ** {A12141} The first parameter to [sqlite3_exec()] must be an valid and open
  843. ** [database connection].
  844. **
  845. ** {A12142} The database connection must not be closed while
  846. ** [sqlite3_exec()] is running.
  847. **
  848. ** {A12143} The calling function should use [sqlite3_free()] to free
  849. ** the memory that *errmsg is left pointing at once the error
  850. ** message is no longer needed.
  851. **
  852. ** {A12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()]
  853. ** must remain unchanged while [sqlite3_exec()] is running.
  854. */
  855. SQLITE_API int sqlite3_exec(
  856. sqlite3*, /* An open database */
  857. const char *sql, /* SQL to be evaluated */
  858. int (*callback)(void*,int,char**,char**), /* Callback function */
  859. void *, /* 1st argument to callback */
  860. char **errmsg /* Error msg written here */
  861. );
  862. /*
  863. ** CAPI3REF: Result Codes {H10210} <S10700>
  864. ** KEYWORDS: SQLITE_OK {error code} {error codes}
  865. ** KEYWORDS: {result code} {result codes}
  866. **
  867. ** Many SQLite functions return an integer result code from the set shown
  868. ** here in order to indicates success or failure.
  869. **
  870. ** New error codes may be added in future versions of SQLite.
  871. **
  872. ** See also: [SQLITE_IOERR_READ | extended result codes]
  873. */
  874. #define SQLITE_OK 0 /* Successful result */
  875. /* beginning-of-error-codes */
  876. #define SQLITE_ERROR 1 /* SQL error or missing database */
  877. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  878. #define SQLITE_PERM 3 /* Access permission denied */
  879. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  880. #define SQLITE_BUSY 5 /* The database file is locked */
  881. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  882. #define SQLITE_NOMEM 7 /* A malloc() failed */
  883. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  884. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  885. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  886. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  887. #define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */
  888. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  889. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  890. #define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */
  891. #define SQLITE_EMPTY 16 /* Database is empty */
  892. #define SQLITE_SCHEMA 17 /* The database schema changed */
  893. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  894. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  895. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  896. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  897. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  898. #define SQLITE_AUTH 23 /* Authorization denied */
  899. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  900. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  901. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  902. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  903. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  904. /* end-of-error-codes */
  905. /*
  906. ** CAPI3REF: Extended Result Codes {H10220} <S10700>
  907. ** KEYWORDS: {extended error code} {extended error codes}
  908. ** KEYWORDS: {extended result code} {extended result codes}
  909. **
  910. ** In its default configuration, SQLite API routines return one of 26 integer
  911. ** [SQLITE_OK | result codes]. However, experience has shown that many of
  912. ** these result codes are too coarse-grained. They do not provide as
  913. ** much information about problems as programmers might like. In an effort to
  914. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  915. ** support for additional result codes that provide more detailed information
  916. ** about errors. The extended result codes are enabled or disabled
  917. ** on a per database connection basis using the
  918. ** [sqlite3_extended_result_codes()] API.
  919. **
  920. ** Some of the available extended result codes are listed here.
  921. ** One may expect the number of extended result codes will be expand
  922. ** over time. Software that uses extended result codes should expect
  923. ** to see new result codes in future releases of SQLite.
  924. **
  925. ** The SQLITE_OK result code will never be extended. It will always
  926. ** be exactly zero.
  927. **
  928. ** INVARIANTS:
  929. **
  930. ** {H10223} The symbolic name for an extended result code shall contains
  931. ** a related primary result code as a prefix.
  932. **
  933. ** {H10224} Primary result code names shall contain a single "_" character.
  934. **
  935. ** {H10225} Extended result code names shall contain two or more "_" characters.
  936. **
  937. ** {H10226} The numeric value of an extended result code shall contain the
  938. ** numeric value of its corresponding primary result code in
  939. ** its least significant 8 bits.
  940. */
  941. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  942. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  943. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  944. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  945. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  946. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  947. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  948. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  949. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  950. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  951. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  952. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  953. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  954. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  955. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  956. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  957. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  958. /*
  959. ** CAPI3REF: Flags For File Open Operations {H10230} <H11120> <H12700>
  960. **
  961. ** These bit values are intended for use in the
  962. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  963. ** in the 4th parameter to the xOpen method of the
  964. ** [sqlite3_vfs] object.
  965. */
  966. #define SQLITE_OPEN_READONLY 0x00000001
  967. #define SQLITE_OPEN_READWRITE 0x00000002
  968. #define SQLITE_OPEN_CREATE 0x00000004
  969. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008
  970. #define SQLITE_OPEN_EXCLUSIVE 0x00000010
  971. #define SQLITE_OPEN_MAIN_DB 0x00000100
  972. #define SQLITE_OPEN_TEMP_DB 0x00000200
  973. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400
  974. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800
  975. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000
  976. #define SQLITE_OPEN_SUBJOURNAL 0x00002000
  977. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000
  978. #define SQLITE_OPEN_NOMUTEX 0x00008000
  979. #define SQLITE_OPEN_FULLMUTEX 0x00010000
  980. /*
  981. ** CAPI3REF: Device Characteristics {H10240} <H11120>
  982. **
  983. ** The xDeviceCapabilities method of the [sqlite3_io_methods]
  984. ** object returns an integer which is a vector of the these
  985. ** bit values expressing I/O characteristics of the mass storage
  986. ** device that holds the file that the [sqlite3_io_methods]
  987. ** refers to.
  988. **
  989. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  990. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  991. ** mean that writes of blocks that are nnn bytes in size and
  992. ** are aligned to an address which is an integer multiple of
  993. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  994. ** that when data is appended to a file, the data is appended
  995. ** first then the size of the file is extended, never the other
  996. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  997. ** information is written to disk in the same order as calls
  998. ** to xWrite().
  999. */
  1000. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1001. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1002. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1003. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1004. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1005. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1006. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1007. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1008. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1009. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1010. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1011. /*
  1012. ** CAPI3REF: File Locking Levels {H10250} <H11120> <H11310>
  1013. **
  1014. ** SQLite uses one of these integer values as the second
  1015. ** argument to calls it makes to the xLock() and xUnlock() methods
  1016. ** of an [sqlite3_io_methods] object.
  1017. */
  1018. #define SQLITE_LOCK_NONE 0
  1019. #define SQLITE_LOCK_SHARED 1
  1020. #define SQLITE_LOCK_RESERVED 2
  1021. #define SQLITE_LOCK_PENDING 3
  1022. #define SQLITE_LOCK_EXCLUSIVE 4
  1023. /*
  1024. ** CAPI3REF: Synchronization Type Flags {H10260} <H11120>
  1025. **
  1026. ** When SQLite invokes the xSync() method of an
  1027. ** [sqlite3_io_methods] object it uses a combination of
  1028. ** these integer values as the second argument.
  1029. **
  1030. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1031. ** sync operation only needs to flush data to mass storage. Inode
  1032. ** information need not be flushed. The SQLITE_SYNC_NORMAL flag means
  1033. ** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means
  1034. ** to use Mac OS X style fullsync instead of fsync().
  1035. */
  1036. #define SQLITE_SYNC_NORMAL 0x00002
  1037. #define SQLITE_SYNC_FULL 0x00003
  1038. #define SQLITE_SYNC_DATAONLY 0x00010
  1039. /*
  1040. ** CAPI3REF: OS Interface Open File Handle {H11110} <S20110>
  1041. **
  1042. ** An [sqlite3_file] object represents an open file in the OS
  1043. ** interface layer. Individual OS interface implementations will
  1044. ** want to subclass this object by appending additional fields
  1045. ** for their own use. The pMethods entry is a pointer to an
  1046. ** [sqlite3_io_methods] object that defines methods for performing
  1047. ** I/O operations on the open file.
  1048. */
  1049. typedef struct sqlite3_file sqlite3_file;
  1050. struct sqlite3_file {
  1051. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1052. };
  1053. /*
  1054. ** CAPI3REF: OS Interface File Virtual Methods Object {H11120} <S20110>
  1055. **
  1056. ** Every file opened by the [sqlite3_vfs] xOpen method populates an
  1057. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1058. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1059. ** This object defines the methods used to perform various operations
  1060. ** against the open file represented by the [sqlite3_file] object.
  1061. **
  1062. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1063. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1064. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1065. ** flag may be ORed in to indicate that only the data of the file
  1066. ** and not its inode needs to be synced.
  1067. **
  1068. ** The integer values to xLock() and xUnlock() are one of
  1069. ** <ul>
  1070. ** <li> [SQLITE_LOCK_NONE],
  1071. ** <li> [SQLITE_LOCK_SHARED],
  1072. ** <li> [SQLITE_LOCK_RESERVED],
  1073. ** <li> [SQLITE_LOCK_PENDING], or
  1074. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1075. ** </ul>
  1076. ** xLock() increases the lock. xUnlock() decreases the lock.
  1077. ** The xCheckReservedLock() method checks whether any database connection,
  1078. ** either in this process or in some other process, is holding a RESERVED,
  1079. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1080. ** if such a lock exists and false otherwise.
  1081. **
  1082. ** The xFileControl() method is a generic interface that allows custom
  1083. ** VFS implementations to directly control an open file using the
  1084. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1085. ** integer opcode. The third argument is a generic pointer intended to
  1086. ** point to a structure that may contain arguments or space in which to
  1087. ** write return values. Potential uses for xFileControl() might be
  1088. ** functions to enable blocking locks with timeouts, to change the
  1089. ** locking strategy (for example to use dot-file locks), to inquire
  1090. ** about the status of a lock, or to break stale locks. The SQLite
  1091. ** core reserves all opcodes less than 100 for its own use.
  1092. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
  1093. ** Applications that define a custom xFileControl method should use opcodes
  1094. ** greater than 100 to avoid conflicts.
  1095. **
  1096. ** The xSectorSize() method returns the sector size of the
  1097. ** device that underlies the file. The sector size is the
  1098. ** minimum write that can be performed without disturbing
  1099. ** other bytes in the file. The xDeviceCharacteristics()
  1100. ** method returns a bit vector describing behaviors of the
  1101. ** underlying device:
  1102. **
  1103. ** <ul>
  1104. ** <li> [SQLITE_IOCAP_ATOMIC]
  1105. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1106. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1107. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1108. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1109. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1110. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1111. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1112. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1113. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1114. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1115. ** </ul>
  1116. **
  1117. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1118. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1119. ** mean that writes of blocks that are nnn bytes in size and
  1120. ** are aligned to an address which is an integer multiple of
  1121. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1122. ** that when data is appended to a file, the data is appended
  1123. ** first then the size of the file is extended, never the other
  1124. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1125. ** information is written to disk in the same order as calls
  1126. ** to xWrite().
  1127. **
  1128. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1129. ** in the unread portions of the buffer with zeros. A VFS that
  1130. ** fails to zero-fill short reads might seem to work. However,
  1131. ** failure to zero-fill short reads will eventually lead to
  1132. ** database corruption.
  1133. */
  1134. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1135. struct sqlite3_io_methods {
  1136. int iVersion;
  1137. int (*xClose)(sqlite3_file*);
  1138. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1139. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1140. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1141. int (*xSync)(sqlite3_file*, int flags);
  1142. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1143. int (*xLock)(sqlite3_file*, int);
  1144. int (*xUnlock)(sqlite3_file*, int);
  1145. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1146. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1147. int (*xSectorSize)(sqlite3_file*);
  1148. int (*xDeviceCharacteristics)(sqlite3_file*);
  1149. /* Additional methods may be added in future releases */
  1150. };
  1151. /*
  1152. ** CAPI3REF: Standard File Control Opcodes {H11310} <S30800>
  1153. **
  1154. ** These integer constants are opcodes for the xFileControl method
  1155. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1156. ** interface.
  1157. **
  1158. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1159. ** opcode causes the xFileControl method to write the current state of
  1160. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1161. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1162. ** into an integer that the pArg argument points to. This capability
  1163. ** is used during testing and only needs to be supported when SQLITE_TEST
  1164. ** is defined.
  1165. */
  1166. #define SQLITE_FCNTL_LOCKSTATE 1
  1167. #define SQLITE_GET_LOCKPROXYFILE 2
  1168. #define SQLITE_SET_LOCKPROXYFILE 3
  1169. #define SQLITE_LAST_ERRNO 4
  1170. /*
  1171. ** CAPI3REF: Mutex Handle {H17110} <S20130>
  1172. **
  1173. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1174. ** abstract type for a mutex object. The SQLite core never looks
  1175. ** at the internal representation of an [sqlite3_mutex]. It only
  1176. ** deals with pointers to the [sqlite3_mutex] object.
  1177. **
  1178. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1179. */
  1180. typedef struct sqlite3_mutex sqlite3_mutex;
  1181. /*
  1182. ** CAPI3REF: OS Interface Object {H11140} <S20100>
  1183. **
  1184. ** An instance of the sqlite3_vfs object defines the interface between
  1185. ** the SQLite core and the underlying operating system. The "vfs"
  1186. ** in the name of the object stands for "virtual file system".
  1187. **
  1188. ** The value of the iVersion field is initially 1 but may be larger in
  1189. ** future versions of SQLite. Additional fields may be appended to this
  1190. ** object when the iVersion value is increased. Note that the structure
  1191. ** of the sqlite3_vfs object changes in the transaction between
  1192. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1193. ** modified.
  1194. **
  1195. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1196. ** structure used by this VFS. mxPathname is the maximum length of
  1197. ** a pathname in this VFS.
  1198. **
  1199. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1200. ** the pNext pointer. The [sqlite3_vfs_register()]
  1201. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1202. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1203. ** searches the list. Neither the application code nor the VFS
  1204. ** implementation should use the pNext pointer.
  1205. **
  1206. ** The pNext field is the only field in the sqlite3_vfs
  1207. ** structure that SQLite will ever modify. SQLite will only access
  1208. ** or modify this field while holding a particular static mutex.
  1209. ** The application should never modify anything within the sqlite3_vfs
  1210. ** object once the object has been registered.
  1211. **
  1212. ** The zName field holds the name of the VFS module. The name must
  1213. ** be unique across all VFS modules.
  1214. **
  1215. ** SQLite will guarantee that the zFilename parameter to xOpen
  1216. ** is either a NULL pointer or string obtained
  1217. ** from xFullPathname(). SQLite further guarantees that
  1218. ** the string will be valid and unchanged until xClose() is
  1219. ** called. Because of the previous sentense,
  1220. ** the [sqlite3_file] can safely store a pointer to the
  1221. ** filename if it needs to remember the filename for some reason.
  1222. ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
  1223. ** must invite its own temporary name for the file. Whenever the
  1224. ** xFilename parameter is NULL it will also be the case that the
  1225. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1226. **
  1227. ** The flags argument to xOpen() includes all bits set in
  1228. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1229. ** or [sqlite3_open16()] is used, then flags includes at least
  1230. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1231. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1232. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1233. **
  1234. ** SQLite will also add one of the following flags to the xOpen()
  1235. ** call, depending on the object being opened:
  1236. **
  1237. ** <ul>
  1238. ** <li> [SQLITE_OPEN_MAIN_DB]
  1239. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1240. ** <li> [SQLITE_OPEN_TEMP_DB]
  1241. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1242. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1243. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1244. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1245. ** </ul>
  1246. **
  1247. ** The file I/O implementation can use the object type flags to
  1248. ** change the way it deals with files. For example, an application
  1249. ** that does not care about crash recovery or rollback might make
  1250. ** the open of a journal file a no-op. Writes to this journal would
  1251. ** also be no-ops, and any attempt to read the journal would return
  1252. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1253. ** file will be doing page-aligned sector reads and writes in a random
  1254. ** order and set up its I/O subsystem accordingly.
  1255. **
  1256. ** SQLite might also add one of the following flags to the xOpen method:
  1257. **
  1258. ** <ul>
  1259. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1260. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1261. ** </ul>
  1262. **
  1263. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1264. ** deleted when it is closed. The [SQLITE_OPEN_DELETEONCLOSE]
  1265. ** will be set for TEMP databases, journals and for subjournals.
  1266. **
  1267. ** The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
  1268. ** for exclusive access. This flag is set for all files except
  1269. ** for the main database file.
  1270. **
  1271. ** At least szOsFile bytes of memory are allocated by SQLite
  1272. ** to hold the [sqlite3_file] structure passed as the third
  1273. ** argument to xOpen. The xOpen method does not have to
  1274. ** allocate the structure; it should just fill it in.
  1275. **
  1276. ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1277. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1278. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1279. ** to test whether a file is at least readable. The file can be a
  1280. ** directory.
  1281. **
  1282. ** SQLite will always allocate at least mxPathname+1 bytes for the
  1283. ** output buffer xFullPathname. The exact size of the output buffer
  1284. ** is also passed as a parameter to both methods. If the output buffer
  1285. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1286. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1287. ** to prevent this by setting mxPathname to a sufficiently large value.
  1288. **
  1289. ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
  1290. ** are not strictly a part of the filesystem, but they are
  1291. ** included in the VFS structure for completeness.
  1292. ** The xRandomness() function attempts to return nBytes bytes
  1293. ** of good-quality randomness into zOut. The return value is
  1294. ** the actual number of bytes of randomness obtained.
  1295. ** The xSleep() method causes the calling thread to sleep for at
  1296. ** least the number of microseconds given. The xCurrentTime()
  1297. ** method returns a Julian Day Number for the current date and time.
  1298. **
  1299. */
  1300. typedef struct sqlite3_vfs sqlite3_vfs;
  1301. struct sqlite3_vfs {
  1302. int iVersion; /* Structure version number */
  1303. int szOsFile; /* Size of subclassed sqlite3_file */
  1304. int mxPathname; /* Maximum file pathname length */
  1305. sqlite3_vfs *pNext; /* Next registered VFS */
  1306. const char *zName; /* Name of this virtual file system */
  1307. void *pAppData; /* Pointer to application-specific data */
  1308. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1309. int flags, int *pOutFlags);
  1310. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1311. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1312. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1313. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1314. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1315. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1316. void (*xDlClose)(sqlite3_vfs*, void*);
  1317. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1318. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1319. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1320. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1321. /* New fields may be appended in figure versions. The iVersion
  1322. ** value will increment whenever this happens. */
  1323. };
  1324. /*
  1325. ** CAPI3REF: Flags for the xAccess VFS method {H11190} <H11140>
  1326. **
  1327. ** These integer constants can be used as the third parameter to
  1328. ** the xAccess method of an [sqlite3_vfs] object. {END} They determine
  1329. ** what kind of permissions the xAccess method is looking for.
  1330. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1331. ** simply checks whether the file exists.
  1332. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1333. ** checks whether the file is both readable and writable.
  1334. ** With SQLITE_ACCESS_READ, the xAccess method
  1335. ** checks whether the file is readable.
  1336. */
  1337. #define SQLITE_ACCESS_EXISTS 0
  1338. #define SQLITE_ACCESS_READWRITE 1
  1339. #define SQLITE_ACCESS_READ 2
  1340. /*
  1341. ** CAPI3REF: Initialize The SQLite Library {H10130} <S20000><S30100>
  1342. **
  1343. ** The sqlite3_initialize() routine initializes the
  1344. ** SQLite library. The sqlite3_shutdown() routine
  1345. ** deallocates any resources that were allocated by sqlite3_initialize().
  1346. **
  1347. ** A call to sqlite3_initialize() is an "effective" call if it is
  1348. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1349. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1350. ** following a call to sqlite3_shutdown(). Only an effective call
  1351. ** of sqlite3_initialize() does any initialization. All other calls
  1352. ** are harmless no-ops.
  1353. **
  1354. ** Among other things, sqlite3_initialize() shall invoke
  1355. ** sqlite3_os_init(). Similarly, sqlite3_shutdown()
  1356. ** shall invoke sqlite3_os_end().
  1357. **
  1358. ** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1359. ** If for some reason, sqlite3_initialize() is unable to initialize
  1360. ** the library (perhaps it is unable to allocate a needed resource such
  1361. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1362. **
  1363. ** The sqlite3_initialize() routine is called internally by many other
  1364. ** SQLite interfaces so that an application usually does not need to
  1365. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1366. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1367. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1368. ** already. However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1369. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1370. ** are omitted and the application must call sqlite3_initialize() directly
  1371. ** prior to using any other SQLite interface. For maximum portability,
  1372. ** it is recommended that applications always invoke sqlite3_initialize()
  1373. ** directly prior to using any other SQLite interface. Future releases
  1374. ** of SQLite may require this. In other words, the behavior exhibited
  1375. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1376. ** default behavior in some future release of SQLite.
  1377. **
  1378. ** The sqlite3_os_init() routine does operating-system specific
  1379. ** initialization of the SQLite library. The sqlite3_os_end()
  1380. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1381. ** performed by these routines include allocation or deallocation
  1382. ** of static resources, initialization of global variables,
  1383. ** setting up a default [sqlite3_vfs] module, or setting up
  1384. ** a default configuration using [sqlite3_config()].
  1385. **
  1386. ** The application should never invoke either sqlite3_os_init()
  1387. ** or sqlite3_os_end() directly. The application should only invoke
  1388. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1389. ** interface is called automatically by sqlite3_initialize() and
  1390. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1391. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1392. ** are built into SQLite when it is compiled for unix, windows, or os/2.
  1393. ** When built for other platforms (using the [SQLITE_OS_OTHER=1] compile-time
  1394. ** option) the application must supply a suitable implementation for
  1395. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1396. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1397. ** must return [SQLITE_OK] on success and some other [error code] upon
  1398. ** failure.
  1399. */
  1400. SQLITE_API int sqlite3_initialize(void);
  1401. SQLITE_API int sqlite3_shutdown(void);
  1402. SQLITE_API int sqlite3_os_init(void);
  1403. SQLITE_API int sqlite3_os_end(void);
  1404. /*
  1405. ** CAPI3REF: Configuring The SQLite Library {H14100} <S20000><S30200>
  1406. ** EXPERIMENTAL
  1407. **
  1408. ** The sqlite3_config() interface is used to make global configuration
  1409. ** changes to SQLite in order to tune SQLite to the specific needs of
  1410. ** the application. The default configuration is recommended for most
  1411. ** applications and so this routine is usually not necessary. It is
  1412. ** provided to support rare applications with unusual needs.
  1413. **
  1414. ** The sqlite3_config() interface is not threadsafe. The application
  1415. ** must insure that no other SQLite interfaces are invoked by other
  1416. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1417. ** may only be invoked prior to library initialization using
  1418. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1419. ** Note, however, that sqlite3_config() can be called as part of the
  1420. ** implementation of an application-defined [sqlite3_os_init()].
  1421. **
  1422. ** The first argument to sqlite3_config() is an integer
  1423. ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
  1424. ** what property of SQLite is to be configured. Subsequent arguments
  1425. ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
  1426. ** in the first argument.
  1427. **
  1428. ** When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1429. ** If the option is unknown or SQLite is unable to set the option
  1430. ** then this routine returns a non-zero [error code].
  1431. **
  1432. ** INVARIANTS:
  1433. **
  1434. ** {H14103} A successful invocation of [sqlite3_config()] shall return
  1435. ** [SQLITE_OK].
  1436. **
  1437. ** {H14106} The [sqlite3_config()] interface shall return [SQLITE_MISUSE]
  1438. ** if it is invoked in between calls to [sqlite3_initialize()] and
  1439. ** [sqlite3_shutdown()].
  1440. **
  1441. ** {H14120} A successful call to [sqlite3_config]([SQLITE_CONFIG_SINGLETHREAD])
  1442. ** shall set the default [threading mode] to Single-thread.
  1443. **
  1444. ** {H14123} A successful call to [sqlite3_config]([SQLITE_CONFIG_MULTITHREAD])
  1445. ** shall set the default [threading mode] to Multi-thread.
  1446. **
  1447. ** {H14126} A successful call to [sqlite3_config]([SQLITE_CONFIG_SERIALIZED])
  1448. ** shall set the default [threading mode] to Serialized.
  1449. **
  1450. ** {H14129} A successful call to [sqlite3_config]([SQLITE_CONFIG_MUTEX],X)
  1451. ** where X is a pointer to an initialized [sqlite3_mutex_methods]
  1452. ** object shall cause all subsequent mutex operations performed
  1453. ** by SQLite to use the mutex methods that were present in X
  1454. ** during the call to [sqlite3_config()].
  1455. **
  1456. ** {H14132} A successful call to [sqlite3_config]([SQLITE_CONFIG_GETMUTEX],X)
  1457. ** where X is a pointer to an [sqlite3_mutex_methods] object
  1458. ** shall overwrite the content of [sqlite3_mutex_methods] object
  1459. ** with the mutex methods currently in use by SQLite.
  1460. **
  1461. ** {H14135} A successful call to [sqlite3_config]([SQLITE_CONFIG_MALLOC],M)
  1462. ** where M is a pointer to an initialized [sqlite3_mem_methods]
  1463. ** object shall cause all subsequent memory allocation operations
  1464. ** performed by SQLite to use the methods that were present in
  1465. ** M during the call to [sqlite3_config()].
  1466. **
  1467. ** {H14138} A successful call to [sqlite3_config]([SQLITE_CONFIG_GETMALLOC],M)
  1468. ** where M is a pointer to an [sqlite3_mem_methods] object shall
  1469. ** overwrite the content of [sqlite3_mem_methods] object with
  1470. ** the memory allocation methods currently in use by
  1471. ** SQLite.
  1472. **
  1473. ** {H14141} A successful call to [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],1)
  1474. ** shall enable the memory allocation status collection logic.
  1475. **
  1476. ** {H14144} A successful call to [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],0)
  1477. ** shall disable the memory allocation status collection logic.
  1478. **
  1479. ** {H14147} The memory allocation status collection logic shall be
  1480. ** enabled by default.
  1481. **
  1482. ** {H14150} A successful call to [sqlite3_config]([SQLITE_CONFIG_SCRATCH],S,Z,N)
  1483. ** where Z and N are non-negative integers and
  1484. ** S is a pointer to an aligned memory buffer not less than
  1485. ** Z*N bytes in size shall cause S to be used by the
  1486. ** [scratch memory allocator] for as many as N simulataneous
  1487. ** allocations each of size (Z & ~7).
  1488. **
  1489. ** {H14153} A successful call to [sqlite3_config]([SQLITE_CONFIG_SCRATCH],S,Z,N)
  1490. ** where S is a NULL pointer shall disable the
  1491. ** [scratch memory allocator].
  1492. **
  1493. ** {H14156} A successful call to
  1494. ** [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],S,Z,N)
  1495. ** where Z and N are non-negative integers and
  1496. ** S is a pointer to an aligned memory buffer not less than
  1497. ** Z*N bytes in size shall cause S to be used by the
  1498. ** [pagecache memory allocator] for as many as N simulataneous
  1499. ** allocations each of size (Z & ~7).
  1500. **
  1501. ** {H14159} A successful call to
  1502. ** [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],S,Z,N)
  1503. ** where S is a NULL pointer shall disable the
  1504. ** [pagecache memory allocator].
  1505. **
  1506. ** {H14162} A successful call to [sqlite3_config]([SQLITE_CONFIG_HEAP],H,Z,N)
  1507. ** where Z and N are non-negative integers and
  1508. ** H is a pointer to an aligned memory buffer not less than
  1509. ** Z bytes in size shall enable the [memsys5] memory allocator
  1510. ** and cause it to use buffer S as its memory source and to use
  1511. ** a minimum allocation size of N.
  1512. **
  1513. ** {H14165} A successful call to [sqlite3_config]([SQLITE_CONFIG_HEAP],H,Z,N)
  1514. ** where H is a NULL pointer shall disable the
  1515. ** [memsys5] memory allocator.
  1516. **
  1517. ** {H14168} A successful call to [sqlite3_config]([SQLITE_CONFIG_LOOKASIDE],Z,N)
  1518. ** shall cause the default [lookaside memory allocator] configuration
  1519. ** for new [database connections] to be N slots of Z bytes each.
  1520. */
  1521. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
  1522. /*
  1523. ** CAPI3REF: Configure database connections {H14200} <S20000>
  1524. ** EXPERIMENTAL
  1525. **
  1526. ** The sqlite3_db_config() interface is used to make configuration
  1527. ** changes to a [database connection]. The interface is similar to
  1528. ** [sqlite3_config()] except that the changes apply to a single
  1529. ** [database connection] (specified in the first argument). The
  1530. ** sqlite3_db_config() interface can only be used immediately after
  1531. ** the database connection is created using [sqlite3_open()],
  1532. ** [sqlite3_open16()], or [sqlite3_open_v2()].
  1533. **
  1534. ** The second argument to sqlite3_db_config(D,V,...) is the
  1535. ** configuration verb - an integer code that indicates what
  1536. ** aspect of the [database connection] is being configured.
  1537. ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
  1538. ** New verbs are likely to be added in future releases of SQLite.
  1539. ** Additional arguments depend on the verb.
  1540. **
  1541. ** INVARIANTS:
  1542. **
  1543. ** {H14203} A call to [sqlite3_db_config(D,V,...)] shall return [SQLITE_OK]
  1544. ** if and only if the call is successful.
  1545. **
  1546. ** {H14206} If one or more slots of the [lookaside memory allocator] for
  1547. ** [database connection] D are in use, then a call to
  1548. ** [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],...) shall
  1549. ** fail with an [SQLITE_BUSY] return code.
  1550. **
  1551. ** {H14209} A successful call to
  1552. ** [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
  1553. ** D is an open [database connection] and Z and N are positive
  1554. ** integers and B is an aligned buffer at least Z*N bytes in size
  1555. ** shall cause the [lookaside memory allocator] for D to use buffer B
  1556. ** with N slots of Z bytes each.
  1557. **
  1558. ** {H14212} A successful call to
  1559. ** [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
  1560. ** D is an open [database connection] and Z and N are positive
  1561. ** integers and B is NULL pointer shall cause the
  1562. ** [lookaside memory allocator] for D to a obtain Z*N byte buffer
  1563. ** from the primary memory allocator and use that buffer
  1564. ** with N lookaside slots of Z bytes each.
  1565. **
  1566. ** {H14215} A successful call to
  1567. ** [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
  1568. ** D is an open [database connection] and Z and N are zero shall
  1569. ** disable the [lookaside memory allocator] for D.
  1570. **
  1571. **
  1572. */
  1573. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
  1574. /*
  1575. ** CAPI3REF: Memory Allocation Routines {H10155} <S20120>
  1576. ** EXPERIMENTAL
  1577. **
  1578. ** An instance of this object defines the interface between SQLite
  1579. ** and low-level memory allocation routines.
  1580. **
  1581. ** This object is used in only one place in the SQLite interface.
  1582. ** A pointer to an instance of this object is the argument to
  1583. ** [sqlite3_config()] when the configuration option is
  1584. ** [SQLITE_CONFIG_MALLOC]. By creating an instance of this object
  1585. ** and passing it to [sqlite3_config()] during configuration, an
  1586. ** application can specify an alternative memory allocation subsystem
  1587. ** for SQLite to use for all of its dynamic memory needs.
  1588. **
  1589. ** Note that SQLite comes with a built-in memory allocator that is
  1590. ** perfectly adequate for the overwhelming majority of applications
  1591. ** and that this object is only useful to a tiny minority of applications
  1592. ** with specialized memory allocation requirements. This object is
  1593. ** also used during testing of SQLite in order to specify an alternative
  1594. ** memory allocator that simulates memory out-of-memory conditions in
  1595. ** order to verify that SQLite recovers gracefully from such
  1596. ** conditions.
  1597. **
  1598. ** The xMalloc, xFree, and xRealloc methods must work like the
  1599. ** malloc(), free(), and realloc() functions from the standard library.
  1600. **
  1601. ** xSize should return the allocated size of a memory allocation
  1602. ** previously obtained from xMalloc or xRealloc. The allocated size
  1603. ** is always at least as big as the requested size but may be larger.
  1604. **
  1605. ** The xRoundup method returns what would be the allocated size of
  1606. ** a memory allocation given a particular requested size. Most memory
  1607. ** allocators round up memory allocations at least to the next multiple
  1608. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1609. **
  1610. ** The xInit method initializes the memory allocator. (For example,
  1611. ** it might allocate any require mutexes or initialize internal data
  1612. ** structures. The xShutdown method is invoked (indirectly) by
  1613. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1614. ** by xInit. The pAppData pointer is used as the only parameter to
  1615. ** xInit and xShutdown.
  1616. */
  1617. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1618. struct sqlite3_mem_methods {
  1619. void *(*xMalloc)(int); /* Memory allocation function */
  1620. void (*xFree)(void*); /* Free a prior allocation */
  1621. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1622. int (*xSize)(void*); /* Return the size of an allocation */
  1623. int (*xRoundup)(int); /* Round up request size to allocation size */
  1624. int (*xInit)(void*); /* Initialize the memory allocator */
  1625. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1626. void *pAppData; /* Argument to xInit() and xShutdown() */
  1627. };
  1628. /*
  1629. ** CAPI3REF: Configuration Options {H10160} <S20000>
  1630. ** EXPERIMENTAL
  1631. **
  1632. ** These constants are the available integer configuration options that
  1633. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1634. **
  1635. ** New configuration options may be added in future releases of SQLite.
  1636. ** Existing configuration options might be discontinued. Applications
  1637. ** should check the return code from [sqlite3_config()] to make sure that
  1638. ** the call worked. The [sqlite3_config()] interface will return a
  1639. ** non-zero [error code] if a discontinued or unsupported configuration option
  1640. ** is invoked.
  1641. **
  1642. ** <dl>
  1643. ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1644. ** <dd>There are no arguments to this option. This option disables
  1645. ** all mutexing and puts SQLite into a mode where it can only be used
  1646. ** by a single thread.</dd>
  1647. **
  1648. ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1649. ** <dd>There are no arguments to this option. This option disables
  1650. ** mutexing on [database connection] and [prepared statement] objects.
  1651. ** The application is responsible for serializing access to
  1652. ** [database connections] and [prepared statements]. But other mutexes
  1653. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1654. ** environment as long as no two threads attempt to use the same
  1655. ** [database connection] at the same time. See the [threading mode]
  1656. ** documentation for additional information.</dd>
  1657. **
  1658. ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1659. ** <dd>There are no arguments to this option. This option enables
  1660. ** all mutexes including the recursive
  1661. ** mutexes on [database connection] and [prepared statement] objects.
  1662. ** In this mode (which is the default when SQLite is compiled with
  1663. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1664. ** to [database connections] and [prepared statements] so that the
  1665. ** application is free to use the same [database connection] or the
  1666. ** same [prepared statement] in different threads at the same time.
  1667. ** See the [threading mode] documentation for additional information.</dd>
  1668. **
  1669. ** <dt>SQLITE_CONFIG_MALLOC</dt>
  1670. ** <dd>This option takes a single argument which is a pointer to an
  1671. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1672. ** alternative low-level memory allocation routines to be used in place of
  1673. ** the memory allocation routines built into SQLite.</dd>
  1674. **
  1675. ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1676. ** <dd>This option takes a single argument which is a pointer to an
  1677. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1678. ** structure is filled with the currently defined memory allocation routines.
  1679. ** This option can be used to overload the default memory allocation
  1680. ** routines with a wrapper that simulations memory allocation failure or
  1681. ** tracks memory usage, for example.</dd>
  1682. **
  1683. ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1684. ** <dd>This option takes single argument of type int, interpreted as a
  1685. ** boolean, which enables or disables the collection of memory allocation
  1686. ** statistics. When disabled, the following SQLite interfaces become
  1687. ** non-operational:
  1688. ** <ul>
  1689. ** <li> [sqlite3_memory_used()]
  1690. ** <li> [sqlite3_memory_highwater()]
  1691. ** <li> [sqlite3_soft_heap_limit()]
  1692. ** <li> [sqlite3_status()]
  1693. ** </ul>
  1694. ** </dd>
  1695. **
  1696. ** <dt>SQLITE_CONFIG_SCRATCH</dt>
  1697. ** <dd>This option specifies a static memory buffer that SQLite can use for
  1698. ** scratch memory. There are three arguments: A pointer to the memory, the
  1699. ** size of each scratch buffer (sz), and the number of buffers (N). The sz
  1700. ** argument must be a multiple of 16. The sz parameter should be a few bytes
  1701. ** larger than the actual scratch space required due internal overhead.
  1702. ** The first
  1703. ** argument should point to an allocation of at least sz*N bytes of memory.
  1704. ** SQLite will use no more than one scratch buffer at once per thread, so
  1705. ** N should be set to the expected maximum number of threads. The sz
  1706. ** parameter should be 6 times the size of the largest database page size.
  1707. ** Scratch buffers are used as part of the btree balance operation. If
  1708. ** The btree balancer needs additional memory beyond what is provided by
  1709. ** scratch buffers or if no scratch buffer space is specified, then SQLite
  1710. ** goes to [sqlite3_malloc()] to obtain the memory it needs.</dd>
  1711. **
  1712. ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1713. ** <dd>This option specifies a static memory buffer that SQLite can use for
  1714. ** the database page cache with the default page cache implemenation.
  1715. ** This configuration should not be used if an application-define page
  1716. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
  1717. ** There are three arguments to this option: A pointer to the
  1718. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1719. ** The sz argument must be a power of two between 512 and 32768. The first
  1720. ** argument should point to an allocation of at least sz*N bytes of memory.
  1721. ** SQLite will use the memory provided by the first argument to satisfy its
  1722. ** memory needs for the first N pages that it adds to cache. If additional
  1723. ** page cache memory is needed beyond what is provided by this option, then
  1724. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1725. ** The implementation might use one or more of the N buffers to hold
  1726. ** memory accounting information. </dd>
  1727. **
  1728. ** <dt>SQLITE_CONFIG_HEAP</dt>
  1729. ** <dd>This option specifies a static memory buffer that SQLite will use
  1730. ** for all of its dynamic memory allocation needs beyond those provided
  1731. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1732. ** There are three arguments: A pointer to the memory, the number of
  1733. ** bytes in the memory buffer, and the minimum allocation size. If
  1734. ** the first pointer (the memory pointer) is NULL, then SQLite reverts
  1735. ** to using its default memory allocator (the system malloc() implementation),
  1736. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. If the
  1737. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1738. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1739. ** allocator is engaged to handle all of SQLites memory allocation needs.</dd>
  1740. **
  1741. ** <dt>SQLITE_CONFIG_MUTEX</dt>
  1742. ** <dd>This option takes a single argument which is a pointer to an
  1743. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  1744. ** alternative low-level mutex routines to be used in place
  1745. ** the mutex routines built into SQLite.</dd>
  1746. **
  1747. ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1748. ** <dd>This option takes a single argument which is a pointer to an
  1749. ** instance of the [sqlite3_mutex_methods] structure. The
  1750. ** [sqlite3_mutex_methods]
  1751. ** structure is filled with the currently defined mutex routines.
  1752. ** This option can be used to overload the default mutex allocation
  1753. ** routines with a wrapper used to track mutex usage for performance
  1754. ** profiling or testing, for example.</dd>
  1755. **
  1756. ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1757. ** <dd>This option takes two arguments that determine the default
  1758. ** memory allcation lookaside optimization. The first argument is the
  1759. ** size of each lookaside buffer slot and the second is the number of
  1760. ** slots allocated to each database connection.</dd>
  1761. **
  1762. ** <dt>SQLITE_CONFIG_PCACHE</dt>
  1763. ** <dd>This option takes a single argument which is a pointer to
  1764. ** an [sqlite3_pcache_methods] object. This object specifies the interface
  1765. ** to a custom page cache implementation. SQLite makes a copy of the
  1766. ** object and uses it for page cache memory allocations.</dd>
  1767. **
  1768. ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
  1769. ** <dd>This option takes a single argument which is a pointer to an
  1770. ** [sqlite3_pcache_methods] object. SQLite copies of the current
  1771. ** page cache implementation into that object.</dd>
  1772. **
  1773. ** </dl>
  1774. */
  1775. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1776. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1777. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1778. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1779. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1780. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1781. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1782. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1783. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1784. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1785. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1786. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1787. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1788. #define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */
  1789. #define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */
  1790. /*
  1791. ** CAPI3REF: Configuration Options {H10170} <S20000>
  1792. ** EXPERIMENTAL
  1793. **
  1794. ** These constants are the available integer configuration options that
  1795. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1796. **
  1797. ** New configuration options may be added in future releases of SQLite.
  1798. ** Existing configuration options might be discontinued. Applications
  1799. ** should check the return code from [sqlite3_db_config()] to make sure that
  1800. ** the call worked. The [sqlite3_db_config()] interface will return a
  1801. ** non-zero [error code] if a discontinued or unsupported configuration option
  1802. ** is invoked.
  1803. **
  1804. ** <dl>
  1805. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1806. ** <dd>This option takes three additional arguments that determine the
  1807. ** [lookaside memory allocator] configuration for the [database connection].
  1808. ** The first argument (the third parameter to [sqlite3_db_config()] is a
  1809. ** pointer to a memory buffer to use for lookaside memory. The first
  1810. ** argument may be NULL in which case SQLite will allocate the lookaside
  1811. ** buffer itself using [sqlite3_malloc()]. The second argument is the
  1812. ** size of each lookaside buffer slot and the third argument is the number of
  1813. ** slots. The size of the buffer in the first argument must be greater than
  1814. ** or equal to the product of the second and third arguments.</dd>
  1815. **
  1816. ** </dl>
  1817. */
  1818. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  1819. /*
  1820. ** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} <S10700>
  1821. **
  1822. ** The sqlite3_extended_result_codes() routine enables or disables the
  1823. ** [extended result codes] feature of SQLite. The extended result
  1824. ** codes are disabled by default for historical compatibility considerations.
  1825. **
  1826. ** INVARIANTS:
  1827. **
  1828. ** {H12201} Each new [database connection] shall have the
  1829. ** [extended result codes] feature disabled by default.
  1830. **
  1831. ** {H12202} The [sqlite3_extended_result_codes(D,F)] interface shall enable
  1832. ** [extended result codes] for the [database connection] D
  1833. ** if the F parameter is true, or disable them if F is false.
  1834. */
  1835. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  1836. /*
  1837. ** CAPI3REF: Last Insert Rowid {H12220} <S10700>
  1838. **
  1839. ** Each entry in an SQLite table has a unique 64-bit signed
  1840. ** integer key called the [ROWID | "rowid"]. The rowid is always available
  1841. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  1842. ** names are not also used by explicitly declared columns. If
  1843. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  1844. ** is another alias for the rowid.
  1845. **
  1846. ** This routine returns the [rowid] of the most recent
  1847. ** successful [INSERT] into the database from the [database connection]
  1848. ** in the first argument. If no successful [INSERT]s
  1849. ** have ever occurred on that database connection, zero is returned.
  1850. **
  1851. ** If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
  1852. ** row is returned by this routine as long as the trigger is running.
  1853. ** But once the trigger terminates, the value returned by this routine
  1854. ** reverts to the last value inserted before the trigger fired.
  1855. **
  1856. ** An [INSERT] that fails due to a constraint violation is not a
  1857. ** successful [INSERT] and does not change the value returned by this
  1858. ** routine. Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  1859. ** and INSERT OR ABORT make no changes to the return value of this
  1860. ** routine when their insertion fails. When INSERT OR REPLACE
  1861. ** encounters a constraint violation, it does not fail. The
  1862. ** INSERT continues to completion after deleting rows that caused
  1863. ** the constraint problem so INSERT OR REPLACE will always change
  1864. ** the return value of this interface.
  1865. **
  1866. ** For the purposes of this routine, an [INSERT] is considered to
  1867. ** be successful even if it is subsequently rolled back.
  1868. **
  1869. ** INVARIANTS:
  1870. **
  1871. ** {H12221} The [sqlite3_last_insert_rowid()] function shall return
  1872. ** the [rowid]
  1873. ** of the most recent successful [INSERT] performed on the same
  1874. ** [database connection] and within the same or higher level
  1875. ** trigger context, or zero if there have been no qualifying
  1876. ** [INSERT] statements.
  1877. **
  1878. ** {H12223} The [sqlite3_last_insert_rowid()] function shall return the
  1879. ** same value when called from the same trigger context
  1880. ** immediately before and after a [ROLLBACK].
  1881. **
  1882. ** ASSUMPTIONS:
  1883. **
  1884. ** {A12232} If a separate thread performs a new [INSERT] on the same
  1885. ** database connection while the [sqlite3_last_insert_rowid()]
  1886. ** function is running and thus changes the last insert [rowid],
  1887. ** then the value returned by [sqlite3_last_insert_rowid()] is
  1888. ** unpredictable and might not equal either the old or the new
  1889. ** last insert [rowid].
  1890. */
  1891. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  1892. /*
  1893. ** CAPI3REF: Count The Number Of Rows Modified {H12240} <S10600>
  1894. **
  1895. ** This function returns the number of database rows that were changed
  1896. ** or inserted or deleted by the most recently completed SQL statement
  1897. ** on the [database connection] specified by the first parameter.
  1898. ** Only changes that are directly specified by the [INSERT], [UPDATE],
  1899. ** or [DELETE] statement are counted. Auxiliary changes caused by
  1900. ** triggers are not counted. Use the [sqlite3_total_changes()] function
  1901. ** to find the total number of changes including changes caused by triggers.
  1902. **
  1903. ** A "row change" is a change to a single row of a single table
  1904. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  1905. ** are changed as side effects of REPLACE constraint resolution,
  1906. ** rollback, ABORT processing, DROP TABLE, or by any other
  1907. ** mechanisms do not count as direct row changes.
  1908. **
  1909. ** A "trigger context" is a scope of execution that begins and
  1910. ** ends with the script of a trigger. Most SQL statements are
  1911. ** evaluated outside of any trigger. This is the "top level"
  1912. ** trigger context. If a trigger fires from the top level, a
  1913. ** new trigger context is entered for the duration of that one
  1914. ** trigger. Subtriggers create subcontexts for their duration.
  1915. **
  1916. ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  1917. ** not create a new trigger context.
  1918. **
  1919. ** This function returns the number of direct row changes in the
  1920. ** most recent INSERT, UPDATE, or DELETE statement within the same
  1921. ** trigger context.
  1922. **
  1923. ** Thus, when called from the top level, this function returns the
  1924. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  1925. ** that also occurred at the top level. Within the body of a trigger,
  1926. ** the sqlite3_changes() interface can be called to find the number of
  1927. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  1928. ** statement within the body of the same trigger.
  1929. ** However, the number returned does not include changes
  1930. ** caused by subtriggers since those have their own context.
  1931. **
  1932. ** SQLite implements the command "DELETE FROM table" without a WHERE clause
  1933. ** by dropping and recreating the table. Doing so is much faster than going
  1934. ** through and deleting individual elements from the table. Because of this
  1935. ** optimization, the deletions in "DELETE FROM table" are not row changes and
  1936. ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
  1937. ** functions, regardless of the number of elements that were originally
  1938. ** in the table. To get an accurate count of the number of rows deleted, use
  1939. ** "DELETE FROM table WHERE 1" instead. Or recompile using the
  1940. ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
  1941. ** optimization on all queries.
  1942. **
  1943. ** INVARIANTS:
  1944. **
  1945. ** {H12241} The [sqlite3_changes()] function shall return the number of
  1946. ** row changes caused by the most recent INSERT, UPDATE,
  1947. ** or DELETE statement on the same database connection and
  1948. ** within the same or higher trigger context, or zero if there have
  1949. ** not been any qualifying row changes.
  1950. **
  1951. ** {H12243} Statements of the form "DELETE FROM tablename" with no
  1952. ** WHERE clause shall cause subsequent calls to
  1953. ** [sqlite3_changes()] to return zero, regardless of the
  1954. ** number of rows originally in the table.
  1955. **
  1956. ** ASSUMPTIONS:
  1957. **
  1958. ** {A12252} If a separate thread makes changes on the same database connection
  1959. ** while [sqlite3_changes()] is running then the value returned
  1960. ** is unpredictable and not meaningful.
  1961. */
  1962. SQLITE_API int sqlite3_changes(sqlite3*);
  1963. /*
  1964. ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
  1965. **
  1966. ** This function returns the number of row changes caused by INSERT,
  1967. ** UPDATE or DELETE statements since the [database connection] was opened.
  1968. ** The count includes all changes from all trigger contexts. However,
  1969. ** the count does not include changes used to implement REPLACE constraints,
  1970. ** do rollbacks or ABORT processing, or DROP table processing.
  1971. ** The changes are counted as soon as the statement that makes them is
  1972. ** completed (when the statement handle is passed to [sqlite3_reset()] or
  1973. ** [sqlite3_finalize()]).
  1974. **
  1975. ** SQLite implements the command "DELETE FROM table" without a WHERE clause
  1976. ** by dropping and recreating the table. (This is much faster than going
  1977. ** through and deleting individual elements from the table.) Because of this
  1978. ** optimization, the deletions in "DELETE FROM table" are not row changes and
  1979. ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
  1980. ** functions, regardless of the number of elements that were originally
  1981. ** in the table. To get an accurate count of the number of rows deleted, use
  1982. ** "DELETE FROM table WHERE 1" instead. Or recompile using the
  1983. ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
  1984. ** optimization on all queries.
  1985. **
  1986. ** See also the [sqlite3_changes()] interface.
  1987. **
  1988. ** INVARIANTS:
  1989. **
  1990. ** {H12261} The [sqlite3_total_changes()] returns the total number
  1991. ** of row changes caused by INSERT, UPDATE, and/or DELETE
  1992. ** statements on the same [database connection], in any
  1993. ** trigger context, since the database connection was created.
  1994. **
  1995. ** {H12263} Statements of the form "DELETE FROM tablename" with no
  1996. ** WHERE clause shall not change the value returned
  1997. ** by [sqlite3_total_changes()].
  1998. **
  1999. ** ASSUMPTIONS:
  2000. **
  2001. ** {A12264} If a separate thread makes changes on the same database connection
  2002. ** while [sqlite3_total_changes()] is running then the value
  2003. ** returned is unpredictable and not meaningful.
  2004. */
  2005. SQLITE_API int sqlite3_total_changes(sqlite3*);
  2006. /*
  2007. ** CAPI3REF: Interrupt A Long-Running Query {H12270} <S30500>
  2008. **
  2009. ** This function causes any pending database operation to abort and
  2010. ** return at its earliest opportunity. This routine is typically
  2011. ** called in response to a user action such as pressing "Cancel"
  2012. ** or Ctrl-C where the user wants a long query operation to halt
  2013. ** immediately.
  2014. **
  2015. ** It is safe to call this routine from a thread different from the
  2016. ** thread that is currently running the database operation. But it
  2017. ** is not safe to call this routine with a [database connection] that
  2018. ** is closed or might close before sqlite3_interrupt() returns.
  2019. **
  2020. ** If an SQL operation is very nearly finished at the time when
  2021. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2022. ** to be interrupted and might continue to completion.
  2023. **
  2024. ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2025. ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2026. ** that is inside an explicit transaction, then the entire transaction
  2027. ** will be rolled back automatically.
  2028. **
  2029. ** A call to sqlite3_interrupt() has no effect on SQL statements
  2030. ** that are started after sqlite3_interrupt() returns.
  2031. **
  2032. ** INVARIANTS:
  2033. **
  2034. ** {H12271} The [sqlite3_interrupt()] interface will force all running
  2035. ** SQL statements associated with the same database connection
  2036. ** to halt after processing at most one additional row of data.
  2037. **
  2038. ** {H12272} Any SQL statement that is interrupted by [sqlite3_interrupt()]
  2039. ** will return [SQLITE_INTERRUPT].
  2040. **
  2041. ** ASSUMPTIONS:
  2042. **
  2043. ** {A12279} If the database connection closes while [sqlite3_interrupt()]
  2044. ** is running then bad things will likely happen.
  2045. */
  2046. SQLITE_API void sqlite3_interrupt(sqlite3*);
  2047. /*
  2048. ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
  2049. **
  2050. ** These routines are useful for command-line input to determine if the
  2051. ** currently entered text seems to form complete a SQL statement or
  2052. ** if additional input is needed before sending the text into
  2053. ** SQLite for parsing. These routines return true if the input string
  2054. ** appears to be a complete SQL statement. A statement is judged to be
  2055. ** complete if it ends with a semicolon token and is not a fragment of a
  2056. ** CREATE TRIGGER statement. Semicolons that are embedded within
  2057. ** string literals or quoted identifier names or comments are not
  2058. ** independent tokens (they are part of the token in which they are
  2059. ** embedded) and thus do not count as a statement terminator.
  2060. **
  2061. ** These routines do not parse the SQL statements thus
  2062. ** will not detect syntactically incorrect SQL.
  2063. **
  2064. ** INVARIANTS:
  2065. **
  2066. ** {H10511} A successful evaluation of [sqlite3_complete()] or
  2067. ** [sqlite3_complete16()] functions shall
  2068. ** return a numeric 1 if and only if the last non-whitespace
  2069. ** token in their input is a semicolon that is not in between
  2070. ** the BEGIN and END of a CREATE TRIGGER statement.
  2071. **
  2072. ** {H10512} If a memory allocation error occurs during an invocation
  2073. ** of [sqlite3_complete()] or [sqlite3_complete16()] then the
  2074. ** routine shall return [SQLITE_NOMEM].
  2075. **
  2076. ** ASSUMPTIONS:
  2077. **
  2078. ** {A10512} The input to [sqlite3_complete()] must be a zero-terminated
  2079. ** UTF-8 string.
  2080. **
  2081. ** {A10513} The input to [sqlite3_complete16()] must be a zero-terminated
  2082. ** UTF-16 string in native byte order.
  2083. */
  2084. SQLITE_API int sqlite3_complete(const char *sql);
  2085. SQLITE_API int sqlite3_complete16(const void *sql);
  2086. /*
  2087. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} <S40400>
  2088. **
  2089. ** This routine sets a callback function that might be invoked whenever
  2090. ** an attempt is made to open a database table that another thread
  2091. ** or process has locked.
  2092. **
  2093. ** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  2094. ** is returned immediately upon encountering the lock. If the busy callback
  2095. ** is not NULL, then the callback will be invoked with two arguments.
  2096. **
  2097. ** The first argument to the handler is a copy of the void* pointer which
  2098. ** is the third argument to sqlite3_busy_handler(). The second argument to
  2099. ** the handler callback is the number of times that the busy handler has
  2100. ** been invoked for this locking event. If the
  2101. ** busy callback returns 0, then no additional attempts are made to
  2102. ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  2103. ** If the callback returns non-zero, then another attempt
  2104. ** is made to open the database for reading and the cycle repeats.
  2105. **
  2106. ** The presence of a busy handler does not guarantee that it will be invoked
  2107. ** when there is lock contention. If SQLite determines that invoking the busy
  2108. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2109. ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  2110. ** Consider a scenario where one process is holding a read lock that
  2111. ** it is trying to promote to a reserved lock and
  2112. ** a second process is holding a reserved lock that it is trying
  2113. ** to promote to an exclusive lock. The first process cannot proceed
  2114. ** because it is blocked by the second and the second process cannot
  2115. ** proceed because it is blocked by the first. If both processes
  2116. ** invoke the busy handlers, neither will make any progress. Therefore,
  2117. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2118. ** will induce the first process to release its read lock and allow
  2119. ** the second process to proceed.
  2120. **
  2121. ** The default busy callback is NULL.
  2122. **
  2123. ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  2124. ** when SQLite is in the middle of a large transaction where all the
  2125. ** changes will not fit into the in-memory cache. SQLite will
  2126. ** already hold a RESERVED lock on the database file, but it needs
  2127. ** to promote this lock to EXCLUSIVE so that it can spill cache
  2128. ** pages into the database file without harm to concurrent
  2129. ** readers. If it is unable to promote the lock, then the in-memory
  2130. ** cache will be left in an inconsistent state and so the error
  2131. ** code is promoted from the relatively benign [SQLITE_BUSY] to
  2132. ** the more severe [SQLITE_IOERR_BLOCKED]. This error code promotion
  2133. ** forces an automatic rollback of the changes. See the
  2134. ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  2135. ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  2136. ** this is important.
  2137. **
  2138. ** There can only be a single busy handler defined for each
  2139. ** [database connection]. Setting a new busy handler clears any
  2140. ** previously set handler. Note that calling [sqlite3_busy_timeout()]
  2141. ** will also set or clear the busy handler.
  2142. **
  2143. ** The busy callback should not take any actions which modify the
  2144. ** database connection that invoked the busy handler. Any such actions
  2145. ** result in undefined behavior.
  2146. **
  2147. ** INVARIANTS:
  2148. **
  2149. ** {H12311} The [sqlite3_busy_handler(D,C,A)] function shall replace
  2150. ** busy callback in the [database connection] D with a new
  2151. ** a new busy handler C and application data pointer A.
  2152. **
  2153. ** {H12312} Newly created [database connections] shall have a busy
  2154. ** handler of NULL.
  2155. **
  2156. ** {H12314} When two or more [database connections] share a
  2157. ** [sqlite3_enable_shared_cache | common cache],
  2158. ** the busy handler for the database connection currently using
  2159. ** the cache shall be invoked when the cache encounters a lock.
  2160. **
  2161. ** {H12316} If a busy handler callback returns zero, then the SQLite interface
  2162. ** that provoked the locking event shall return [SQLITE_BUSY].
  2163. **
  2164. ** {H12318} SQLite shall invokes the busy handler with two arguments which
  2165. ** are a copy of the pointer supplied by the 3rd parameter to
  2166. ** [sqlite3_busy_handler()] and a count of the number of prior
  2167. ** invocations of the busy handler for the same locking event.
  2168. **
  2169. ** ASSUMPTIONS:
  2170. **
  2171. ** {A12319} A busy handler must not close the database connection
  2172. ** or [prepared statement] that invoked the busy handler.
  2173. */
  2174. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2175. /*
  2176. ** CAPI3REF: Set A Busy Timeout {H12340} <S40410>
  2177. **
  2178. ** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2179. ** for a specified amount of time when a table is locked. The handler
  2180. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2181. ** have accumulated. {H12343} After "ms" milliseconds of sleeping,
  2182. ** the handler returns 0 which causes [sqlite3_step()] to return
  2183. ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  2184. **
  2185. ** Calling this routine with an argument less than or equal to zero
  2186. ** turns off all busy handlers.
  2187. **
  2188. ** There can only be a single busy handler for a particular
  2189. ** [database connection] any any given moment. If another busy handler
  2190. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2191. ** this routine, that other busy handler is cleared.
  2192. **
  2193. ** INVARIANTS:
  2194. **
  2195. ** {H12341} The [sqlite3_busy_timeout()] function shall override any prior
  2196. ** [sqlite3_busy_timeout()] or [sqlite3_busy_handler()] setting
  2197. ** on the same [database connection].
  2198. **
  2199. ** {H12343} If the 2nd parameter to [sqlite3_busy_timeout()] is less than
  2200. ** or equal to zero, then the busy handler shall be cleared so that
  2201. ** all subsequent locking events immediately return [SQLITE_BUSY].
  2202. **
  2203. ** {H12344} If the 2nd parameter to [sqlite3_busy_timeout()] is a positive
  2204. ** number N, then a busy handler shall be set that repeatedly calls
  2205. ** the xSleep() method in the [sqlite3_vfs | VFS interface] until
  2206. ** either the lock clears or until the cumulative sleep time
  2207. ** reported back by xSleep() exceeds N milliseconds.
  2208. */
  2209. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2210. /*
  2211. ** CAPI3REF: Convenience Routines For Running Queries {H12370} <S10000>
  2212. **
  2213. ** Definition: A <b>result table</b> is memory data structure created by the
  2214. ** [sqlite3_get_table()] interface. A result table records the
  2215. ** complete query results from one or more queries.
  2216. **
  2217. ** The table conceptually has a number of rows and columns. But
  2218. ** these numbers are not part of the result table itself. These
  2219. ** numbers are obtained separately. Let N be the number of rows
  2220. ** and M be the number of columns.
  2221. **
  2222. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2223. ** There are (N+1)*M elements in the array. The first M pointers point
  2224. ** to zero-terminated strings that contain the names of the columns.
  2225. ** The remaining entries all point to query results. NULL values result
  2226. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2227. ** string representation as returned by [sqlite3_column_text()].
  2228. **
  2229. ** A result table might consist of one or more memory allocations.
  2230. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2231. ** A result table should be deallocated using [sqlite3_free_table()].
  2232. **
  2233. ** As an example of the result table format, suppose a query result
  2234. ** is as follows:
  2235. **
  2236. ** <blockquote><pre>
  2237. ** Name | Age
  2238. ** -----------------------
  2239. ** Alice | 43
  2240. ** Bob | 28
  2241. ** Cindy | 21
  2242. ** </pre></blockquote>
  2243. **
  2244. ** There are two column (M==2) and three rows (N==3). Thus the
  2245. ** result table has 8 entries. Suppose the result table is stored
  2246. ** in an array names azResult. Then azResult holds this content:
  2247. **
  2248. ** <blockquote><pre>
  2249. ** azResult&#91;0] = "Name";
  2250. ** azResult&#91;1] = "Age";
  2251. ** azResult&#91;2] = "Alice";
  2252. ** azResult&#91;3] = "43";
  2253. ** azResult&#91;4] = "Bob";
  2254. ** azResult&#91;5] = "28";
  2255. ** azResult&#91;6] = "Cindy";
  2256. ** azResult&#91;7] = "21";
  2257. ** </pre></blockquote>
  2258. **
  2259. ** The sqlite3_get_table() function evaluates one or more
  2260. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2261. ** string of its 2nd parameter. It returns a result table to the
  2262. ** pointer given in its 3rd parameter.
  2263. **
  2264. ** After the calling function has finished using the result, it should
  2265. ** pass the pointer to the result table to sqlite3_free_table() in order to
  2266. ** release the memory that was malloced. Because of the way the
  2267. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2268. ** function must not try to call [sqlite3_free()] directly. Only
  2269. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2270. **
  2271. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2272. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2273. ** to any internal data structures of SQLite. It uses only the public
  2274. ** interface defined here. As a consequence, errors that occur in the
  2275. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2276. ** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()].
  2277. **
  2278. ** INVARIANTS:
  2279. **
  2280. ** {H12371} If a [sqlite3_get_table()] fails a memory allocation, then
  2281. ** it shall free the result table under construction, abort the
  2282. ** query in process, skip any subsequent queries, set the
  2283. ** *pazResult output pointer to NULL and return [SQLITE_NOMEM].
  2284. **
  2285. ** {H12373} If the pnColumn parameter to [sqlite3_get_table()] is not NULL
  2286. ** then a successful invocation of [sqlite3_get_table()] shall
  2287. ** write the number of columns in the
  2288. ** result set of the query into *pnColumn.
  2289. **
  2290. ** {H12374} If the pnRow parameter to [sqlite3_get_table()] is not NULL
  2291. ** then a successful invocation of [sqlite3_get_table()] shall
  2292. ** writes the number of rows in the
  2293. ** result set of the query into *pnRow.
  2294. **
  2295. ** {H12376} A successful invocation of [sqlite3_get_table()] that computes
  2296. ** N rows of result with C columns per row shall make *pazResult
  2297. ** point to an array of pointers to (N+1)*C strings where the first
  2298. ** C strings are column names as obtained from
  2299. ** [sqlite3_column_name()] and the rest are column result values
  2300. ** obtained from [sqlite3_column_text()].
  2301. **
  2302. ** {H12379} The values in the pazResult array returned by [sqlite3_get_table()]
  2303. ** shall remain valid until cleared by [sqlite3_free_table()].
  2304. **
  2305. ** {H12382} When an error occurs during evaluation of [sqlite3_get_table()]
  2306. ** the function shall set *pazResult to NULL, write an error message
  2307. ** into memory obtained from [sqlite3_malloc()], make
  2308. ** **pzErrmsg point to that error message, and return a
  2309. ** appropriate [error code].
  2310. */
  2311. SQLITE_API int sqlite3_get_table(
  2312. sqlite3 *db, /* An open database */
  2313. const char *zSql, /* SQL to be evaluated */
  2314. char ***pazResult, /* Results of the query */
  2315. int *pnRow, /* Number of result rows written here */
  2316. int *pnColumn, /* Number of result columns written here */
  2317. char **pzErrmsg /* Error msg written here */
  2318. );
  2319. SQLITE_API void sqlite3_free_table(char **result);
  2320. /*
  2321. ** CAPI3REF: Formatted String Printing Functions {H17400} <S70000><S20000>
  2322. **
  2323. ** These routines are workalikes of the "printf()" family of functions
  2324. ** from the standard C library.
  2325. **
  2326. ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2327. ** results into memory obtained from [sqlite3_malloc()].
  2328. ** The strings returned by these two routines should be
  2329. ** released by [sqlite3_free()]. Both routines return a
  2330. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2331. ** memory to hold the resulting string.
  2332. **
  2333. ** In sqlite3_snprintf() routine is similar to "snprintf()" from
  2334. ** the standard C library. The result is written into the
  2335. ** buffer supplied as the second parameter whose size is given by
  2336. ** the first parameter. Note that the order of the
  2337. ** first two parameters is reversed from snprintf(). This is an
  2338. ** historical accident that cannot be fixed without breaking
  2339. ** backwards compatibility. Note also that sqlite3_snprintf()
  2340. ** returns a pointer to its buffer instead of the number of
  2341. ** characters actually written into the buffer. We admit that
  2342. ** the number of characters written would be a more useful return
  2343. ** value but we cannot change the implementation of sqlite3_snprintf()
  2344. ** now without breaking compatibility.
  2345. **
  2346. ** As long as the buffer size is greater than zero, sqlite3_snprintf()
  2347. ** guarantees that the buffer is always zero-terminated. The first
  2348. ** parameter "n" is the total size of the buffer, including space for
  2349. ** the zero terminator. So the longest string that can be completely
  2350. ** written will be n-1 characters.
  2351. **
  2352. ** These routines all implement some additional formatting
  2353. ** options that are useful for constructing SQL statements.
  2354. ** All of the usual printf() formatting options apply. In addition, there
  2355. ** is are "%q", "%Q", and "%z" options.
  2356. **
  2357. ** The %q option works like %s in that it substitutes a null-terminated
  2358. ** string from the argument list. But %q also doubles every '\'' character.
  2359. ** %q is designed for use inside a string literal. By doubling each '\''
  2360. ** character it escapes that character and allows it to be inserted into
  2361. ** the string.
  2362. **
  2363. ** For example, assume the string variable zText contains text as follows:
  2364. **
  2365. ** <blockquote><pre>
  2366. ** char *zText = "It's a happy day!";
  2367. ** </pre></blockquote>
  2368. **
  2369. ** One can use this text in an SQL statement as follows:
  2370. **
  2371. ** <blockquote><pre>
  2372. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2373. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2374. ** sqlite3_free(zSQL);
  2375. ** </pre></blockquote>
  2376. **
  2377. ** Because the %q format string is used, the '\'' character in zText
  2378. ** is escaped and the SQL generated is as follows:
  2379. **
  2380. ** <blockquote><pre>
  2381. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2382. ** </pre></blockquote>
  2383. **
  2384. ** This is correct. Had we used %s instead of %q, the generated SQL
  2385. ** would have looked like this:
  2386. **
  2387. ** <blockquote><pre>
  2388. ** INSERT INTO table1 VALUES('It's a happy day!');
  2389. ** </pre></blockquote>
  2390. **
  2391. ** This second example is an SQL syntax error. As a general rule you should
  2392. ** always use %q instead of %s when inserting text into a string literal.
  2393. **
  2394. ** The %Q option works like %q except it also adds single quotes around
  2395. ** the outside of the total string. Additionally, if the parameter in the
  2396. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2397. ** single quotes) in place of the %Q option. So, for example, one could say:
  2398. **
  2399. ** <blockquote><pre>
  2400. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2401. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2402. ** sqlite3_free(zSQL);
  2403. ** </pre></blockquote>
  2404. **
  2405. ** The code above will render a correct SQL statement in the zSQL
  2406. ** variable even if the zText variable is a NULL pointer.
  2407. **
  2408. ** The "%z" formatting option works exactly like "%s" with the
  2409. ** addition that after the string has been read and copied into
  2410. ** the result, [sqlite3_free()] is called on the input string. {END}
  2411. **
  2412. ** INVARIANTS:
  2413. **
  2414. ** {H17403} The [sqlite3_mprintf()] and [sqlite3_vmprintf()] interfaces
  2415. ** return either pointers to zero-terminated UTF-8 strings held in
  2416. ** memory obtained from [sqlite3_malloc()] or NULL pointers if
  2417. ** a call to [sqlite3_malloc()] fails.
  2418. **
  2419. ** {H17406} The [sqlite3_snprintf()] interface writes a zero-terminated
  2420. ** UTF-8 string into the buffer pointed to by the second parameter
  2421. ** provided that the first parameter is greater than zero.
  2422. **
  2423. ** {H17407} The [sqlite3_snprintf()] interface does not write slots of
  2424. ** its output buffer (the second parameter) outside the range
  2425. ** of 0 through N-1 (where N is the first parameter)
  2426. ** regardless of the length of the string
  2427. ** requested by the format specification.
  2428. */
  2429. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2430. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2431. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2432. /*
  2433. ** CAPI3REF: Memory Allocation Subsystem {H17300} <S20000>
  2434. **
  2435. ** The SQLite core uses these three routines for all of its own
  2436. ** internal memory allocation needs. "Core" in the previous sentence
  2437. ** does not include operating-system specific VFS implementation. The
  2438. ** Windows VFS uses native malloc() and free() for some operations.
  2439. **
  2440. ** The sqlite3_malloc() routine returns a pointer to a block
  2441. ** of memory at least N bytes in length, where N is the parameter.
  2442. ** If sqlite3_malloc() is unable to obtain sufficient free
  2443. ** memory, it returns a NULL pointer. If the parameter N to
  2444. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2445. ** a NULL pointer.
  2446. **
  2447. ** Calling sqlite3_free() with a pointer previously returned
  2448. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2449. ** that it might be reused. The sqlite3_free() routine is
  2450. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2451. ** to sqlite3_free() is harmless. After being freed, memory
  2452. ** should neither be read nor written. Even reading previously freed
  2453. ** memory might result in a segmentation fault or other severe error.
  2454. ** Memory corruption, a segmentation fault, or other severe error
  2455. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2456. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2457. **
  2458. ** The sqlite3_realloc() interface attempts to resize a
  2459. ** prior memory allocation to be at least N bytes, where N is the
  2460. ** second parameter. The memory allocation to be resized is the first
  2461. ** parameter. If the first parameter to sqlite3_realloc()
  2462. ** is a NULL pointer then its behavior is identical to calling
  2463. ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  2464. ** If the second parameter to sqlite3_realloc() is zero or
  2465. ** negative then the behavior is exactly the same as calling
  2466. ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  2467. ** sqlite3_realloc() returns a pointer to a memory allocation
  2468. ** of at least N bytes in size or NULL if sufficient memory is unavailable.
  2469. ** If M is the size of the prior allocation, then min(N,M) bytes
  2470. ** of the prior allocation are copied into the beginning of buffer returned
  2471. ** by sqlite3_realloc() and the prior allocation is freed.
  2472. ** If sqlite3_realloc() returns NULL, then the prior allocation
  2473. ** is not freed.
  2474. **
  2475. ** The memory returned by sqlite3_malloc() and sqlite3_realloc()
  2476. ** is always aligned to at least an 8 byte boundary. {END}
  2477. **
  2478. ** The default implementation of the memory allocation subsystem uses
  2479. ** the malloc(), realloc() and free() provided by the standard C library.
  2480. ** {H17382} However, if SQLite is compiled with the
  2481. ** SQLITE_MEMORY_SIZE=<i>NNN</i> C preprocessor macro (where <i>NNN</i>
  2482. ** is an integer), then SQLite create a static array of at least
  2483. ** <i>NNN</i> bytes in size and uses that array for all of its dynamic
  2484. ** memory allocation needs. {END} Additional memory allocator options
  2485. ** may be added in future releases.
  2486. **
  2487. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2488. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2489. ** implementation of these routines to be omitted. That capability
  2490. ** is no longer provided. Only built-in memory allocators can be used.
  2491. **
  2492. ** The Windows OS interface layer calls
  2493. ** the system malloc() and free() directly when converting
  2494. ** filenames between the UTF-8 encoding used by SQLite
  2495. ** and whatever filename encoding is used by the particular Windows
  2496. ** installation. Memory allocation errors are detected, but
  2497. ** they are reported back as [SQLITE_CANTOPEN] or
  2498. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2499. **
  2500. ** INVARIANTS:
  2501. **
  2502. ** {H17303} The [sqlite3_malloc(N)] interface returns either a pointer to
  2503. ** a newly checked-out block of at least N bytes of memory
  2504. ** that is 8-byte aligned, or it returns NULL if it is unable
  2505. ** to fulfill the request.
  2506. **
  2507. ** {H17304} The [sqlite3_malloc(N)] interface returns a NULL pointer if
  2508. ** N is less than or equal to zero.
  2509. **
  2510. ** {H17305} The [sqlite3_free(P)] interface releases memory previously
  2511. ** returned from [sqlite3_malloc()] or [sqlite3_realloc()],
  2512. ** making it available for reuse.
  2513. **
  2514. ** {H17306} A call to [sqlite3_free(NULL)] is a harmless no-op.
  2515. **
  2516. ** {H17310} A call to [sqlite3_realloc(0,N)] is equivalent to a call
  2517. ** to [sqlite3_malloc(N)].
  2518. **
  2519. ** {H17312} A call to [sqlite3_realloc(P,0)] is equivalent to a call
  2520. ** to [sqlite3_free(P)].
  2521. **
  2522. ** {H17315} The SQLite core uses [sqlite3_malloc()], [sqlite3_realloc()],
  2523. ** and [sqlite3_free()] for all of its memory allocation and
  2524. ** deallocation needs.
  2525. **
  2526. ** {H17318} The [sqlite3_realloc(P,N)] interface returns either a pointer
  2527. ** to a block of checked-out memory of at least N bytes in size
  2528. ** that is 8-byte aligned, or a NULL pointer.
  2529. **
  2530. ** {H17321} When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
  2531. ** copies the first K bytes of content from P into the newly
  2532. ** allocated block, where K is the lesser of N and the size of
  2533. ** the buffer P.
  2534. **
  2535. ** {H17322} When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
  2536. ** releases the buffer P.
  2537. **
  2538. ** {H17323} When [sqlite3_realloc(P,N)] returns NULL, the buffer P is
  2539. ** not modified or released.
  2540. **
  2541. ** ASSUMPTIONS:
  2542. **
  2543. ** {A17350} The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2544. ** must be either NULL or else pointers obtained from a prior
  2545. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2546. ** not yet been released.
  2547. **
  2548. ** {A17351} The application must not read or write any part of
  2549. ** a block of memory after it has been released using
  2550. ** [sqlite3_free()] or [sqlite3_realloc()].
  2551. */
  2552. SQLITE_API void *sqlite3_malloc(int);
  2553. SQLITE_API void *sqlite3_realloc(void*, int);
  2554. SQLITE_API void sqlite3_free(void*);
  2555. /*
  2556. ** CAPI3REF: Memory Allocator Statistics {H17370} <S30210>
  2557. **
  2558. ** SQLite provides these two interfaces for reporting on the status
  2559. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2560. ** routines, which form the built-in memory allocation subsystem.
  2561. **
  2562. ** INVARIANTS:
  2563. **
  2564. ** {H17371} The [sqlite3_memory_used()] routine returns the number of bytes
  2565. ** of memory currently outstanding (malloced but not freed).
  2566. **
  2567. ** {H17373} The [sqlite3_memory_highwater()] routine returns the maximum
  2568. ** value of [sqlite3_memory_used()] since the high-water mark
  2569. ** was last reset.
  2570. **
  2571. ** {H17374} The values returned by [sqlite3_memory_used()] and
  2572. ** [sqlite3_memory_highwater()] include any overhead
  2573. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2574. ** but not overhead added by the any underlying system library
  2575. ** routines that [sqlite3_malloc()] may call.
  2576. **
  2577. ** {H17375} The memory high-water mark is reset to the current value of
  2578. ** [sqlite3_memory_used()] if and only if the parameter to
  2579. ** [sqlite3_memory_highwater()] is true. The value returned
  2580. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2581. ** prior to the reset.
  2582. */
  2583. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2584. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2585. /*
  2586. ** CAPI3REF: Pseudo-Random Number Generator {H17390} <S20000>
  2587. **
  2588. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2589. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2590. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2591. ** the build-in random() and randomblob() SQL functions. This interface allows
  2592. ** applications to access the same PRNG for other purposes.
  2593. **
  2594. ** A call to this routine stores N bytes of randomness into buffer P.
  2595. **
  2596. ** The first time this routine is invoked (either internally or by
  2597. ** the application) the PRNG is seeded using randomness obtained
  2598. ** from the xRandomness method of the default [sqlite3_vfs] object.
  2599. ** On all subsequent invocations, the pseudo-randomness is generated
  2600. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2601. ** method.
  2602. **
  2603. ** INVARIANTS:
  2604. **
  2605. ** {H17392} The [sqlite3_randomness(N,P)] interface writes N bytes of
  2606. ** high-quality pseudo-randomness into buffer P.
  2607. */
  2608. SQLITE_API void sqlite3_randomness(int N, void *P);
  2609. /*
  2610. ** CAPI3REF: Compile-Time Authorization Callbacks {H12500} <S70100>
  2611. **
  2612. ** This routine registers a authorizer callback with a particular
  2613. ** [database connection], supplied in the first argument.
  2614. ** The authorizer callback is invoked as SQL statements are being compiled
  2615. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2616. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. At various
  2617. ** points during the compilation process, as logic is being created
  2618. ** to perform various actions, the authorizer callback is invoked to
  2619. ** see if those actions are allowed. The authorizer callback should
  2620. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2621. ** specific action but allow the SQL statement to continue to be
  2622. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2623. ** rejected with an error. If the authorizer callback returns
  2624. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2625. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2626. ** the authorizer will fail with an error message.
  2627. **
  2628. ** When the callback returns [SQLITE_OK], that means the operation
  2629. ** requested is ok. When the callback returns [SQLITE_DENY], the
  2630. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2631. ** authorizer will fail with an error message explaining that
  2632. ** access is denied. If the authorizer code is [SQLITE_READ]
  2633. ** and the callback returns [SQLITE_IGNORE] then the
  2634. ** [prepared statement] statement is constructed to substitute
  2635. ** a NULL value in place of the table column that would have
  2636. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2637. ** return can be used to deny an untrusted user access to individual
  2638. ** columns of a table.
  2639. **
  2640. ** The first parameter to the authorizer callback is a copy of the third
  2641. ** parameter to the sqlite3_set_authorizer() interface. The second parameter
  2642. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2643. ** the particular action to be authorized. The third through sixth parameters
  2644. ** to the callback are zero-terminated strings that contain additional
  2645. ** details about the action to be authorized.
  2646. **
  2647. ** An authorizer is used when [sqlite3_prepare | preparing]
  2648. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2649. ** do not try to access data they are not allowed to see, or that they do not
  2650. ** try to execute malicious statements that damage the database. For
  2651. ** example, an application may allow a user to enter arbitrary
  2652. ** SQL queries for evaluation by a database. But the application does
  2653. ** not want the user to be able to make arbitrary changes to the
  2654. ** database. An authorizer could then be put in place while the
  2655. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2656. ** disallows everything except [SELECT] statements.
  2657. **
  2658. ** Applications that need to process SQL from untrusted sources
  2659. ** might also consider lowering resource limits using [sqlite3_limit()]
  2660. ** and limiting database size using the [max_page_count] [PRAGMA]
  2661. ** in addition to using an authorizer.
  2662. **
  2663. ** Only a single authorizer can be in place on a database connection
  2664. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2665. ** previous call. Disable the authorizer by installing a NULL callback.
  2666. ** The authorizer is disabled by default.
  2667. **
  2668. ** The authorizer callback must not do anything that will modify
  2669. ** the database connection that invoked the authorizer callback.
  2670. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2671. ** database connections for the meaning of "modify" in this paragraph.
  2672. **
  2673. ** When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2674. ** statement might be reprepared during [sqlite3_step()] due to a
  2675. ** schema change. Hence, the application should ensure that the
  2676. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2677. **
  2678. ** Note that the authorizer callback is invoked only during
  2679. ** [sqlite3_prepare()] or its variants. Authorization is not
  2680. ** performed during statement evaluation in [sqlite3_step()].
  2681. **
  2682. ** INVARIANTS:
  2683. **
  2684. ** {H12501} The [sqlite3_set_authorizer(D,...)] interface registers a
  2685. ** authorizer callback with database connection D.
  2686. **
  2687. ** {H12502} The authorizer callback is invoked as SQL statements are
  2688. ** being parseed and compiled.
  2689. **
  2690. ** {H12503} If the authorizer callback returns any value other than
  2691. ** [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY], then
  2692. ** the application interface call that caused
  2693. ** the authorizer callback to run shall fail with an
  2694. ** [SQLITE_ERROR] error code and an appropriate error message.
  2695. **
  2696. ** {H12504} When the authorizer callback returns [SQLITE_OK], the operation
  2697. ** described is processed normally.
  2698. **
  2699. ** {H12505} When the authorizer callback returns [SQLITE_DENY], the
  2700. ** application interface call that caused the
  2701. ** authorizer callback to run shall fail
  2702. ** with an [SQLITE_ERROR] error code and an error message
  2703. ** explaining that access is denied.
  2704. **
  2705. ** {H12506} If the authorizer code (the 2nd parameter to the authorizer
  2706. ** callback) is [SQLITE_READ] and the authorizer callback returns
  2707. ** [SQLITE_IGNORE], then the prepared statement is constructed to
  2708. ** insert a NULL value in place of the table column that would have
  2709. ** been read if [SQLITE_OK] had been returned.
  2710. **
  2711. ** {H12507} If the authorizer code (the 2nd parameter to the authorizer
  2712. ** callback) is anything other than [SQLITE_READ], then
  2713. ** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY].
  2714. **
  2715. ** {H12510} The first parameter to the authorizer callback is a copy of
  2716. ** the third parameter to the [sqlite3_set_authorizer()] interface.
  2717. **
  2718. ** {H12511} The second parameter to the callback is an integer
  2719. ** [SQLITE_COPY | action code] that specifies the particular action
  2720. ** to be authorized.
  2721. **
  2722. ** {H12512} The third through sixth parameters to the callback are
  2723. ** zero-terminated strings that contain
  2724. ** additional details about the action to be authorized.
  2725. **
  2726. ** {H12520} Each call to [sqlite3_set_authorizer()] overrides
  2727. ** any previously installed authorizer.
  2728. **
  2729. ** {H12521} A NULL authorizer means that no authorization
  2730. ** callback is invoked.
  2731. **
  2732. ** {H12522} The default authorizer is NULL.
  2733. */
  2734. SQLITE_API int sqlite3_set_authorizer(
  2735. sqlite3*,
  2736. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2737. void *pUserData
  2738. );
  2739. /*
  2740. ** CAPI3REF: Authorizer Return Codes {H12590} <H12500>
  2741. **
  2742. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2743. ** return either [SQLITE_OK] or one of these two constants in order
  2744. ** to signal SQLite whether or not the action is permitted. See the
  2745. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2746. ** information.
  2747. */
  2748. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2749. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2750. /*
  2751. ** CAPI3REF: Authorizer Action Codes {H12550} <H12500>
  2752. **
  2753. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2754. ** that is invoked to authorize certain SQL statement actions. The
  2755. ** second parameter to the callback is an integer code that specifies
  2756. ** what action is being authorized. These are the integer action codes that
  2757. ** the authorizer callback may be passed.
  2758. **
  2759. ** These action code values signify what kind of operation is to be
  2760. ** authorized. The 3rd and 4th parameters to the authorization
  2761. ** callback function will be parameters or NULL depending on which of these
  2762. ** codes is used as the second parameter. The 5th parameter to the
  2763. ** authorizer callback is the name of the database ("main", "temp",
  2764. ** etc.) if applicable. The 6th parameter to the authorizer callback
  2765. ** is the name of the inner-most trigger or view that is responsible for
  2766. ** the access attempt or NULL if this access attempt is directly from
  2767. ** top-level SQL code.
  2768. **
  2769. ** INVARIANTS:
  2770. **
  2771. ** {H12551} The second parameter to an
  2772. ** [sqlite3_set_authorizer | authorizer callback] shall be an integer
  2773. ** [SQLITE_COPY | authorizer code] that specifies what action
  2774. ** is being authorized.
  2775. **
  2776. ** {H12552} The 3rd and 4th parameters to the
  2777. ** [sqlite3_set_authorizer | authorization callback]
  2778. ** shall be parameters or NULL depending on which
  2779. ** [SQLITE_COPY | authorizer code] is used as the second parameter.
  2780. **
  2781. ** {H12553} The 5th parameter to the
  2782. ** [sqlite3_set_authorizer | authorizer callback] shall be the name
  2783. ** of the database (example: "main", "temp", etc.) if applicable.
  2784. **
  2785. ** {H12554} The 6th parameter to the
  2786. ** [sqlite3_set_authorizer | authorizer callback] shall be the name
  2787. ** of the inner-most trigger or view that is responsible for
  2788. ** the access attempt or NULL if this access attempt is directly from
  2789. ** top-level SQL code.
  2790. */
  2791. /******************************************* 3rd ************ 4th ***********/
  2792. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2793. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2794. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2795. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2796. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2797. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2798. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2799. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2800. #define SQLITE_DELETE 9 /* Table Name NULL */
  2801. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2802. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2803. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2804. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2805. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2806. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2807. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2808. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2809. #define SQLITE_INSERT 18 /* Table Name NULL */
  2810. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2811. #define SQLITE_READ 20 /* Table Name Column Name */
  2812. #define SQLITE_SELECT 21 /* NULL NULL */
  2813. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2814. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2815. #define SQLITE_ATTACH 24 /* Filename NULL */
  2816. #define SQLITE_DETACH 25 /* Database Name NULL */
  2817. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2818. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2819. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2820. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2821. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2822. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2823. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2824. #define SQLITE_COPY 0 /* No longer used */
  2825. /*
  2826. ** CAPI3REF: Tracing And Profiling Functions {H12280} <S60400>
  2827. ** EXPERIMENTAL
  2828. **
  2829. ** These routines register callback functions that can be used for
  2830. ** tracing and profiling the execution of SQL statements.
  2831. **
  2832. ** The callback function registered by sqlite3_trace() is invoked at
  2833. ** various times when an SQL statement is being run by [sqlite3_step()].
  2834. ** The callback returns a UTF-8 rendering of the SQL statement text
  2835. ** as the statement first begins executing. Additional callbacks occur
  2836. ** as each triggered subprogram is entered. The callbacks for triggers
  2837. ** contain a UTF-8 SQL comment that identifies the trigger.
  2838. **
  2839. ** The callback function registered by sqlite3_profile() is invoked
  2840. ** as each SQL statement finishes. The profile callback contains
  2841. ** the original statement text and an estimate of wall-clock time
  2842. ** of how long that statement took to run.
  2843. **
  2844. ** INVARIANTS:
  2845. **
  2846. ** {H12281} The callback function registered by [sqlite3_trace()]
  2847. ** shall be invoked
  2848. ** whenever an SQL statement first begins to execute and
  2849. ** whenever a trigger subprogram first begins to run.
  2850. **
  2851. ** {H12282} Each call to [sqlite3_trace()] shall override the previously
  2852. ** registered trace callback.
  2853. **
  2854. ** {H12283} A NULL trace callback shall disable tracing.
  2855. **
  2856. ** {H12284} The first argument to the trace callback shall be a copy of
  2857. ** the pointer which was the 3rd argument to [sqlite3_trace()].
  2858. **
  2859. ** {H12285} The second argument to the trace callback is a
  2860. ** zero-terminated UTF-8 string containing the original text
  2861. ** of the SQL statement as it was passed into [sqlite3_prepare_v2()]
  2862. ** or the equivalent, or an SQL comment indicating the beginning
  2863. ** of a trigger subprogram.
  2864. **
  2865. ** {H12287} The callback function registered by [sqlite3_profile()] is invoked
  2866. ** as each SQL statement finishes.
  2867. **
  2868. ** {H12288} The first parameter to the profile callback is a copy of
  2869. ** the 3rd parameter to [sqlite3_profile()].
  2870. **
  2871. ** {H12289} The second parameter to the profile callback is a
  2872. ** zero-terminated UTF-8 string that contains the complete text of
  2873. ** the SQL statement as it was processed by [sqlite3_prepare_v2()]
  2874. ** or the equivalent.
  2875. **
  2876. ** {H12290} The third parameter to the profile callback is an estimate
  2877. ** of the number of nanoseconds of wall-clock time required to
  2878. ** run the SQL statement from start to finish.
  2879. */
  2880. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2881. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2882. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2883. /*
  2884. ** CAPI3REF: Query Progress Callbacks {H12910} <S60400>
  2885. **
  2886. ** This routine configures a callback function - the
  2887. ** progress callback - that is invoked periodically during long
  2888. ** running calls to [sqlite3_exec()], [sqlite3_step()] and
  2889. ** [sqlite3_get_table()]. An example use for this
  2890. ** interface is to keep a GUI updated during a large query.
  2891. **
  2892. ** If the progress callback returns non-zero, the operation is
  2893. ** interrupted. This feature can be used to implement a
  2894. ** "Cancel" button on a GUI progress dialog box.
  2895. **
  2896. ** The progress handler must not do anything that will modify
  2897. ** the database connection that invoked the progress handler.
  2898. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2899. ** database connections for the meaning of "modify" in this paragraph.
  2900. **
  2901. ** INVARIANTS:
  2902. **
  2903. ** {H12911} The callback function registered by sqlite3_progress_handler()
  2904. ** is invoked periodically during long running calls to
  2905. ** [sqlite3_step()].
  2906. **
  2907. ** {H12912} The progress callback is invoked once for every N virtual
  2908. ** machine opcodes, where N is the second argument to
  2909. ** the [sqlite3_progress_handler()] call that registered
  2910. ** the callback. If N is less than 1, sqlite3_progress_handler()
  2911. ** acts as if a NULL progress handler had been specified.
  2912. **
  2913. ** {H12913} The progress callback itself is identified by the third
  2914. ** argument to sqlite3_progress_handler().
  2915. **
  2916. ** {H12914} The fourth argument to sqlite3_progress_handler() is a
  2917. ** void pointer passed to the progress callback
  2918. ** function each time it is invoked.
  2919. **
  2920. ** {H12915} If a call to [sqlite3_step()] results in fewer than N opcodes
  2921. ** being executed, then the progress callback is never invoked.
  2922. **
  2923. ** {H12916} Every call to [sqlite3_progress_handler()]
  2924. ** overwrites any previously registered progress handler.
  2925. **
  2926. ** {H12917} If the progress handler callback is NULL then no progress
  2927. ** handler is invoked.
  2928. **
  2929. ** {H12918} If the progress callback returns a result other than 0, then
  2930. ** the behavior is a if [sqlite3_interrupt()] had been called.
  2931. ** <S30500>
  2932. */
  2933. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2934. /*
  2935. ** CAPI3REF: Opening A New Database Connection {H12700} <S40200>
  2936. **
  2937. ** These routines open an SQLite database file whose name is given by the
  2938. ** filename argument. The filename argument is interpreted as UTF-8 for
  2939. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2940. ** order for sqlite3_open16(). A [database connection] handle is usually
  2941. ** returned in *ppDb, even if an error occurs. The only exception is that
  2942. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2943. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2944. ** object. If the database is opened (and/or created) successfully, then
  2945. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned. The
  2946. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2947. ** an English language description of the error.
  2948. **
  2949. ** The default encoding for the database will be UTF-8 if
  2950. ** sqlite3_open() or sqlite3_open_v2() is called and
  2951. ** UTF-16 in the native byte order if sqlite3_open16() is used.
  2952. **
  2953. ** Whether or not an error occurs when it is opened, resources
  2954. ** associated with the [database connection] handle should be released by
  2955. ** passing it to [sqlite3_close()] when it is no longer required.
  2956. **
  2957. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2958. ** except that it accepts two additional parameters for additional control
  2959. ** over the new database connection. The flags parameter can take one of
  2960. ** the following three values, optionally combined with the
  2961. ** [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags:
  2962. **
  2963. ** <dl>
  2964. ** <dt>[SQLITE_OPEN_READONLY]</dt>
  2965. ** <dd>The database is opened in read-only mode. If the database does not
  2966. ** already exist, an error is returned.</dd>
  2967. **
  2968. ** <dt>[SQLITE_OPEN_READWRITE]</dt>
  2969. ** <dd>The database is opened for reading and writing if possible, or reading
  2970. ** only if the file is write protected by the operating system. In either
  2971. ** case the database must already exist, otherwise an error is returned.</dd>
  2972. **
  2973. ** <dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2974. ** <dd>The database is opened for reading and writing, and is creates it if
  2975. ** it does not already exist. This is the behavior that is always used for
  2976. ** sqlite3_open() and sqlite3_open16().</dd>
  2977. ** </dl>
  2978. **
  2979. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2980. ** combinations shown above or one of the combinations shown above combined
  2981. ** with the [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags,
  2982. ** then the behavior is undefined.
  2983. **
  2984. ** If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2985. ** opens in the multi-thread [threading mode] as long as the single-thread
  2986. ** mode has not been set at compile-time or start-time. If the
  2987. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2988. ** in the serialized [threading mode] unless single-thread was
  2989. ** previously selected at compile-time or start-time.
  2990. **
  2991. ** If the filename is ":memory:", then a private, temporary in-memory database
  2992. ** is created for the connection. This in-memory database will vanish when
  2993. ** the database connection is closed. Future versions of SQLite might
  2994. ** make use of additional special filenames that begin with the ":" character.
  2995. ** It is recommended that when a database filename actually does begin with
  2996. ** a ":" character you should prefix the filename with a pathname such as
  2997. ** "./" to avoid ambiguity.
  2998. **
  2999. ** If the filename is an empty string, then a private, temporary
  3000. ** on-disk database will be created. This private database will be
  3001. ** automatically deleted as soon as the database connection is closed.
  3002. **
  3003. ** The fourth parameter to sqlite3_open_v2() is the name of the
  3004. ** [sqlite3_vfs] object that defines the operating system interface that
  3005. ** the new database connection should use. If the fourth parameter is
  3006. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  3007. **
  3008. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3009. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3010. ** codepage is currently defined. Filenames containing international
  3011. ** characters must be converted to UTF-8 prior to passing them into
  3012. ** sqlite3_open() or sqlite3_open_v2().
  3013. **
  3014. ** INVARIANTS:
  3015. **
  3016. ** {H12701} The [sqlite3_open()], [sqlite3_open16()], and
  3017. ** [sqlite3_open_v2()] interfaces create a new
  3018. ** [database connection] associated with
  3019. ** the database file given in their first parameter.
  3020. **
  3021. ** {H12702} The filename argument is interpreted as UTF-8
  3022. ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
  3023. ** in the native byte order for [sqlite3_open16()].
  3024. **
  3025. ** {H12703} A successful invocation of [sqlite3_open()], [sqlite3_open16()],
  3026. ** or [sqlite3_open_v2()] writes a pointer to a new
  3027. ** [database connection] into *ppDb.
  3028. **
  3029. ** {H12704} The [sqlite3_open()], [sqlite3_open16()], and
  3030. ** [sqlite3_open_v2()] interfaces return [SQLITE_OK] upon success,
  3031. ** or an appropriate [error code] on failure.
  3032. **
  3033. ** {H12706} The default text encoding for a new database created using
  3034. ** [sqlite3_open()] or [sqlite3_open_v2()] will be UTF-8.
  3035. **
  3036. ** {H12707} The default text encoding for a new database created using
  3037. ** [sqlite3_open16()] will be UTF-16.
  3038. **
  3039. ** {H12709} The [sqlite3_open(F,D)] interface is equivalent to
  3040. ** [sqlite3_open_v2(F,D,G,0)] where the G parameter is
  3041. ** [SQLITE_OPEN_READWRITE]|[SQLITE_OPEN_CREATE].
  3042. **
  3043. ** {H12711} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
  3044. ** bit value [SQLITE_OPEN_READONLY] then the database is opened
  3045. ** for reading only.
  3046. **
  3047. ** {H12712} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
  3048. ** bit value [SQLITE_OPEN_READWRITE] then the database is opened
  3049. ** reading and writing if possible, or for reading only if the
  3050. ** file is write protected by the operating system.
  3051. **
  3052. ** {H12713} If the G parameter to [sqlite3_open_v2(F,D,G,V)] omits the
  3053. ** bit value [SQLITE_OPEN_CREATE] and the database does not
  3054. ** previously exist, an error is returned.
  3055. **
  3056. ** {H12714} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
  3057. ** bit value [SQLITE_OPEN_CREATE] and the database does not
  3058. ** previously exist, then an attempt is made to create and
  3059. ** initialize the database.
  3060. **
  3061. ** {H12717} If the filename argument to [sqlite3_open()], [sqlite3_open16()],
  3062. ** or [sqlite3_open_v2()] is ":memory:", then an private,
  3063. ** ephemeral, in-memory database is created for the connection.
  3064. ** <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
  3065. ** in sqlite3_open_v2()?</todo>
  3066. **
  3067. ** {H12719} If the filename is NULL or an empty string, then a private,
  3068. ** ephemeral on-disk database will be created.
  3069. ** <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
  3070. ** in sqlite3_open_v2()?</todo>
  3071. **
  3072. ** {H12721} The [database connection] created by [sqlite3_open_v2(F,D,G,V)]
  3073. ** will use the [sqlite3_vfs] object identified by the V parameter,
  3074. ** or the default [sqlite3_vfs] object if V is a NULL pointer.
  3075. **
  3076. ** {H12723} Two [database connections] will share a common cache if both were
  3077. ** opened with the same VFS while [shared cache mode] was enabled and
  3078. ** if both filenames compare equal using memcmp() after having been
  3079. ** processed by the [sqlite3_vfs | xFullPathname] method of the VFS.
  3080. */
  3081. SQLITE_API int sqlite3_open(
  3082. const char *filename, /* Database filename (UTF-8) */
  3083. sqlite3 **ppDb /* OUT: SQLite db handle */
  3084. );
  3085. SQLITE_API int sqlite3_open16(
  3086. const void *filename, /* Database filename (UTF-16) */
  3087. sqlite3 **ppDb /* OUT: SQLite db handle */
  3088. );
  3089. SQLITE_API int sqlite3_open_v2(
  3090. const char *filename, /* Database filename (UTF-8) */
  3091. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3092. int flags, /* Flags */
  3093. const char *zVfs /* Name of VFS module to use */
  3094. );
  3095. /*
  3096. ** CAPI3REF: Error Codes And Messages {H12800} <S60200>
  3097. **
  3098. ** The sqlite3_errcode() interface returns the numeric [result code] or
  3099. ** [extended result code] for the most recent failed sqlite3_* API call
  3100. ** associated with a [database connection]. If a prior API call failed
  3101. ** but the most recent API call succeeded, the return value from
  3102. ** sqlite3_errcode() is undefined. The sqlite3_extended_errcode()
  3103. ** interface is the same except that it always returns the
  3104. ** [extended result code] even when extended result codes are
  3105. ** disabled.
  3106. **
  3107. ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3108. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3109. ** Memory to hold the error message string is managed internally.
  3110. ** The application does not need to worry about freeing the result.
  3111. ** However, the error string might be overwritten or deallocated by
  3112. ** subsequent calls to other SQLite interface functions.
  3113. **
  3114. ** When the serialized [threading mode] is in use, it might be the
  3115. ** case that a second error occurs on a separate thread in between
  3116. ** the time of the first error and the call to these interfaces.
  3117. ** When that happens, the second error will be reported since these
  3118. ** interfaces always report the most recent result. To avoid
  3119. ** this, each thread can obtain exclusive use of the [database connection] D
  3120. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3121. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3122. ** all calls to the interfaces listed here are completed.
  3123. **
  3124. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3125. ** was invoked incorrectly by the application. In that case, the
  3126. ** error code and message may or may not be set.
  3127. **
  3128. ** INVARIANTS:
  3129. **
  3130. ** {H12801} The [sqlite3_errcode(D)] interface returns the numeric
  3131. ** [result code] or [extended result code] for the most recently
  3132. ** failed interface call associated with the [database connection] D.
  3133. **
  3134. ** {H12802} The [sqlite3_extended_errcode(D)] interface returns the numeric
  3135. ** [extended result code] for the most recently
  3136. ** failed interface call associated with the [database connection] D.
  3137. **
  3138. ** {H12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)]
  3139. ** interfaces return English-language text that describes
  3140. ** the error in the mostly recently failed interface call,
  3141. ** encoded as either UTF-8 or UTF-16 respectively.
  3142. **
  3143. ** {H12807} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]
  3144. ** are valid until the next SQLite interface call.
  3145. **
  3146. ** {H12808} Calls to API routines that do not return an error code
  3147. ** (example: [sqlite3_data_count()]) do not
  3148. ** change the error code or message returned by
  3149. ** [sqlite3_errcode()], [sqlite3_extended_errcode()],
  3150. ** [sqlite3_errmsg()], or [sqlite3_errmsg16()].
  3151. **
  3152. ** {H12809} Interfaces that are not associated with a specific
  3153. ** [database connection] (examples:
  3154. ** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()]
  3155. ** do not change the values returned by
  3156. ** [sqlite3_errcode()], [sqlite3_extended_errcode()],
  3157. ** [sqlite3_errmsg()], or [sqlite3_errmsg16()].
  3158. */
  3159. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  3160. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  3161. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  3162. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  3163. /*
  3164. ** CAPI3REF: SQL Statement Object {H13000} <H13010>
  3165. ** KEYWORDS: {prepared statement} {prepared statements}
  3166. **
  3167. ** An instance of this object represents a single SQL statement.
  3168. ** This object is variously known as a "prepared statement" or a
  3169. ** "compiled SQL statement" or simply as a "statement".
  3170. **
  3171. ** The life of a statement object goes something like this:
  3172. **
  3173. ** <ol>
  3174. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  3175. ** function.
  3176. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  3177. ** interfaces.
  3178. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3179. ** <li> Reset the statement using [sqlite3_reset()] then go back
  3180. ** to step 2. Do this zero or more times.
  3181. ** <li> Destroy the object using [sqlite3_finalize()].
  3182. ** </ol>
  3183. **
  3184. ** Refer to documentation on individual methods above for additional
  3185. ** information.
  3186. */
  3187. typedef struct sqlite3_stmt sqlite3_stmt;
  3188. /*
  3189. ** CAPI3REF: Run-time Limits {H12760} <S20600>
  3190. **
  3191. ** This interface allows the size of various constructs to be limited
  3192. ** on a connection by connection basis. The first parameter is the
  3193. ** [database connection] whose limit is to be set or queried. The
  3194. ** second parameter is one of the [limit categories] that define a
  3195. ** class of constructs to be size limited. The third parameter is the
  3196. ** new limit for that construct. The function returns the old limit.
  3197. **
  3198. ** If the new limit is a negative number, the limit is unchanged.
  3199. ** For the limit category of SQLITE_LIMIT_XYZ there is a hard upper
  3200. ** bound set by a compile-time C preprocessor macro named SQLITE_MAX_XYZ.
  3201. ** (The "_LIMIT_" in the name is changed to "_MAX_".)
  3202. ** Attempts to increase a limit above its hard upper bound are
  3203. ** silently truncated to the hard upper limit.
  3204. **
  3205. ** Run time limits are intended for use in applications that manage
  3206. ** both their own internal database and also databases that are controlled
  3207. ** by untrusted external sources. An example application might be a
  3208. ** webbrowser that has its own databases for storing history and
  3209. ** separate databases controlled by JavaScript applications downloaded
  3210. ** off the Internet. The internal databases can be given the
  3211. ** large, default limits. Databases managed by external sources can
  3212. ** be given much smaller limits designed to prevent a denial of service
  3213. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3214. ** interface to further control untrusted SQL. The size of the database
  3215. ** created by an untrusted script can be contained using the
  3216. ** [max_page_count] [PRAGMA].
  3217. **
  3218. ** New run-time limit categories may be added in future releases.
  3219. **
  3220. ** INVARIANTS:
  3221. **
  3222. ** {H12762} A successful call to [sqlite3_limit(D,C,V)] where V is
  3223. ** positive changes the limit on the size of construct C in the
  3224. ** [database connection] D to the lesser of V and the hard upper
  3225. ** bound on the size of C that is set at compile-time.
  3226. **
  3227. ** {H12766} A successful call to [sqlite3_limit(D,C,V)] where V is negative
  3228. ** leaves the state of the [database connection] D unchanged.
  3229. **
  3230. ** {H12769} A successful call to [sqlite3_limit(D,C,V)] returns the
  3231. ** value of the limit on the size of construct C in the
  3232. ** [database connection] D as it was prior to the call.
  3233. */
  3234. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  3235. /*
  3236. ** CAPI3REF: Run-Time Limit Categories {H12790} <H12760>
  3237. ** KEYWORDS: {limit category} {limit categories}
  3238. **
  3239. ** These constants define various aspects of a [database connection]
  3240. ** that can be limited in size by calls to [sqlite3_limit()].
  3241. ** The meanings of the various limits are as follows:
  3242. **
  3243. ** <dl>
  3244. ** <dt>SQLITE_LIMIT_LENGTH</dt>
  3245. ** <dd>The maximum size of any string or BLOB or table row.<dd>
  3246. **
  3247. ** <dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3248. ** <dd>The maximum length of an SQL statement.</dd>
  3249. **
  3250. ** <dt>SQLITE_LIMIT_COLUMN</dt>
  3251. ** <dd>The maximum number of columns in a table definition or in the
  3252. ** result set of a SELECT or the maximum number of columns in an index
  3253. ** or in an ORDER BY or GROUP BY clause.</dd>
  3254. **
  3255. ** <dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3256. ** <dd>The maximum depth of the parse tree on any expression.</dd>
  3257. **
  3258. ** <dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3259. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>
  3260. **
  3261. ** <dt>SQLITE_LIMIT_VDBE_OP</dt>
  3262. ** <dd>The maximum number of instructions in a virtual machine program
  3263. ** used to implement an SQL statement.</dd>
  3264. **
  3265. ** <dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3266. ** <dd>The maximum number of arguments on a function.</dd>
  3267. **
  3268. ** <dt>SQLITE_LIMIT_ATTACHED</dt>
  3269. ** <dd>The maximum number of attached databases.</dd>
  3270. **
  3271. ** <dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3272. ** <dd>The maximum length of the pattern argument to the LIKE or
  3273. ** GLOB operators.</dd>
  3274. **
  3275. ** <dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3276. ** <dd>The maximum number of variables in an SQL statement that can
  3277. ** be bound.</dd>
  3278. ** </dl>
  3279. */
  3280. #define SQLITE_LIMIT_LENGTH 0
  3281. #define SQLITE_LIMIT_SQL_LENGTH 1
  3282. #define SQLITE_LIMIT_COLUMN 2
  3283. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3284. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3285. #define SQLITE_LIMIT_VDBE_OP 5
  3286. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3287. #define SQLITE_LIMIT_ATTACHED 7
  3288. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3289. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3290. /*
  3291. ** CAPI3REF: Compiling An SQL Statement {H13010} <S10000>
  3292. ** KEYWORDS: {SQL statement compiler}
  3293. **
  3294. ** To execute an SQL query, it must first be compiled into a byte-code
  3295. ** program using one of these routines.
  3296. **
  3297. ** The first argument, "db", is a [database connection] obtained from a
  3298. ** prior call to [sqlite3_open()], [sqlite3_open_v2()] or [sqlite3_open16()].
  3299. **
  3300. ** The second argument, "zSql", is the statement to be compiled, encoded
  3301. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3302. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3303. ** use UTF-16.
  3304. **
  3305. ** If the nByte argument is less than zero, then zSql is read up to the
  3306. ** first zero terminator. If nByte is non-negative, then it is the maximum
  3307. ** number of bytes read from zSql. When nByte is non-negative, the
  3308. ** zSql string ends at either the first '\000' or '\u0000' character or
  3309. ** the nByte-th byte, whichever comes first. If the caller knows
  3310. ** that the supplied string is nul-terminated, then there is a small
  3311. ** performance advantage to be gained by passing an nByte parameter that
  3312. ** is equal to the number of bytes in the input string <i>including</i>
  3313. ** the nul-terminator bytes.
  3314. **
  3315. ** *pzTail is made to point to the first byte past the end of the
  3316. ** first SQL statement in zSql. These routines only compile the first
  3317. ** statement in zSql, so *pzTail is left pointing to what remains
  3318. ** uncompiled.
  3319. **
  3320. ** *ppStmt is left pointing to a compiled [prepared statement] that can be
  3321. ** executed using [sqlite3_step()]. If there is an error, *ppStmt is set
  3322. ** to NULL. If the input text contains no SQL (if the input is an empty
  3323. ** string or a comment) then *ppStmt is set to NULL.
  3324. ** {A13018} The calling procedure is responsible for deleting the compiled
  3325. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3326. **
  3327. ** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned.
  3328. **
  3329. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3330. ** recommended for all new programs. The two older interfaces are retained
  3331. ** for backwards compatibility, but their use is discouraged.
  3332. ** In the "v2" interfaces, the prepared statement
  3333. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3334. ** original SQL text. This causes the [sqlite3_step()] interface to
  3335. ** behave a differently in two ways:
  3336. **
  3337. ** <ol>
  3338. ** <li>
  3339. ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3340. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3341. ** statement and try to run it again. If the schema has changed in
  3342. ** a way that makes the statement no longer valid, [sqlite3_step()] will still
  3343. ** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is
  3344. ** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the
  3345. ** error go away. Note: use [sqlite3_errmsg()] to find the text
  3346. ** of the parsing error that results in an [SQLITE_SCHEMA] return.
  3347. ** </li>
  3348. **
  3349. ** <li>
  3350. ** When an error occurs, [sqlite3_step()] will return one of the detailed
  3351. ** [error codes] or [extended error codes]. The legacy behavior was that
  3352. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3353. ** and you would have to make a second call to [sqlite3_reset()] in order
  3354. ** to find the underlying cause of the problem. With the "v2" prepare
  3355. ** interfaces, the underlying reason for the error is returned immediately.
  3356. ** </li>
  3357. ** </ol>
  3358. **
  3359. ** INVARIANTS:
  3360. **
  3361. ** {H13011} The [sqlite3_prepare(db,zSql,...)] and
  3362. ** [sqlite3_prepare_v2(db,zSql,...)] interfaces interpret the
  3363. ** text in their zSql parameter as UTF-8.
  3364. **
  3365. ** {H13012} The [sqlite3_prepare16(db,zSql,...)] and
  3366. ** [sqlite3_prepare16_v2(db,zSql,...)] interfaces interpret the
  3367. ** text in their zSql parameter as UTF-16 in the native byte order.
  3368. **
  3369. ** {H13013} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
  3370. ** and its variants is less than zero, the SQL text is
  3371. ** read from zSql is read up to the first zero terminator.
  3372. **
  3373. ** {H13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
  3374. ** and its variants is non-negative, then at most nBytes bytes of
  3375. ** SQL text is read from zSql.
  3376. **
  3377. ** {H13015} In [sqlite3_prepare_v2(db,zSql,N,P,pzTail)] and its variants
  3378. ** if the zSql input text contains more than one SQL statement
  3379. ** and pzTail is not NULL, then *pzTail is made to point to the
  3380. ** first byte past the end of the first SQL statement in zSql.
  3381. ** <todo>What does *pzTail point to if there is one statement?</todo>
  3382. **
  3383. ** {H13016} A successful call to [sqlite3_prepare_v2(db,zSql,N,ppStmt,...)]
  3384. ** or one of its variants writes into *ppStmt a pointer to a new
  3385. ** [prepared statement] or a pointer to NULL if zSql contains
  3386. ** nothing other than whitespace or comments.
  3387. **
  3388. ** {H13019} The [sqlite3_prepare_v2()] interface and its variants return
  3389. ** [SQLITE_OK] or an appropriate [error code] upon failure.
  3390. **
  3391. ** {H13021} Before [sqlite3_prepare(db,zSql,nByte,ppStmt,pzTail)] or its
  3392. ** variants returns an error (any value other than [SQLITE_OK]),
  3393. ** they first set *ppStmt to NULL.
  3394. */
  3395. SQLITE_API int sqlite3_prepare(
  3396. sqlite3 *db, /* Database handle */
  3397. const char *zSql, /* SQL statement, UTF-8 encoded */
  3398. int nByte, /* Maximum length of zSql in bytes. */
  3399. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3400. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3401. );
  3402. SQLITE_API int sqlite3_prepare_v2(
  3403. sqlite3 *db, /* Database handle */
  3404. const char *zSql, /* SQL statement, UTF-8 encoded */
  3405. int nByte, /* Maximum length of zSql in bytes. */
  3406. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3407. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3408. );
  3409. SQLITE_API int sqlite3_prepare16(
  3410. sqlite3 *db, /* Database handle */
  3411. const void *zSql, /* SQL statement, UTF-16 encoded */
  3412. int nByte, /* Maximum length of zSql in bytes. */
  3413. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3414. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3415. );
  3416. SQLITE_API int sqlite3_prepare16_v2(
  3417. sqlite3 *db, /* Database handle */
  3418. const void *zSql, /* SQL statement, UTF-16 encoded */
  3419. int nByte, /* Maximum length of zSql in bytes. */
  3420. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3421. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3422. );
  3423. /*
  3424. ** CAPI3REF: Retrieving Statement SQL {H13100} <H13000>
  3425. **
  3426. ** This interface can be used to retrieve a saved copy of the original
  3427. ** SQL text used to create a [prepared statement] if that statement was
  3428. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3429. **
  3430. ** INVARIANTS:
  3431. **
  3432. ** {H13101} If the [prepared statement] passed as the argument to
  3433. ** [sqlite3_sql()] was compiled using either [sqlite3_prepare_v2()] or
  3434. ** [sqlite3_prepare16_v2()], then [sqlite3_sql()] returns
  3435. ** a pointer to a zero-terminated string containing a UTF-8 rendering
  3436. ** of the original SQL statement.
  3437. **
  3438. ** {H13102} If the [prepared statement] passed as the argument to
  3439. ** [sqlite3_sql()] was compiled using either [sqlite3_prepare()] or
  3440. ** [sqlite3_prepare16()], then [sqlite3_sql()] returns a NULL pointer.
  3441. **
  3442. ** {H13103} The string returned by [sqlite3_sql(S)] is valid until the
  3443. ** [prepared statement] S is deleted using [sqlite3_finalize(S)].
  3444. */
  3445. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3446. /*
  3447. ** CAPI3REF: Dynamically Typed Value Object {H15000} <S20200>
  3448. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3449. **
  3450. ** SQLite uses the sqlite3_value object to represent all values
  3451. ** that can be stored in a database table. SQLite uses dynamic typing
  3452. ** for the values it stores. Values stored in sqlite3_value objects
  3453. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3454. **
  3455. ** An sqlite3_value object may be either "protected" or "unprotected".
  3456. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3457. ** will accept either a protected or an unprotected sqlite3_value.
  3458. ** Every interface that accepts sqlite3_value arguments specifies
  3459. ** whether or not it requires a protected sqlite3_value.
  3460. **
  3461. ** The terms "protected" and "unprotected" refer to whether or not
  3462. ** a mutex is held. A internal mutex is held for a protected
  3463. ** sqlite3_value object but no mutex is held for an unprotected
  3464. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3465. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3466. ** or if SQLite is run in one of reduced mutex modes
  3467. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3468. ** then there is no distinction between protected and unprotected
  3469. ** sqlite3_value objects and they can be used interchangeably. However,
  3470. ** for maximum code portability it is recommended that applications
  3471. ** still make the distinction between between protected and unprotected
  3472. ** sqlite3_value objects even when not strictly required.
  3473. **
  3474. ** The sqlite3_value objects that are passed as parameters into the
  3475. ** implementation of [application-defined SQL functions] are protected.
  3476. ** The sqlite3_value object returned by
  3477. ** [sqlite3_column_value()] is unprotected.
  3478. ** Unprotected sqlite3_value objects may only be used with
  3479. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3480. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3481. ** interfaces require protected sqlite3_value objects.
  3482. */
  3483. typedef struct Mem sqlite3_value;
  3484. /*
  3485. ** CAPI3REF: SQL Function Context Object {H16001} <S20200>
  3486. **
  3487. ** The context in which an SQL function executes is stored in an
  3488. ** sqlite3_context object. A pointer to an sqlite3_context object
  3489. ** is always first parameter to [application-defined SQL functions].
  3490. ** The application-defined SQL function implementation will pass this
  3491. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3492. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3493. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3494. ** and/or [sqlite3_set_auxdata()].
  3495. */
  3496. typedef struct sqlite3_context sqlite3_context;
  3497. /*
  3498. ** CAPI3REF: Binding Values To Prepared Statements {H13500} <S70300>
  3499. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3500. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3501. **
  3502. ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
  3503. ** literals may be replaced by a parameter in one of these forms:
  3504. **
  3505. ** <ul>
  3506. ** <li> ?
  3507. ** <li> ?NNN
  3508. ** <li> :VVV
  3509. ** <li> @VVV
  3510. ** <li> $VVV
  3511. ** </ul>
  3512. **
  3513. ** In the parameter forms shown above NNN is an integer literal,
  3514. ** and VVV is an alpha-numeric parameter name. The values of these
  3515. ** parameters (also called "host parameter names" or "SQL parameters")
  3516. ** can be set using the sqlite3_bind_*() routines defined here.
  3517. **
  3518. ** The first argument to the sqlite3_bind_*() routines is always
  3519. ** a pointer to the [sqlite3_stmt] object returned from
  3520. ** [sqlite3_prepare_v2()] or its variants.
  3521. **
  3522. ** The second argument is the index of the SQL parameter to be set.
  3523. ** The leftmost SQL parameter has an index of 1. When the same named
  3524. ** SQL parameter is used more than once, second and subsequent
  3525. ** occurrences have the same index as the first occurrence.
  3526. ** The index for named parameters can be looked up using the
  3527. ** [sqlite3_bind_parameter_index()] API if desired. The index
  3528. ** for "?NNN" parameters is the value of NNN.
  3529. ** The NNN value must be between 1 and the [sqlite3_limit()]
  3530. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3531. **
  3532. ** The third argument is the value to bind to the parameter.
  3533. **
  3534. ** In those routines that have a fourth argument, its value is the
  3535. ** number of bytes in the parameter. To be clear: the value is the
  3536. ** number of <u>bytes</u> in the value, not the number of characters.
  3537. ** If the fourth parameter is negative, the length of the string is
  3538. ** the number of bytes up to the first zero terminator.
  3539. **
  3540. ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  3541. ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  3542. ** string after SQLite has finished with it. If the fifth argument is
  3543. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3544. ** information is in static, unmanaged space and does not need to be freed.
  3545. ** If the fifth argument has the value [SQLITE_TRANSIENT], then
  3546. ** SQLite makes its own private copy of the data immediately, before
  3547. ** the sqlite3_bind_*() routine returns.
  3548. **
  3549. ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3550. ** is filled with zeroes. A zeroblob uses a fixed amount of memory
  3551. ** (just an integer to hold its size) while it is being processed.
  3552. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3553. ** content is later written using
  3554. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3555. ** A negative value for the zeroblob results in a zero-length BLOB.
  3556. **
  3557. ** The sqlite3_bind_*() routines must be called after
  3558. ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
  3559. ** before [sqlite3_step()].
  3560. ** Bindings are not cleared by the [sqlite3_reset()] routine.
  3561. ** Unbound parameters are interpreted as NULL.
  3562. **
  3563. ** These routines return [SQLITE_OK] on success or an error code if
  3564. ** anything goes wrong. [SQLITE_RANGE] is returned if the parameter
  3565. ** index is out of range. [SQLITE_NOMEM] is returned if malloc() fails.
  3566. ** [SQLITE_MISUSE] might be returned if these routines are called on a
  3567. ** virtual machine that is the wrong state or which has already been finalized.
  3568. ** Detection of misuse is unreliable. Applications should not depend
  3569. ** on SQLITE_MISUSE returns. SQLITE_MISUSE is intended to indicate a
  3570. ** a logic error in the application. Future versions of SQLite might
  3571. ** panic rather than return SQLITE_MISUSE.
  3572. **
  3573. ** See also: [sqlite3_bind_parameter_count()],
  3574. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3575. **
  3576. ** INVARIANTS:
  3577. **
  3578. ** {H13506} The [SQL statement compiler] recognizes tokens of the forms
  3579. ** "?", "?NNN", "$VVV", ":VVV", and "@VVV" as SQL parameters,
  3580. ** where NNN is any sequence of one or more digits
  3581. ** and where VVV is any sequence of one or more alphanumeric
  3582. ** characters or "::" optionally followed by a string containing
  3583. ** no spaces and contained within parentheses.
  3584. **
  3585. ** {H13509} The initial value of an SQL parameter is NULL.
  3586. **
  3587. ** {H13512} The index of an "?" SQL parameter is one larger than the
  3588. ** largest index of SQL parameter to the left, or 1 if
  3589. ** the "?" is the leftmost SQL parameter.
  3590. **
  3591. ** {H13515} The index of an "?NNN" SQL parameter is the integer NNN.
  3592. **
  3593. ** {H13518} The index of an ":VVV", "$VVV", or "@VVV" SQL parameter is
  3594. ** the same as the index of leftmost occurrences of the same
  3595. ** parameter, or one more than the largest index over all
  3596. ** parameters to the left if this is the first occurrence
  3597. ** of this parameter, or 1 if this is the leftmost parameter.
  3598. **
  3599. ** {H13521} The [SQL statement compiler] fails with an [SQLITE_RANGE]
  3600. ** error if the index of an SQL parameter is less than 1
  3601. ** or greater than the compile-time SQLITE_MAX_VARIABLE_NUMBER
  3602. ** parameter.
  3603. **
  3604. ** {H13524} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,V,...)]
  3605. ** associate the value V with all SQL parameters having an
  3606. ** index of N in the [prepared statement] S.
  3607. **
  3608. ** {H13527} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,...)]
  3609. ** override prior calls with the same values of S and N.
  3610. **
  3611. ** {H13530} Bindings established by [sqlite3_bind_text | sqlite3_bind(S,...)]
  3612. ** persist across calls to [sqlite3_reset(S)].
  3613. **
  3614. ** {H13533} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
  3615. ** [sqlite3_bind_text(S,N,V,L,D)], or
  3616. ** [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds the first L
  3617. ** bytes of the BLOB or string pointed to by V, when L
  3618. ** is non-negative.
  3619. **
  3620. ** {H13536} In calls to [sqlite3_bind_text(S,N,V,L,D)] or
  3621. ** [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds characters
  3622. ** from V through the first zero character when L is negative.
  3623. **
  3624. ** {H13539} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
  3625. ** [sqlite3_bind_text(S,N,V,L,D)], or
  3626. ** [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
  3627. ** constant [SQLITE_STATIC], SQLite assumes that the value V
  3628. ** is held in static unmanaged space that will not change
  3629. ** during the lifetime of the binding.
  3630. **
  3631. ** {H13542} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
  3632. ** [sqlite3_bind_text(S,N,V,L,D)], or
  3633. ** [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
  3634. ** constant [SQLITE_TRANSIENT], the routine makes a
  3635. ** private copy of the value V before it returns.
  3636. **
  3637. ** {H13545} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
  3638. ** [sqlite3_bind_text(S,N,V,L,D)], or
  3639. ** [sqlite3_bind_text16(S,N,V,L,D)] when D is a pointer to
  3640. ** a function, SQLite invokes that function to destroy the
  3641. ** value V after it has finished using the value V.
  3642. **
  3643. ** {H13548} In calls to [sqlite3_bind_zeroblob(S,N,V,L)] the value bound
  3644. ** is a BLOB of L bytes, or a zero-length BLOB if L is negative.
  3645. **
  3646. ** {H13551} In calls to [sqlite3_bind_value(S,N,V)] the V argument may
  3647. ** be either a [protected sqlite3_value] object or an
  3648. ** [unprotected sqlite3_value] object.
  3649. */
  3650. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3651. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3652. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3653. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3654. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3655. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  3656. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3657. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3658. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3659. /*
  3660. ** CAPI3REF: Number Of SQL Parameters {H13600} <S70300>
  3661. **
  3662. ** This routine can be used to find the number of [SQL parameters]
  3663. ** in a [prepared statement]. SQL parameters are tokens of the
  3664. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3665. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3666. ** to the parameters at a later time.
  3667. **
  3668. ** This routine actually returns the index of the largest (rightmost)
  3669. ** parameter. For all forms except ?NNN, this will correspond to the
  3670. ** number of unique parameters. If parameters of the ?NNN are used,
  3671. ** there may be gaps in the list.
  3672. **
  3673. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3674. ** [sqlite3_bind_parameter_name()], and
  3675. ** [sqlite3_bind_parameter_index()].
  3676. **
  3677. ** INVARIANTS:
  3678. **
  3679. ** {H13601} The [sqlite3_bind_parameter_count(S)] interface returns
  3680. ** the largest index of all SQL parameters in the
  3681. ** [prepared statement] S, or 0 if S contains no SQL parameters.
  3682. */
  3683. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3684. /*
  3685. ** CAPI3REF: Name Of A Host Parameter {H13620} <S70300>
  3686. **
  3687. ** This routine returns a pointer to the name of the n-th
  3688. ** [SQL parameter] in a [prepared statement].
  3689. ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3690. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3691. ** respectively.
  3692. ** In other words, the initial ":" or "$" or "@" or "?"
  3693. ** is included as part of the name.
  3694. ** Parameters of the form "?" without a following integer have no name
  3695. ** and are also referred to as "anonymous parameters".
  3696. **
  3697. ** The first host parameter has an index of 1, not 0.
  3698. **
  3699. ** If the value n is out of range or if the n-th parameter is
  3700. ** nameless, then NULL is returned. The returned string is
  3701. ** always in UTF-8 encoding even if the named parameter was
  3702. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3703. ** [sqlite3_prepare16_v2()].
  3704. **
  3705. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3706. ** [sqlite3_bind_parameter_count()], and
  3707. ** [sqlite3_bind_parameter_index()].
  3708. **
  3709. ** INVARIANTS:
  3710. **
  3711. ** {H13621} The [sqlite3_bind_parameter_name(S,N)] interface returns
  3712. ** a UTF-8 rendering of the name of the SQL parameter in
  3713. ** the [prepared statement] S having index N, or
  3714. ** NULL if there is no SQL parameter with index N or if the
  3715. ** parameter with index N is an anonymous parameter "?".
  3716. */
  3717. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3718. /*
  3719. ** CAPI3REF: Index Of A Parameter With A Given Name {H13640} <S70300>
  3720. **
  3721. ** Return the index of an SQL parameter given its name. The
  3722. ** index value returned is suitable for use as the second
  3723. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. A zero
  3724. ** is returned if no matching parameter is found. The parameter
  3725. ** name must be given in UTF-8 even if the original statement
  3726. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3727. **
  3728. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3729. ** [sqlite3_bind_parameter_count()], and
  3730. ** [sqlite3_bind_parameter_index()].
  3731. **
  3732. ** INVARIANTS:
  3733. **
  3734. ** {H13641} The [sqlite3_bind_parameter_index(S,N)] interface returns
  3735. ** the index of SQL parameter in the [prepared statement]
  3736. ** S whose name matches the UTF-8 string N, or 0 if there is
  3737. ** no match.
  3738. */
  3739. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3740. /*
  3741. ** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} <S70300>
  3742. **
  3743. ** Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3744. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3745. ** Use this routine to reset all host parameters to NULL.
  3746. **
  3747. ** INVARIANTS:
  3748. **
  3749. ** {H13661} The [sqlite3_clear_bindings(S)] interface resets all SQL
  3750. ** parameter bindings in the [prepared statement] S back to NULL.
  3751. */
  3752. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3753. /*
  3754. ** CAPI3REF: Number Of Columns In A Result Set {H13710} <S10700>
  3755. **
  3756. ** Return the number of columns in the result set returned by the
  3757. ** [prepared statement]. This routine returns 0 if pStmt is an SQL
  3758. ** statement that does not return data (for example an [UPDATE]).
  3759. **
  3760. ** INVARIANTS:
  3761. **
  3762. ** {H13711} The [sqlite3_column_count(S)] interface returns the number of
  3763. ** columns in the result set generated by the [prepared statement] S,
  3764. ** or 0 if S does not generate a result set.
  3765. */
  3766. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3767. /*
  3768. ** CAPI3REF: Column Names In A Result Set {H13720} <S10700>
  3769. **
  3770. ** These routines return the name assigned to a particular column
  3771. ** in the result set of a [SELECT] statement. The sqlite3_column_name()
  3772. ** interface returns a pointer to a zero-terminated UTF-8 string
  3773. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3774. ** UTF-16 string. The first parameter is the [prepared statement]
  3775. ** that implements the [SELECT] statement. The second parameter is the
  3776. ** column number. The leftmost column is number 0.
  3777. **
  3778. ** The returned string pointer is valid until either the [prepared statement]
  3779. ** is destroyed by [sqlite3_finalize()] or until the next call to
  3780. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3781. **
  3782. ** If sqlite3_malloc() fails during the processing of either routine
  3783. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3784. ** NULL pointer is returned.
  3785. **
  3786. ** The name of a result column is the value of the "AS" clause for
  3787. ** that column, if there is an AS clause. If there is no AS clause
  3788. ** then the name of the column is unspecified and may change from
  3789. ** one release of SQLite to the next.
  3790. **
  3791. ** INVARIANTS:
  3792. **
  3793. ** {H13721} A successful invocation of the [sqlite3_column_name(S,N)]
  3794. ** interface returns the name of the Nth column (where 0 is
  3795. ** the leftmost column) for the result set of the
  3796. ** [prepared statement] S as a zero-terminated UTF-8 string.
  3797. **
  3798. ** {H13723} A successful invocation of the [sqlite3_column_name16(S,N)]
  3799. ** interface returns the name of the Nth column (where 0 is
  3800. ** the leftmost column) for the result set of the
  3801. ** [prepared statement] S as a zero-terminated UTF-16 string
  3802. ** in the native byte order.
  3803. **
  3804. ** {H13724} The [sqlite3_column_name()] and [sqlite3_column_name16()]
  3805. ** interfaces return a NULL pointer if they are unable to
  3806. ** allocate memory to hold their normal return strings.
  3807. **
  3808. ** {H13725} If the N parameter to [sqlite3_column_name(S,N)] or
  3809. ** [sqlite3_column_name16(S,N)] is out of range, then the
  3810. ** interfaces return a NULL pointer.
  3811. **
  3812. ** {H13726} The strings returned by [sqlite3_column_name(S,N)] and
  3813. ** [sqlite3_column_name16(S,N)] are valid until the next
  3814. ** call to either routine with the same S and N parameters
  3815. ** or until [sqlite3_finalize(S)] is called.
  3816. **
  3817. ** {H13727} When a result column of a [SELECT] statement contains
  3818. ** an AS clause, the name of that column is the identifier
  3819. ** to the right of the AS keyword.
  3820. */
  3821. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3822. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3823. /*
  3824. ** CAPI3REF: Source Of Data In A Query Result {H13740} <S10700>
  3825. **
  3826. ** These routines provide a means to determine what column of what
  3827. ** table in which database a result of a [SELECT] statement comes from.
  3828. ** The name of the database or table or column can be returned as
  3829. ** either a UTF-8 or UTF-16 string. The _database_ routines return
  3830. ** the database name, the _table_ routines return the table name, and
  3831. ** the origin_ routines return the column name.
  3832. ** The returned string is valid until the [prepared statement] is destroyed
  3833. ** using [sqlite3_finalize()] or until the same information is requested
  3834. ** again in a different encoding.
  3835. **
  3836. ** The names returned are the original un-aliased names of the
  3837. ** database, table, and column.
  3838. **
  3839. ** The first argument to the following calls is a [prepared statement].
  3840. ** These functions return information about the Nth column returned by
  3841. ** the statement, where N is the second function argument.
  3842. **
  3843. ** If the Nth column returned by the statement is an expression or
  3844. ** subquery and is not a column value, then all of these functions return
  3845. ** NULL. These routine might also return NULL if a memory allocation error
  3846. ** occurs. Otherwise, they return the name of the attached database, table
  3847. ** and column that query result column was extracted from.
  3848. **
  3849. ** As with all other SQLite APIs, those postfixed with "16" return
  3850. ** UTF-16 encoded strings, the other functions return UTF-8. {END}
  3851. **
  3852. ** These APIs are only available if the library was compiled with the
  3853. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  3854. **
  3855. ** {A13751}
  3856. ** If two or more threads call one or more of these routines against the same
  3857. ** prepared statement and column at the same time then the results are
  3858. ** undefined.
  3859. **
  3860. ** INVARIANTS:
  3861. **
  3862. ** {H13741} The [sqlite3_column_database_name(S,N)] interface returns either
  3863. ** the UTF-8 zero-terminated name of the database from which the
  3864. ** Nth result column of the [prepared statement] S is extracted,
  3865. ** or NULL if the Nth column of S is a general expression
  3866. ** or if unable to allocate memory to store the name.
  3867. **
  3868. ** {H13742} The [sqlite3_column_database_name16(S,N)] interface returns either
  3869. ** the UTF-16 native byte order zero-terminated name of the database
  3870. ** from which the Nth result column of the [prepared statement] S is
  3871. ** extracted, or NULL if the Nth column of S is a general expression
  3872. ** or if unable to allocate memory to store the name.
  3873. **
  3874. ** {H13743} The [sqlite3_column_table_name(S,N)] interface returns either
  3875. ** the UTF-8 zero-terminated name of the table from which the
  3876. ** Nth result column of the [prepared statement] S is extracted,
  3877. ** or NULL if the Nth column of S is a general expression
  3878. ** or if unable to allocate memory to store the name.
  3879. **
  3880. ** {H13744} The [sqlite3_column_table_name16(S,N)] interface returns either
  3881. ** the UTF-16 native byte order zero-terminated name of the table
  3882. ** from which the Nth result column of the [prepared statement] S is
  3883. ** extracted, or NULL if the Nth column of S is a general expression
  3884. ** or if unable to allocate memory to store the name.
  3885. **
  3886. ** {H13745} The [sqlite3_column_origin_name(S,N)] interface returns either
  3887. ** the UTF-8 zero-terminated name of the table column from which the
  3888. ** Nth result column of the [prepared statement] S is extracted,
  3889. ** or NULL if the Nth column of S is a general expression
  3890. ** or if unable to allocate memory to store the name.
  3891. **
  3892. ** {H13746} The [sqlite3_column_origin_name16(S,N)] interface returns either
  3893. ** the UTF-16 native byte order zero-terminated name of the table
  3894. ** column from which the Nth result column of the
  3895. ** [prepared statement] S is extracted, or NULL if the Nth column
  3896. ** of S is a general expression or if unable to allocate memory
  3897. ** to store the name.
  3898. **
  3899. ** {H13748} The return values from
  3900. ** [sqlite3_column_database_name | column metadata interfaces]
  3901. ** are valid for the lifetime of the [prepared statement]
  3902. ** or until the encoding is changed by another metadata
  3903. ** interface call for the same prepared statement and column.
  3904. **
  3905. ** ASSUMPTIONS:
  3906. **
  3907. ** {A13751} If two or more threads call one or more
  3908. ** [sqlite3_column_database_name | column metadata interfaces]
  3909. ** for the same [prepared statement] and result column
  3910. ** at the same time then the results are undefined.
  3911. */
  3912. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3913. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3914. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3915. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3916. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3917. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3918. /*
  3919. ** CAPI3REF: Declared Datatype Of A Query Result {H13760} <S10700>
  3920. **
  3921. ** The first parameter is a [prepared statement].
  3922. ** If this statement is a [SELECT] statement and the Nth column of the
  3923. ** returned result set of that [SELECT] is a table column (not an
  3924. ** expression or subquery) then the declared type of the table
  3925. ** column is returned. If the Nth column of the result set is an
  3926. ** expression or subquery, then a NULL pointer is returned.
  3927. ** The returned string is always UTF-8 encoded. {END}
  3928. **
  3929. ** For example, given the database schema:
  3930. **
  3931. ** CREATE TABLE t1(c1 VARIANT);
  3932. **
  3933. ** and the following statement to be compiled:
  3934. **
  3935. ** SELECT c1 + 1, c1 FROM t1;
  3936. **
  3937. ** this routine would return the string "VARIANT" for the second result
  3938. ** column (i==1), and a NULL pointer for the first result column (i==0).
  3939. **
  3940. ** SQLite uses dynamic run-time typing. So just because a column
  3941. ** is declared to contain a particular type does not mean that the
  3942. ** data stored in that column is of the declared type. SQLite is
  3943. ** strongly typed, but the typing is dynamic not static. Type
  3944. ** is associated with individual values, not with the containers
  3945. ** used to hold those values.
  3946. **
  3947. ** INVARIANTS:
  3948. **
  3949. ** {H13761} A successful call to [sqlite3_column_decltype(S,N)] returns a
  3950. ** zero-terminated UTF-8 string containing the declared datatype
  3951. ** of the table column that appears as the Nth column (numbered
  3952. ** from 0) of the result set to the [prepared statement] S.
  3953. **
  3954. ** {H13762} A successful call to [sqlite3_column_decltype16(S,N)]
  3955. ** returns a zero-terminated UTF-16 native byte order string
  3956. ** containing the declared datatype of the table column that appears
  3957. ** as the Nth column (numbered from 0) of the result set to the
  3958. ** [prepared statement] S.
  3959. **
  3960. ** {H13763} If N is less than 0 or N is greater than or equal to
  3961. ** the number of columns in the [prepared statement] S,
  3962. ** or if the Nth column of S is an expression or subquery rather
  3963. ** than a table column, or if a memory allocation failure
  3964. ** occurs during encoding conversions, then
  3965. ** calls to [sqlite3_column_decltype(S,N)] or
  3966. ** [sqlite3_column_decltype16(S,N)] return NULL.
  3967. */
  3968. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3969. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3970. /*
  3971. ** CAPI3REF: Evaluate An SQL Statement {H13200} <S10000>
  3972. **
  3973. ** After a [prepared statement] has been prepared using either
  3974. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3975. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3976. ** must be called one or more times to evaluate the statement.
  3977. **
  3978. ** The details of the behavior of the sqlite3_step() interface depend
  3979. ** on whether the statement was prepared using the newer "v2" interface
  3980. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3981. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3982. ** new "v2" interface is recommended for new applications but the legacy
  3983. ** interface will continue to be supported.
  3984. **
  3985. ** In the legacy interface, the return value will be either [SQLITE_BUSY],
  3986. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3987. ** With the "v2" interface, any of the other [result codes] or
  3988. ** [extended result codes] might be returned as well.
  3989. **
  3990. ** [SQLITE_BUSY] means that the database engine was unable to acquire the
  3991. ** database locks it needs to do its job. If the statement is a [COMMIT]
  3992. ** or occurs outside of an explicit transaction, then you can retry the
  3993. ** statement. If the statement is not a [COMMIT] and occurs within a
  3994. ** explicit transaction then you should rollback the transaction before
  3995. ** continuing.
  3996. **
  3997. ** [SQLITE_DONE] means that the statement has finished executing
  3998. ** successfully. sqlite3_step() should not be called again on this virtual
  3999. ** machine without first calling [sqlite3_reset()] to reset the virtual
  4000. ** machine back to its initial state.
  4001. **
  4002. ** If the SQL statement being executed returns any data, then [SQLITE_ROW]
  4003. ** is returned each time a new row of data is ready for processing by the
  4004. ** caller. The values may be accessed using the [column access functions].
  4005. ** sqlite3_step() is called again to retrieve the next row of data.
  4006. **
  4007. ** [SQLITE_ERROR] means that a run-time error (such as a constraint
  4008. ** violation) has occurred. sqlite3_step() should not be called again on
  4009. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  4010. ** With the legacy interface, a more specific error code (for example,
  4011. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  4012. ** can be obtained by calling [sqlite3_reset()] on the
  4013. ** [prepared statement]. In the "v2" interface,
  4014. ** the more specific error code is returned directly by sqlite3_step().
  4015. **
  4016. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  4017. ** Perhaps it was called on a [prepared statement] that has
  4018. ** already been [sqlite3_finalize | finalized] or on one that had
  4019. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  4020. ** be the case that the same database connection is being used by two or
  4021. ** more threads at the same moment in time.
  4022. **
  4023. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  4024. ** API always returns a generic error code, [SQLITE_ERROR], following any
  4025. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  4026. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  4027. ** specific [error codes] that better describes the error.
  4028. ** We admit that this is a goofy design. The problem has been fixed
  4029. ** with the "v2" interface. If you prepare all of your SQL statements
  4030. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  4031. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  4032. ** then the more specific [error codes] are returned directly
  4033. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  4034. **
  4035. ** INVARIANTS:
  4036. **
  4037. ** {H13202} If the [prepared statement] S is ready to be run, then
  4038. ** [sqlite3_step(S)] advances that prepared statement until
  4039. ** completion or until it is ready to return another row of the
  4040. ** result set, or until an [sqlite3_interrupt | interrupt]
  4041. ** or a run-time error occurs.
  4042. **
  4043. ** {H15304} When a call to [sqlite3_step(S)] causes the [prepared statement]
  4044. ** S to run to completion, the function returns [SQLITE_DONE].
  4045. **
  4046. ** {H15306} When a call to [sqlite3_step(S)] stops because it is ready to
  4047. ** return another row of the result set, it returns [SQLITE_ROW].
  4048. **
  4049. ** {H15308} If a call to [sqlite3_step(S)] encounters an
  4050. ** [sqlite3_interrupt | interrupt] or a run-time error,
  4051. ** it returns an appropriate error code that is not one of
  4052. ** [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE].
  4053. **
  4054. ** {H15310} If an [sqlite3_interrupt | interrupt] or a run-time error
  4055. ** occurs during a call to [sqlite3_step(S)]
  4056. ** for a [prepared statement] S created using
  4057. ** legacy interfaces [sqlite3_prepare()] or
  4058. ** [sqlite3_prepare16()], then the function returns either
  4059. ** [SQLITE_ERROR], [SQLITE_BUSY], or [SQLITE_MISUSE].
  4060. */
  4061. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  4062. /*
  4063. ** CAPI3REF: Number of columns in a result set {H13770} <S10700>
  4064. **
  4065. ** Returns the number of values in the current row of the result set.
  4066. **
  4067. ** INVARIANTS:
  4068. **
  4069. ** {H13771} After a call to [sqlite3_step(S)] that returns [SQLITE_ROW],
  4070. ** the [sqlite3_data_count(S)] routine will return the same value
  4071. ** as the [sqlite3_column_count(S)] function.
  4072. **
  4073. ** {H13772} After [sqlite3_step(S)] has returned any value other than
  4074. ** [SQLITE_ROW] or before [sqlite3_step(S)] has been called on the
  4075. ** [prepared statement] for the first time since it was
  4076. ** [sqlite3_prepare | prepared] or [sqlite3_reset | reset],
  4077. ** the [sqlite3_data_count(S)] routine returns zero.
  4078. */
  4079. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  4080. /*
  4081. ** CAPI3REF: Fundamental Datatypes {H10265} <S10110><S10120>
  4082. ** KEYWORDS: SQLITE_TEXT
  4083. **
  4084. ** {H10266} Every value in SQLite has one of five fundamental datatypes:
  4085. **
  4086. ** <ul>
  4087. ** <li> 64-bit signed integer
  4088. ** <li> 64-bit IEEE floating point number
  4089. ** <li> string
  4090. ** <li> BLOB
  4091. ** <li> NULL
  4092. ** </ul> {END}
  4093. **
  4094. ** These constants are codes for each of those types.
  4095. **
  4096. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  4097. ** for a completely different meaning. Software that links against both
  4098. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  4099. ** SQLITE_TEXT.
  4100. */
  4101. #define SQLITE_INTEGER 1
  4102. #define SQLITE_FLOAT 2
  4103. #define SQLITE_BLOB 4
  4104. #define SQLITE_NULL 5
  4105. #ifdef SQLITE_TEXT
  4106. # undef SQLITE_TEXT
  4107. #else
  4108. # define SQLITE_TEXT 3
  4109. #endif
  4110. #define SQLITE3_TEXT 3
  4111. /*
  4112. ** CAPI3REF: Result Values From A Query {H13800} <S10700>
  4113. ** KEYWORDS: {column access functions}
  4114. **
  4115. ** These routines form the "result set query" interface.
  4116. **
  4117. ** These routines return information about a single column of the current
  4118. ** result row of a query. In every case the first argument is a pointer
  4119. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  4120. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  4121. ** and the second argument is the index of the column for which information
  4122. ** should be returned. The leftmost column of the result set has the index 0.
  4123. **
  4124. ** If the SQL statement does not currently point to a valid row, or if the
  4125. ** column index is out of range, the result is undefined.
  4126. ** These routines may only be called when the most recent call to
  4127. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  4128. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  4129. ** If any of these routines are called after [sqlite3_reset()] or
  4130. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  4131. ** something other than [SQLITE_ROW], the results are undefined.
  4132. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  4133. ** are called from a different thread while any of these routines
  4134. ** are pending, then the results are undefined.
  4135. **
  4136. ** The sqlite3_column_type() routine returns the
  4137. ** [SQLITE_INTEGER | datatype code] for the initial data type
  4138. ** of the result column. The returned value is one of [SQLITE_INTEGER],
  4139. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  4140. ** returned by sqlite3_column_type() is only meaningful if no type
  4141. ** conversions have occurred as described below. After a type conversion,
  4142. ** the value returned by sqlite3_column_type() is undefined. Future
  4143. ** versions of SQLite may change the behavior of sqlite3_column_type()
  4144. ** following a type conversion.
  4145. **
  4146. ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  4147. ** routine returns the number of bytes in that BLOB or string.
  4148. ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  4149. ** the string to UTF-8 and then returns the number of bytes.
  4150. ** If the result is a numeric value then sqlite3_column_bytes() uses
  4151. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  4152. ** the number of bytes in that string.
  4153. ** The value returned does not include the zero terminator at the end
  4154. ** of the string. For clarity: the value returned is the number of
  4155. ** bytes in the string, not the number of characters.
  4156. **
  4157. ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  4158. ** even empty strings, are always zero terminated. The return
  4159. ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
  4160. ** pointer, possibly even a NULL pointer.
  4161. **
  4162. ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
  4163. ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
  4164. ** The zero terminator is not included in this count.
  4165. **
  4166. ** The object returned by [sqlite3_column_value()] is an
  4167. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  4168. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  4169. ** If the [unprotected sqlite3_value] object returned by
  4170. ** [sqlite3_column_value()] is used in any other way, including calls
  4171. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  4172. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  4173. **
  4174. ** These routines attempt to convert the value where appropriate. For
  4175. ** example, if the internal representation is FLOAT and a text result
  4176. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  4177. ** conversion automatically. The following table details the conversions
  4178. ** that are applied:
  4179. **
  4180. ** <blockquote>
  4181. ** <table border="1">
  4182. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  4183. **
  4184. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  4185. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  4186. ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
  4187. ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
  4188. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  4189. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  4190. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  4191. ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
  4192. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  4193. ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
  4194. ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
  4195. ** <tr><td> TEXT <td> FLOAT <td> Use atof()
  4196. ** <tr><td> TEXT <td> BLOB <td> No change
  4197. ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
  4198. ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
  4199. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4200. ** </table>
  4201. ** </blockquote>
  4202. **
  4203. ** The table above makes reference to standard C library functions atoi()
  4204. ** and atof(). SQLite does not really use these functions. It has its
  4205. ** own equivalent internal routines. The atoi() and atof() names are
  4206. ** used in the table for brevity and because they are familiar to most
  4207. ** C programmers.
  4208. **
  4209. ** Note that when type conversions occur, pointers returned by prior
  4210. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4211. ** sqlite3_column_text16() may be invalidated.
  4212. ** Type conversions and pointer invalidations might occur
  4213. ** in the following cases:
  4214. **
  4215. ** <ul>
  4216. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4217. ** sqlite3_column_text16() is called. A zero-terminator might
  4218. ** need to be added to the string.</li>
  4219. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4220. ** sqlite3_column_text16() is called. The content must be converted
  4221. ** to UTF-16.</li>
  4222. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4223. ** sqlite3_column_text() is called. The content must be converted
  4224. ** to UTF-8.</li>
  4225. ** </ul>
  4226. **
  4227. ** Conversions between UTF-16be and UTF-16le are always done in place and do
  4228. ** not invalidate a prior pointer, though of course the content of the buffer
  4229. ** that the prior pointer points to will have been modified. Other kinds
  4230. ** of conversion are done in place when it is possible, but sometimes they
  4231. ** are not possible and in those cases prior pointers are invalidated.
  4232. **
  4233. ** The safest and easiest to remember policy is to invoke these routines
  4234. ** in one of the following ways:
  4235. **
  4236. ** <ul>
  4237. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4238. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4239. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4240. ** </ul>
  4241. **
  4242. ** In other words, you should call sqlite3_column_text(),
  4243. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4244. ** into the desired format, then invoke sqlite3_column_bytes() or
  4245. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4246. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4247. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4248. ** with calls to sqlite3_column_bytes().
  4249. **
  4250. ** The pointers returned are valid until a type conversion occurs as
  4251. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4252. ** [sqlite3_finalize()] is called. The memory space used to hold strings
  4253. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  4254. ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4255. ** [sqlite3_free()].
  4256. **
  4257. ** If a memory allocation error occurs during the evaluation of any
  4258. ** of these routines, a default value is returned. The default value
  4259. ** is either the integer 0, the floating point number 0.0, or a NULL
  4260. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4261. ** [SQLITE_NOMEM].
  4262. **
  4263. ** INVARIANTS:
  4264. **
  4265. ** {H13803} The [sqlite3_column_blob(S,N)] interface converts the
  4266. ** Nth column in the current row of the result set for
  4267. ** the [prepared statement] S into a BLOB and then returns a
  4268. ** pointer to the converted value.
  4269. **
  4270. ** {H13806} The [sqlite3_column_bytes(S,N)] interface returns the
  4271. ** number of bytes in the BLOB or string (exclusive of the
  4272. ** zero terminator on the string) that was returned by the
  4273. ** most recent call to [sqlite3_column_blob(S,N)] or
  4274. ** [sqlite3_column_text(S,N)].
  4275. **
  4276. ** {H13809} The [sqlite3_column_bytes16(S,N)] interface returns the
  4277. ** number of bytes in the string (exclusive of the
  4278. ** zero terminator on the string) that was returned by the
  4279. ** most recent call to [sqlite3_column_text16(S,N)].
  4280. **
  4281. ** {H13812} The [sqlite3_column_double(S,N)] interface converts the
  4282. ** Nth column in the current row of the result set for the
  4283. ** [prepared statement] S into a floating point value and
  4284. ** returns a copy of that value.
  4285. **
  4286. ** {H13815} The [sqlite3_column_int(S,N)] interface converts the
  4287. ** Nth column in the current row of the result set for the
  4288. ** [prepared statement] S into a 64-bit signed integer and
  4289. ** returns the lower 32 bits of that integer.
  4290. **
  4291. ** {H13818} The [sqlite3_column_int64(S,N)] interface converts the
  4292. ** Nth column in the current row of the result set for the
  4293. ** [prepared statement] S into a 64-bit signed integer and
  4294. ** returns a copy of that integer.
  4295. **
  4296. ** {H13821} The [sqlite3_column_text(S,N)] interface converts the
  4297. ** Nth column in the current row of the result set for
  4298. ** the [prepared statement] S into a zero-terminated UTF-8
  4299. ** string and returns a pointer to that string.
  4300. **
  4301. ** {H13824} The [sqlite3_column_text16(S,N)] interface converts the
  4302. ** Nth column in the current row of the result set for the
  4303. ** [prepared statement] S into a zero-terminated 2-byte
  4304. ** aligned UTF-16 native byte order string and returns
  4305. ** a pointer to that string.
  4306. **
  4307. ** {H13827} The [sqlite3_column_type(S,N)] interface returns
  4308. ** one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
  4309. ** [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
  4310. ** the Nth column in the current row of the result set for
  4311. ** the [prepared statement] S.
  4312. **
  4313. ** {H13830} The [sqlite3_column_value(S,N)] interface returns a
  4314. ** pointer to an [unprotected sqlite3_value] object for the
  4315. ** Nth column in the current row of the result set for
  4316. ** the [prepared statement] S.
  4317. */
  4318. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4319. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4320. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4321. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  4322. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  4323. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4324. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  4325. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4326. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  4327. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  4328. /*
  4329. ** CAPI3REF: Destroy A Prepared Statement Object {H13300} <S70300><S30100>
  4330. **
  4331. ** The sqlite3_finalize() function is called to delete a [prepared statement].
  4332. ** If the statement was executed successfully or not executed at all, then
  4333. ** SQLITE_OK is returned. If execution of the statement failed then an
  4334. ** [error code] or [extended error code] is returned.
  4335. **
  4336. ** This routine can be called at any point during the execution of the
  4337. ** [prepared statement]. If the virtual machine has not
  4338. ** completed execution when this routine is called, that is like
  4339. ** encountering an error or an [sqlite3_interrupt | interrupt].
  4340. ** Incomplete updates may be rolled back and transactions canceled,
  4341. ** depending on the circumstances, and the
  4342. ** [error code] returned will be [SQLITE_ABORT].
  4343. **
  4344. ** INVARIANTS:
  4345. **
  4346. ** {H11302} The [sqlite3_finalize(S)] interface destroys the
  4347. ** [prepared statement] S and releases all
  4348. ** memory and file resources held by that object.
  4349. **
  4350. ** {H11304} If the most recent call to [sqlite3_step(S)] for the
  4351. ** [prepared statement] S returned an error,
  4352. ** then [sqlite3_finalize(S)] returns that same error.
  4353. */
  4354. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  4355. /*
  4356. ** CAPI3REF: Reset A Prepared Statement Object {H13330} <S70300>
  4357. **
  4358. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4359. ** object back to its initial state, ready to be re-executed.
  4360. ** Any SQL statement variables that had values bound to them using
  4361. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4362. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4363. **
  4364. ** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4365. ** back to the beginning of its program.
  4366. **
  4367. ** {H11334} If the most recent call to [sqlite3_step(S)] for the
  4368. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4369. ** or if [sqlite3_step(S)] has never before been called on S,
  4370. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4371. **
  4372. ** {H11336} If the most recent call to [sqlite3_step(S)] for the
  4373. ** [prepared statement] S indicated an error, then
  4374. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4375. **
  4376. ** {H11338} The [sqlite3_reset(S)] interface does not change the values
  4377. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4378. */
  4379. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  4380. /*
  4381. ** CAPI3REF: Create Or Redefine SQL Functions {H16100} <S20200>
  4382. ** KEYWORDS: {function creation routines}
  4383. ** KEYWORDS: {application-defined SQL function}
  4384. ** KEYWORDS: {application-defined SQL functions}
  4385. **
  4386. ** These two functions (collectively known as "function creation routines")
  4387. ** are used to add SQL functions or aggregates or to redefine the behavior
  4388. ** of existing SQL functions or aggregates. The only difference between the
  4389. ** two is that the second parameter, the name of the (scalar) function or
  4390. ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
  4391. ** for sqlite3_create_function16().
  4392. **
  4393. ** The first parameter is the [database connection] to which the SQL
  4394. ** function is to be added. If a single program uses more than one database
  4395. ** connection internally, then SQL functions must be added individually to
  4396. ** each database connection.
  4397. **
  4398. ** The second parameter is the name of the SQL function to be created or
  4399. ** redefined. The length of the name is limited to 255 bytes, exclusive of
  4400. ** the zero-terminator. Note that the name length limit is in bytes, not
  4401. ** characters. Any attempt to create a function with a longer name
  4402. ** will result in [SQLITE_ERROR] being returned.
  4403. **
  4404. ** The third parameter (nArg)
  4405. ** is the number of arguments that the SQL function or
  4406. ** aggregate takes. If this parameter is negative, then the SQL function or
  4407. ** aggregate may take any number of arguments.
  4408. **
  4409. ** The fourth parameter, eTextRep, specifies what
  4410. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4411. ** its parameters. Any SQL function implementation should be able to work
  4412. ** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
  4413. ** more efficient with one encoding than another. It is allowed to
  4414. ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  4415. ** times with the same function but with different values of eTextRep.
  4416. ** When multiple implementations of the same function are available, SQLite
  4417. ** will pick the one that involves the least amount of data conversion.
  4418. ** If there is only a single implementation which does not care what text
  4419. ** encoding is used, then the fourth argument should be [SQLITE_ANY].
  4420. **
  4421. ** The fifth parameter is an arbitrary pointer. The implementation of the
  4422. ** function can gain access to this pointer using [sqlite3_user_data()].
  4423. **
  4424. ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
  4425. ** pointers to C-language functions that implement the SQL function or
  4426. ** aggregate. A scalar SQL function requires an implementation of the xFunc
  4427. ** callback only, NULL pointers should be passed as the xStep and xFinal
  4428. ** parameters. An aggregate SQL function requires an implementation of xStep
  4429. ** and xFinal and NULL should be passed for xFunc. To delete an existing
  4430. ** SQL function or aggregate, pass NULL for all three function callbacks.
  4431. **
  4432. ** It is permitted to register multiple implementations of the same
  4433. ** functions with the same name but with either differing numbers of
  4434. ** arguments or differing preferred text encodings. SQLite will use
  4435. ** the implementation most closely matches the way in which the
  4436. ** SQL function is used. A function implementation with a non-negative
  4437. ** nArg parameter is a better match than a function implementation with
  4438. ** a negative nArg. A function where the preferred text encoding
  4439. ** matches the database encoding is a better
  4440. ** match than a function where the encoding is different.
  4441. ** A function where the encoding difference is between UTF16le and UTF16be
  4442. ** is a closer match than a function where the encoding difference is
  4443. ** between UTF8 and UTF16.
  4444. **
  4445. ** Built-in functions may be overloaded by new application-defined functions.
  4446. ** The first application-defined function with a given name overrides all
  4447. ** built-in functions in the same [database connection] with the same name.
  4448. ** Subsequent application-defined functions of the same name only override
  4449. ** prior application-defined functions that are an exact match for the
  4450. ** number of parameters and preferred encoding.
  4451. **
  4452. ** An application-defined function is permitted to call other
  4453. ** SQLite interfaces. However, such calls must not
  4454. ** close the database connection nor finalize or reset the prepared
  4455. ** statement in which the function is running.
  4456. **
  4457. ** INVARIANTS:
  4458. **
  4459. ** {H16103} The [sqlite3_create_function16(D,X,...)] interface shall behave
  4460. ** as [sqlite3_create_function(D,X,...)] in every way except that it
  4461. ** interprets the X argument as zero-terminated UTF-16
  4462. ** native byte order instead of as zero-terminated UTF-8.
  4463. **
  4464. ** {H16106} A successful invocation of the
  4465. ** [sqlite3_create_function(D,X,N,E,...)] interface shall register
  4466. ** or replaces callback functions in the [database connection] D
  4467. ** used to implement the SQL function named X with N parameters
  4468. ** and having a preferred text encoding of E.
  4469. **
  4470. ** {H16109} A successful call to [sqlite3_create_function(D,X,N,E,P,F,S,L)]
  4471. ** shall replace the P, F, S, and L values from any prior calls with
  4472. ** the same D, X, N, and E values.
  4473. **
  4474. ** {H16112} The [sqlite3_create_function(D,X,...)] interface shall fail
  4475. ** if the SQL function name X is
  4476. ** longer than 255 bytes exclusive of the zero terminator.
  4477. **
  4478. ** {H16118} The [sqlite3_create_function(D,X,N,E,P,F,S,L)] interface
  4479. ** shall fail unless either F is NULL and S and L are non-NULL or
  4480. *** F is non-NULL and S and L are NULL.
  4481. **
  4482. ** {H16121} The [sqlite3_create_function(D,...)] interface shall fails with an
  4483. ** error code of [SQLITE_BUSY] if there exist [prepared statements]
  4484. ** associated with the [database connection] D.
  4485. **
  4486. ** {H16124} The [sqlite3_create_function(D,X,N,...)] interface shall fail with
  4487. ** an error code of [SQLITE_ERROR] if parameter N is less
  4488. ** than -1 or greater than 127.
  4489. **
  4490. ** {H16127} When N is non-negative, the [sqlite3_create_function(D,X,N,...)]
  4491. ** interface shall register callbacks to be invoked for the
  4492. ** SQL function
  4493. ** named X when the number of arguments to the SQL function is
  4494. ** exactly N.
  4495. **
  4496. ** {H16130} When N is -1, the [sqlite3_create_function(D,X,N,...)]
  4497. ** interface shall register callbacks to be invoked for the SQL
  4498. ** function named X with any number of arguments.
  4499. **
  4500. ** {H16133} When calls to [sqlite3_create_function(D,X,N,...)]
  4501. ** specify multiple implementations of the same function X
  4502. ** and when one implementation has N>=0 and the other has N=(-1)
  4503. ** the implementation with a non-zero N shall be preferred.
  4504. **
  4505. ** {H16136} When calls to [sqlite3_create_function(D,X,N,E,...)]
  4506. ** specify multiple implementations of the same function X with
  4507. ** the same number of arguments N but with different
  4508. ** encodings E, then the implementation where E matches the
  4509. ** database encoding shall preferred.
  4510. **
  4511. ** {H16139} For an aggregate SQL function created using
  4512. ** [sqlite3_create_function(D,X,N,E,P,0,S,L)] the finalizer
  4513. ** function L shall always be invoked exactly once if the
  4514. ** step function S is called one or more times.
  4515. **
  4516. ** {H16142} When SQLite invokes either the xFunc or xStep function of
  4517. ** an application-defined SQL function or aggregate created
  4518. ** by [sqlite3_create_function()] or [sqlite3_create_function16()],
  4519. ** then the array of [sqlite3_value] objects passed as the
  4520. ** third parameter shall be [protected sqlite3_value] objects.
  4521. */
  4522. SQLITE_API int sqlite3_create_function(
  4523. sqlite3 *db,
  4524. const char *zFunctionName,
  4525. int nArg,
  4526. int eTextRep,
  4527. void *pApp,
  4528. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4529. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4530. void (*xFinal)(sqlite3_context*)
  4531. );
  4532. SQLITE_API int sqlite3_create_function16(
  4533. sqlite3 *db,
  4534. const void *zFunctionName,
  4535. int nArg,
  4536. int eTextRep,
  4537. void *pApp,
  4538. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4539. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4540. void (*xFinal)(sqlite3_context*)
  4541. );
  4542. /*
  4543. ** CAPI3REF: Text Encodings {H10267} <S50200> <H16100>
  4544. **
  4545. ** These constant define integer codes that represent the various
  4546. ** text encodings supported by SQLite.
  4547. */
  4548. #define SQLITE_UTF8 1
  4549. #define SQLITE_UTF16LE 2
  4550. #define SQLITE_UTF16BE 3
  4551. #define SQLITE_UTF16 4 /* Use native byte order */
  4552. #define SQLITE_ANY 5 /* sqlite3_create_function only */
  4553. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4554. /*
  4555. ** CAPI3REF: Deprecated Functions
  4556. ** DEPRECATED
  4557. **
  4558. ** These functions are [deprecated]. In order to maintain
  4559. ** backwards compatibility with older code, these functions continue
  4560. ** to be supported. However, new applications should avoid
  4561. ** the use of these functions. To help encourage people to avoid
  4562. ** using these functions, we are not going to tell you what they do.
  4563. */
  4564. #ifndef SQLITE_OMIT_DEPRECATED
  4565. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  4566. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  4567. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4568. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  4569. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  4570. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
  4571. #endif
  4572. /*
  4573. ** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} <S20200>
  4574. **
  4575. ** The C-language implementation of SQL functions and aggregates uses
  4576. ** this set of interface routines to access the parameter values on
  4577. ** the function or aggregate.
  4578. **
  4579. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4580. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4581. ** define callbacks that implement the SQL functions and aggregates.
  4582. ** The 4th parameter to these callbacks is an array of pointers to
  4583. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4584. ** each parameter to the SQL function. These routines are used to
  4585. ** extract values from the [sqlite3_value] objects.
  4586. **
  4587. ** These routines work only with [protected sqlite3_value] objects.
  4588. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4589. ** object results in undefined behavior.
  4590. **
  4591. ** These routines work just like the corresponding [column access functions]
  4592. ** except that these routines take a single [protected sqlite3_value] object
  4593. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4594. **
  4595. ** The sqlite3_value_text16() interface extracts a UTF-16 string
  4596. ** in the native byte-order of the host machine. The
  4597. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4598. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4599. **
  4600. ** The sqlite3_value_numeric_type() interface attempts to apply
  4601. ** numeric affinity to the value. This means that an attempt is
  4602. ** made to convert the value to an integer or floating point. If
  4603. ** such a conversion is possible without loss of information (in other
  4604. ** words, if the value is a string that looks like a number)
  4605. ** then the conversion is performed. Otherwise no conversion occurs.
  4606. ** The [SQLITE_INTEGER | datatype] after conversion is returned.
  4607. **
  4608. ** Please pay particular attention to the fact that the pointer returned
  4609. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4610. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4611. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4612. ** or [sqlite3_value_text16()].
  4613. **
  4614. ** These routines must be called from the same thread as
  4615. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4616. **
  4617. ** INVARIANTS:
  4618. **
  4619. ** {H15103} The [sqlite3_value_blob(V)] interface converts the
  4620. ** [protected sqlite3_value] object V into a BLOB and then
  4621. ** returns a pointer to the converted value.
  4622. **
  4623. ** {H15106} The [sqlite3_value_bytes(V)] interface returns the
  4624. ** number of bytes in the BLOB or string (exclusive of the
  4625. ** zero terminator on the string) that was returned by the
  4626. ** most recent call to [sqlite3_value_blob(V)] or
  4627. ** [sqlite3_value_text(V)].
  4628. **
  4629. ** {H15109} The [sqlite3_value_bytes16(V)] interface returns the
  4630. ** number of bytes in the string (exclusive of the
  4631. ** zero terminator on the string) that was returned by the
  4632. ** most recent call to [sqlite3_value_text16(V)],
  4633. ** [sqlite3_value_text16be(V)], or [sqlite3_value_text16le(V)].
  4634. **
  4635. ** {H15112} The [sqlite3_value_double(V)] interface converts the
  4636. ** [protected sqlite3_value] object V into a floating point value and
  4637. ** returns a copy of that value.
  4638. **
  4639. ** {H15115} The [sqlite3_value_int(V)] interface converts the
  4640. ** [protected sqlite3_value] object V into a 64-bit signed integer and
  4641. ** returns the lower 32 bits of that integer.
  4642. **
  4643. ** {H15118} The [sqlite3_value_int64(V)] interface converts the
  4644. ** [protected sqlite3_value] object V into a 64-bit signed integer and
  4645. ** returns a copy of that integer.
  4646. **
  4647. ** {H15121} The [sqlite3_value_text(V)] interface converts the
  4648. ** [protected sqlite3_value] object V into a zero-terminated UTF-8
  4649. ** string and returns a pointer to that string.
  4650. **
  4651. ** {H15124} The [sqlite3_value_text16(V)] interface converts the
  4652. ** [protected sqlite3_value] object V into a zero-terminated 2-byte
  4653. ** aligned UTF-16 native byte order
  4654. ** string and returns a pointer to that string.
  4655. **
  4656. ** {H15127} The [sqlite3_value_text16be(V)] interface converts the
  4657. ** [protected sqlite3_value] object V into a zero-terminated 2-byte
  4658. ** aligned UTF-16 big-endian
  4659. ** string and returns a pointer to that string.
  4660. **
  4661. ** {H15130} The [sqlite3_value_text16le(V)] interface converts the
  4662. ** [protected sqlite3_value] object V into a zero-terminated 2-byte
  4663. ** aligned UTF-16 little-endian
  4664. ** string and returns a pointer to that string.
  4665. **
  4666. ** {H15133} The [sqlite3_value_type(V)] interface returns
  4667. ** one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
  4668. ** [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
  4669. ** the [sqlite3_value] object V.
  4670. **
  4671. ** {H15136} The [sqlite3_value_numeric_type(V)] interface converts
  4672. ** the [protected sqlite3_value] object V into either an integer or
  4673. ** a floating point value if it can do so without loss of
  4674. ** information, and returns one of [SQLITE_NULL],
  4675. ** [SQLITE_INTEGER], [SQLITE_FLOAT], [SQLITE_TEXT], or
  4676. ** [SQLITE_BLOB] as appropriate for the
  4677. ** [protected sqlite3_value] object V after the conversion attempt.
  4678. */
  4679. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4680. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4681. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4682. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4683. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4684. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4685. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4686. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4687. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4688. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4689. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4690. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4691. /*
  4692. ** CAPI3REF: Obtain Aggregate Function Context {H16210} <S20200>
  4693. **
  4694. ** The implementation of aggregate SQL functions use this routine to allocate
  4695. ** a structure for storing their state.
  4696. **
  4697. ** The first time the sqlite3_aggregate_context() routine is called for a
  4698. ** particular aggregate, SQLite allocates nBytes of memory, zeroes out that
  4699. ** memory, and returns a pointer to it. On second and subsequent calls to
  4700. ** sqlite3_aggregate_context() for the same aggregate function index,
  4701. ** the same buffer is returned. The implementation of the aggregate can use
  4702. ** the returned buffer to accumulate data.
  4703. **
  4704. ** SQLite automatically frees the allocated buffer when the aggregate
  4705. ** query concludes.
  4706. **
  4707. ** The first parameter should be a copy of the
  4708. ** [sqlite3_context | SQL function context] that is the first parameter
  4709. ** to the callback routine that implements the aggregate function.
  4710. **
  4711. ** This routine must be called from the same thread in which
  4712. ** the aggregate SQL function is running.
  4713. **
  4714. ** INVARIANTS:
  4715. **
  4716. ** {H16211} The first invocation of [sqlite3_aggregate_context(C,N)] for
  4717. ** a particular instance of an aggregate function (for a particular
  4718. ** context C) causes SQLite to allocate N bytes of memory,
  4719. ** zero that memory, and return a pointer to the allocated memory.
  4720. **
  4721. ** {H16213} If a memory allocation error occurs during
  4722. ** [sqlite3_aggregate_context(C,N)] then the function returns 0.
  4723. **
  4724. ** {H16215} Second and subsequent invocations of
  4725. ** [sqlite3_aggregate_context(C,N)] for the same context pointer C
  4726. ** ignore the N parameter and return a pointer to the same
  4727. ** block of memory returned by the first invocation.
  4728. **
  4729. ** {H16217} The memory allocated by [sqlite3_aggregate_context(C,N)] is
  4730. ** automatically freed on the next call to [sqlite3_reset()]
  4731. ** or [sqlite3_finalize()] for the [prepared statement] containing
  4732. ** the aggregate function associated with context C.
  4733. */
  4734. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4735. /*
  4736. ** CAPI3REF: User Data For Functions {H16240} <S20200>
  4737. **
  4738. ** The sqlite3_user_data() interface returns a copy of
  4739. ** the pointer that was the pUserData parameter (the 5th parameter)
  4740. ** of the [sqlite3_create_function()]
  4741. ** and [sqlite3_create_function16()] routines that originally
  4742. ** registered the application defined function. {END}
  4743. **
  4744. ** This routine must be called from the same thread in which
  4745. ** the application-defined function is running.
  4746. **
  4747. ** INVARIANTS:
  4748. **
  4749. ** {H16243} The [sqlite3_user_data(C)] interface returns a copy of the
  4750. ** P pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
  4751. ** or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
  4752. ** registered the SQL function associated with [sqlite3_context] C.
  4753. */
  4754. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4755. /*
  4756. ** CAPI3REF: Database Connection For Functions {H16250} <S60600><S20200>
  4757. **
  4758. ** The sqlite3_context_db_handle() interface returns a copy of
  4759. ** the pointer to the [database connection] (the 1st parameter)
  4760. ** of the [sqlite3_create_function()]
  4761. ** and [sqlite3_create_function16()] routines that originally
  4762. ** registered the application defined function.
  4763. **
  4764. ** INVARIANTS:
  4765. **
  4766. ** {H16253} The [sqlite3_context_db_handle(C)] interface returns a copy of the
  4767. ** D pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
  4768. ** or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
  4769. ** registered the SQL function associated with [sqlite3_context] C.
  4770. */
  4771. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4772. /*
  4773. ** CAPI3REF: Function Auxiliary Data {H16270} <S20200>
  4774. **
  4775. ** The following two functions may be used by scalar SQL functions to
  4776. ** associate metadata with argument values. If the same value is passed to
  4777. ** multiple invocations of the same SQL function during query execution, under
  4778. ** some circumstances the associated metadata may be preserved. This may
  4779. ** be used, for example, to add a regular-expression matching scalar
  4780. ** function. The compiled version of the regular expression is stored as
  4781. ** metadata associated with the SQL value passed as the regular expression
  4782. ** pattern. The compiled regular expression can be reused on multiple
  4783. ** invocations of the same function so that the original pattern string
  4784. ** does not need to be recompiled on each invocation.
  4785. **
  4786. ** The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4787. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4788. ** value to the application-defined function. If no metadata has been ever
  4789. ** been set for the Nth argument of the function, or if the corresponding
  4790. ** function parameter has changed since the meta-data was set,
  4791. ** then sqlite3_get_auxdata() returns a NULL pointer.
  4792. **
  4793. ** The sqlite3_set_auxdata() interface saves the metadata
  4794. ** pointed to by its 3rd parameter as the metadata for the N-th
  4795. ** argument of the application-defined function. Subsequent
  4796. ** calls to sqlite3_get_auxdata() might return this data, if it has
  4797. ** not been destroyed.
  4798. ** If it is not NULL, SQLite will invoke the destructor
  4799. ** function given by the 4th parameter to sqlite3_set_auxdata() on
  4800. ** the metadata when the corresponding function parameter changes
  4801. ** or when the SQL statement completes, whichever comes first.
  4802. **
  4803. ** SQLite is free to call the destructor and drop metadata on any
  4804. ** parameter of any function at any time. The only guarantee is that
  4805. ** the destructor will be called before the metadata is dropped.
  4806. **
  4807. ** In practice, metadata is preserved between function calls for
  4808. ** expressions that are constant at compile time. This includes literal
  4809. ** values and SQL variables.
  4810. **
  4811. ** These routines must be called from the same thread in which
  4812. ** the SQL function is running.
  4813. **
  4814. ** INVARIANTS:
  4815. **
  4816. ** {H16272} The [sqlite3_get_auxdata(C,N)] interface returns a pointer
  4817. ** to metadata associated with the Nth parameter of the SQL function
  4818. ** whose context is C, or NULL if there is no metadata associated
  4819. ** with that parameter.
  4820. **
  4821. ** {H16274} The [sqlite3_set_auxdata(C,N,P,D)] interface assigns a metadata
  4822. ** pointer P to the Nth parameter of the SQL function with context C.
  4823. **
  4824. ** {H16276} SQLite will invoke the destructor D with a single argument
  4825. ** which is the metadata pointer P following a call to
  4826. ** [sqlite3_set_auxdata(C,N,P,D)] when SQLite ceases to hold
  4827. ** the metadata.
  4828. **
  4829. ** {H16277} SQLite ceases to hold metadata for an SQL function parameter
  4830. ** when the value of that parameter changes.
  4831. **
  4832. ** {H16278} When [sqlite3_set_auxdata(C,N,P,D)] is invoked, the destructor
  4833. ** is called for any prior metadata associated with the same function
  4834. ** context C and parameter N.
  4835. **
  4836. ** {H16279} SQLite will call destructors for any metadata it is holding
  4837. ** in a particular [prepared statement] S when either
  4838. ** [sqlite3_reset(S)] or [sqlite3_finalize(S)] is called.
  4839. */
  4840. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4841. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4842. /*
  4843. ** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} <S30100>
  4844. **
  4845. ** These are special values for the destructor that is passed in as the
  4846. ** final argument to routines like [sqlite3_result_blob()]. If the destructor
  4847. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4848. ** and will never change. It does not need to be destroyed. The
  4849. ** SQLITE_TRANSIENT value means that the content will likely change in
  4850. ** the near future and that SQLite should make its own private copy of
  4851. ** the content before returning.
  4852. **
  4853. ** The typedef is necessary to work around problems in certain
  4854. ** C++ compilers. See ticket #2191.
  4855. */
  4856. typedef void (*sqlite3_destructor_type)(void*);
  4857. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4858. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4859. /*
  4860. ** CAPI3REF: Setting The Result Of An SQL Function {H16400} <S20200>
  4861. **
  4862. ** These routines are used by the xFunc or xFinal callbacks that
  4863. ** implement SQL functions and aggregates. See
  4864. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4865. ** for additional information.
  4866. **
  4867. ** These functions work very much like the [parameter binding] family of
  4868. ** functions used to bind values to host parameters in prepared statements.
  4869. ** Refer to the [SQL parameter] documentation for additional information.
  4870. **
  4871. ** The sqlite3_result_blob() interface sets the result from
  4872. ** an application-defined function to be the BLOB whose content is pointed
  4873. ** to by the second parameter and which is N bytes long where N is the
  4874. ** third parameter.
  4875. **
  4876. ** The sqlite3_result_zeroblob() interfaces set the result of
  4877. ** the application-defined function to be a BLOB containing all zero
  4878. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4879. **
  4880. ** The sqlite3_result_double() interface sets the result from
  4881. ** an application-defined function to be a floating point value specified
  4882. ** by its 2nd argument.
  4883. **
  4884. ** The sqlite3_result_error() and sqlite3_result_error16() functions
  4885. ** cause the implemented SQL function to throw an exception.
  4886. ** SQLite uses the string pointed to by the
  4887. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4888. ** as the text of an error message. SQLite interprets the error
  4889. ** message string from sqlite3_result_error() as UTF-8. SQLite
  4890. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4891. ** byte order. If the third parameter to sqlite3_result_error()
  4892. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4893. ** message all text up through the first zero character.
  4894. ** If the third parameter to sqlite3_result_error() or
  4895. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4896. ** bytes (not characters) from the 2nd parameter as the error message.
  4897. ** The sqlite3_result_error() and sqlite3_result_error16()
  4898. ** routines make a private copy of the error message text before
  4899. ** they return. Hence, the calling function can deallocate or
  4900. ** modify the text after they return without harm.
  4901. ** The sqlite3_result_error_code() function changes the error code
  4902. ** returned by SQLite as a result of an error in a function. By default,
  4903. ** the error code is SQLITE_ERROR. A subsequent call to sqlite3_result_error()
  4904. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4905. **
  4906. ** The sqlite3_result_toobig() interface causes SQLite to throw an error
  4907. ** indicating that a string or BLOB is to long to represent.
  4908. **
  4909. ** The sqlite3_result_nomem() interface causes SQLite to throw an error
  4910. ** indicating that a memory allocation failed.
  4911. **
  4912. ** The sqlite3_result_int() interface sets the return value
  4913. ** of the application-defined function to be the 32-bit signed integer
  4914. ** value given in the 2nd argument.
  4915. ** The sqlite3_result_int64() interface sets the return value
  4916. ** of the application-defined function to be the 64-bit signed integer
  4917. ** value given in the 2nd argument.
  4918. **
  4919. ** The sqlite3_result_null() interface sets the return value
  4920. ** of the application-defined function to be NULL.
  4921. **
  4922. ** The sqlite3_result_text(), sqlite3_result_text16(),
  4923. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4924. ** set the return value of the application-defined function to be
  4925. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4926. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4927. ** SQLite takes the text result from the application from
  4928. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4929. ** If the 3rd parameter to the sqlite3_result_text* interfaces
  4930. ** is negative, then SQLite takes result text from the 2nd parameter
  4931. ** through the first zero character.
  4932. ** If the 3rd parameter to the sqlite3_result_text* interfaces
  4933. ** is non-negative, then as many bytes (not characters) of the text
  4934. ** pointed to by the 2nd parameter are taken as the application-defined
  4935. ** function result.
  4936. ** If the 4th parameter to the sqlite3_result_text* interfaces
  4937. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4938. ** function as the destructor on the text or BLOB result when it has
  4939. ** finished using that result.
  4940. ** If the 4th parameter to the sqlite3_result_text* interfaces or
  4941. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4942. ** assumes that the text or BLOB result is in constant space and does not
  4943. ** copy the it or call a destructor when it has finished using that result.
  4944. ** If the 4th parameter to the sqlite3_result_text* interfaces
  4945. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4946. ** then SQLite makes a copy of the result into space obtained from
  4947. ** from [sqlite3_malloc()] before it returns.
  4948. **
  4949. ** The sqlite3_result_value() interface sets the result of
  4950. ** the application-defined function to be a copy the
  4951. ** [unprotected sqlite3_value] object specified by the 2nd parameter. The
  4952. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4953. ** so that the [sqlite3_value] specified in the parameter may change or
  4954. ** be deallocated after sqlite3_result_value() returns without harm.
  4955. ** A [protected sqlite3_value] object may always be used where an
  4956. ** [unprotected sqlite3_value] object is required, so either
  4957. ** kind of [sqlite3_value] object can be used with this interface.
  4958. **
  4959. ** If these routines are called from within the different thread
  4960. ** than the one containing the application-defined function that received
  4961. ** the [sqlite3_context] pointer, the results are undefined.
  4962. **
  4963. ** INVARIANTS:
  4964. **
  4965. ** {H16403} The default return value from any SQL function is NULL.
  4966. **
  4967. ** {H16406} The [sqlite3_result_blob(C,V,N,D)] interface changes the
  4968. ** return value of function C to be a BLOB that is N bytes
  4969. ** in length and with content pointed to by V.
  4970. **
  4971. ** {H16409} The [sqlite3_result_double(C,V)] interface changes the
  4972. ** return value of function C to be the floating point value V.
  4973. **
  4974. ** {H16412} The [sqlite3_result_error(C,V,N)] interface changes the return
  4975. ** value of function C to be an exception with error code
  4976. ** [SQLITE_ERROR] and a UTF-8 error message copied from V up to the
  4977. ** first zero byte or until N bytes are read if N is positive.
  4978. **
  4979. ** {H16415} The [sqlite3_result_error16(C,V,N)] interface changes the return
  4980. ** value of function C to be an exception with error code
  4981. ** [SQLITE_ERROR] and a UTF-16 native byte order error message
  4982. ** copied from V up to the first zero terminator or until N bytes
  4983. ** are read if N is positive.
  4984. **
  4985. ** {H16418} The [sqlite3_result_error_toobig(C)] interface changes the return
  4986. ** value of the function C to be an exception with error code
  4987. ** [SQLITE_TOOBIG] and an appropriate error message.
  4988. **
  4989. ** {H16421} The [sqlite3_result_error_nomem(C)] interface changes the return
  4990. ** value of the function C to be an exception with error code
  4991. ** [SQLITE_NOMEM] and an appropriate error message.
  4992. **
  4993. ** {H16424} The [sqlite3_result_error_code(C,E)] interface changes the return
  4994. ** value of the function C to be an exception with error code E.
  4995. ** The error message text is unchanged.
  4996. **
  4997. ** {H16427} The [sqlite3_result_int(C,V)] interface changes the
  4998. ** return value of function C to be the 32-bit integer value V.
  4999. **
  5000. ** {H16430} The [sqlite3_result_int64(C,V)] interface changes the
  5001. ** return value of function C to be the 64-bit integer value V.
  5002. **
  5003. ** {H16433} The [sqlite3_result_null(C)] interface changes the
  5004. ** return value of function C to be NULL.
  5005. **
  5006. ** {H16436} The [sqlite3_result_text(C,V,N,D)] interface changes the
  5007. ** return value of function C to be the UTF-8 string
  5008. ** V up to the first zero if N is negative
  5009. ** or the first N bytes of V if N is non-negative.
  5010. **
  5011. ** {H16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the
  5012. ** return value of function C to be the UTF-16 native byte order
  5013. ** string V up to the first zero if N is negative
  5014. ** or the first N bytes of V if N is non-negative.
  5015. **
  5016. ** {H16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the
  5017. ** return value of function C to be the UTF-16 big-endian
  5018. ** string V up to the first zero if N is negative
  5019. ** or the first N bytes or V if N is non-negative.
  5020. **
  5021. ** {H16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the
  5022. ** return value of function C to be the UTF-16 little-endian
  5023. ** string V up to the first zero if N is negative
  5024. ** or the first N bytes of V if N is non-negative.
  5025. **
  5026. ** {H16448} The [sqlite3_result_value(C,V)] interface changes the
  5027. ** return value of function C to be the [unprotected sqlite3_value]
  5028. ** object V.
  5029. **
  5030. ** {H16451} The [sqlite3_result_zeroblob(C,N)] interface changes the
  5031. ** return value of function C to be an N-byte BLOB of all zeros.
  5032. **
  5033. ** {H16454} The [sqlite3_result_error()] and [sqlite3_result_error16()]
  5034. ** interfaces make a copy of their error message strings before
  5035. ** returning.
  5036. **
  5037. ** {H16457} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
  5038. ** [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
  5039. ** [sqlite3_result_text16be(C,V,N,D)], or
  5040. ** [sqlite3_result_text16le(C,V,N,D)] is the constant [SQLITE_STATIC]
  5041. ** then no destructor is ever called on the pointer V and SQLite
  5042. ** assumes that V is immutable.
  5043. **
  5044. ** {H16460} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
  5045. ** [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
  5046. ** [sqlite3_result_text16be(C,V,N,D)], or
  5047. ** [sqlite3_result_text16le(C,V,N,D)] is the constant
  5048. ** [SQLITE_TRANSIENT] then the interfaces makes a copy of the
  5049. ** content of V and retains the copy.
  5050. **
  5051. ** {H16463} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
  5052. ** [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
  5053. ** [sqlite3_result_text16be(C,V,N,D)], or
  5054. ** [sqlite3_result_text16le(C,V,N,D)] is some value other than
  5055. ** the constants [SQLITE_STATIC] and [SQLITE_TRANSIENT] then
  5056. ** SQLite will invoke the destructor D with V as its only argument
  5057. ** when it has finished with the V value.
  5058. */
  5059. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  5060. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  5061. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  5062. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  5063. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  5064. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  5065. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  5066. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  5067. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  5068. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  5069. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  5070. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  5071. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  5072. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  5073. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  5074. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  5075. /*
  5076. ** CAPI3REF: Define New Collating Sequences {H16600} <S20300>
  5077. **
  5078. ** These functions are used to add new collation sequences to the
  5079. ** [database connection] specified as the first argument.
  5080. **
  5081. ** The name of the new collation sequence is specified as a UTF-8 string
  5082. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  5083. ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
  5084. ** the name is passed as the second function argument.
  5085. **
  5086. ** The third argument may be one of the constants [SQLITE_UTF8],
  5087. ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
  5088. ** routine expects to be passed pointers to strings encoded using UTF-8,
  5089. ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
  5090. ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
  5091. ** the routine expects pointers to 16-bit word aligned strings
  5092. ** of UTF-16 in the native byte order of the host computer.
  5093. **
  5094. ** A pointer to the user supplied routine must be passed as the fifth
  5095. ** argument. If it is NULL, this is the same as deleting the collation
  5096. ** sequence (so that SQLite cannot call it anymore).
  5097. ** Each time the application supplied function is invoked, it is passed
  5098. ** as its first parameter a copy of the void* passed as the fourth argument
  5099. ** to sqlite3_create_collation() or sqlite3_create_collation16().
  5100. **
  5101. ** The remaining arguments to the application-supplied routine are two strings,
  5102. ** each represented by a (length, data) pair and encoded in the encoding
  5103. ** that was passed as the third argument when the collation sequence was
  5104. ** registered. {END} The application defined collation routine should
  5105. ** return negative, zero or positive if the first string is less than,
  5106. ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
  5107. **
  5108. ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  5109. ** except that it takes an extra argument which is a destructor for
  5110. ** the collation. The destructor is called when the collation is
  5111. ** destroyed and is passed a copy of the fourth parameter void* pointer
  5112. ** of the sqlite3_create_collation_v2().
  5113. ** Collations are destroyed when they are overridden by later calls to the
  5114. ** collation creation functions or when the [database connection] is closed
  5115. ** using [sqlite3_close()].
  5116. **
  5117. ** INVARIANTS:
  5118. **
  5119. ** {H16603} A successful call to the
  5120. ** [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface
  5121. ** registers function F as the comparison function used to
  5122. ** implement collation X on the [database connection] B for
  5123. ** databases having encoding E.
  5124. **
  5125. ** {H16604} SQLite understands the X parameter to
  5126. ** [sqlite3_create_collation_v2(B,X,E,P,F,D)] as a zero-terminated
  5127. ** UTF-8 string in which case is ignored for ASCII characters and
  5128. ** is significant for non-ASCII characters.
  5129. **
  5130. ** {H16606} Successive calls to [sqlite3_create_collation_v2(B,X,E,P,F,D)]
  5131. ** with the same values for B, X, and E, override prior values
  5132. ** of P, F, and D.
  5133. **
  5134. ** {H16609} If the destructor D in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
  5135. ** is not NULL then it is called with argument P when the
  5136. ** collating function is dropped by SQLite.
  5137. **
  5138. ** {H16612} A collating function is dropped when it is overloaded.
  5139. **
  5140. ** {H16615} A collating function is dropped when the database connection
  5141. ** is closed using [sqlite3_close()].
  5142. **
  5143. ** {H16618} The pointer P in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
  5144. ** is passed through as the first parameter to the comparison
  5145. ** function F for all subsequent invocations of F.
  5146. **
  5147. ** {H16621} A call to [sqlite3_create_collation(B,X,E,P,F)] is exactly
  5148. ** the same as a call to [sqlite3_create_collation_v2()] with
  5149. ** the same parameters and a NULL destructor.
  5150. **
  5151. ** {H16624} Following a [sqlite3_create_collation_v2(B,X,E,P,F,D)],
  5152. ** SQLite uses the comparison function F for all text comparison
  5153. ** operations on the [database connection] B on text values that
  5154. ** use the collating sequence named X.
  5155. **
  5156. ** {H16627} The [sqlite3_create_collation16(B,X,E,P,F)] works the same
  5157. ** as [sqlite3_create_collation(B,X,E,P,F)] except that the
  5158. ** collation name X is understood as UTF-16 in native byte order
  5159. ** instead of UTF-8.
  5160. **
  5161. ** {H16630} When multiple comparison functions are available for the same
  5162. ** collating sequence, SQLite chooses the one whose text encoding
  5163. ** requires the least amount of conversion from the default
  5164. ** text encoding of the database.
  5165. */
  5166. SQLITE_API int sqlite3_create_collation(
  5167. sqlite3*,
  5168. const char *zName,
  5169. int eTextRep,
  5170. void*,
  5171. int(*xCompare)(void*,int,const void*,int,const void*)
  5172. );
  5173. SQLITE_API int sqlite3_create_collation_v2(
  5174. sqlite3*,
  5175. const char *zName,
  5176. int eTextRep,
  5177. void*,
  5178. int(*xCompare)(void*,int,const void*,int,const void*),
  5179. void(*xDestroy)(void*)
  5180. );
  5181. SQLITE_API int sqlite3_create_collation16(
  5182. sqlite3*,
  5183. const void *zName,
  5184. int eTextRep,
  5185. void*,
  5186. int(*xCompare)(void*,int,const void*,int,const void*)
  5187. );
  5188. /*
  5189. ** CAPI3REF: Collation Needed Callbacks {H16700} <S20300>
  5190. **
  5191. ** To avoid having to register all collation sequences before a database
  5192. ** can be used, a single callback function may be registered with the
  5193. ** [database connection] to be called whenever an undefined collation
  5194. ** sequence is required.
  5195. **
  5196. ** If the function is registered using the sqlite3_collation_needed() API,
  5197. ** then it is passed the names of undefined collation sequences as strings
  5198. ** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used,
  5199. ** the names are passed as UTF-16 in machine native byte order.
  5200. ** A call to either function replaces any existing callback.
  5201. **
  5202. ** When the callback is invoked, the first argument passed is a copy
  5203. ** of the second argument to sqlite3_collation_needed() or
  5204. ** sqlite3_collation_needed16(). The second argument is the database
  5205. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  5206. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  5207. ** sequence function required. The fourth parameter is the name of the
  5208. ** required collation sequence.
  5209. **
  5210. ** The callback function should register the desired collation using
  5211. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  5212. ** [sqlite3_create_collation_v2()].
  5213. **
  5214. ** INVARIANTS:
  5215. **
  5216. ** {H16702} A successful call to [sqlite3_collation_needed(D,P,F)]
  5217. ** or [sqlite3_collation_needed16(D,P,F)] causes
  5218. ** the [database connection] D to invoke callback F with first
  5219. ** parameter P whenever it needs a comparison function for a
  5220. ** collating sequence that it does not know about.
  5221. **
  5222. ** {H16704} Each successful call to [sqlite3_collation_needed()] or
  5223. ** [sqlite3_collation_needed16()] overrides the callback registered
  5224. ** on the same [database connection] by prior calls to either
  5225. ** interface.
  5226. **
  5227. ** {H16706} The name of the requested collating function passed in the
  5228. ** 4th parameter to the callback is in UTF-8 if the callback
  5229. ** was registered using [sqlite3_collation_needed()] and
  5230. ** is in UTF-16 native byte order if the callback was
  5231. ** registered using [sqlite3_collation_needed16()].
  5232. */
  5233. SQLITE_API int sqlite3_collation_needed(
  5234. sqlite3*,
  5235. void*,
  5236. void(*)(void*,sqlite3*,int eTextRep,const char*)
  5237. );
  5238. SQLITE_API int sqlite3_collation_needed16(
  5239. sqlite3*,
  5240. void*,
  5241. void(*)(void*,sqlite3*,int eTextRep,const void*)
  5242. );
  5243. /*
  5244. ** Specify the key for an encrypted database. This routine should be
  5245. ** called right after sqlite3_open().
  5246. **
  5247. ** The code to implement this API is not available in the public release
  5248. ** of SQLite.
  5249. */
  5250. SQLITE_API int sqlite3_key(
  5251. sqlite3 *db, /* Database to be rekeyed */
  5252. const void *pKey, int nKey /* The key */
  5253. );
  5254. /*
  5255. ** Change the key on an open database. If the current database is not
  5256. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  5257. ** database is decrypted.
  5258. **
  5259. ** The code to implement this API is not available in the public release
  5260. ** of SQLite.
  5261. */
  5262. SQLITE_API int sqlite3_rekey(
  5263. sqlite3 *db, /* Database to be rekeyed */
  5264. const void *pKey, int nKey /* The new key */
  5265. );
  5266. /*
  5267. ** CAPI3REF: Suspend Execution For A Short Time {H10530} <S40410>
  5268. **
  5269. ** The sqlite3_sleep() function causes the current thread to suspend execution
  5270. ** for at least a number of milliseconds specified in its parameter.
  5271. **
  5272. ** If the operating system does not support sleep requests with
  5273. ** millisecond time resolution, then the time will be rounded up to
  5274. ** the nearest second. The number of milliseconds of sleep actually
  5275. ** requested from the operating system is returned.
  5276. **
  5277. ** SQLite implements this interface by calling the xSleep()
  5278. ** method of the default [sqlite3_vfs] object.
  5279. **
  5280. ** INVARIANTS:
  5281. **
  5282. ** {H10533} The [sqlite3_sleep(M)] interface invokes the xSleep
  5283. ** method of the default [sqlite3_vfs|VFS] in order to
  5284. ** suspend execution of the current thread for at least
  5285. ** M milliseconds.
  5286. **
  5287. ** {H10536} The [sqlite3_sleep(M)] interface returns the number of
  5288. ** milliseconds of sleep actually requested of the operating
  5289. ** system, which might be larger than the parameter M.
  5290. */
  5291. SQLITE_API int sqlite3_sleep(int);
  5292. /*
  5293. ** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} <S20000>
  5294. **
  5295. ** If this global variable is made to point to a string which is
  5296. ** the name of a folder (a.k.a. directory), then all temporary files
  5297. ** created by SQLite will be placed in that directory. If this variable
  5298. ** is a NULL pointer, then SQLite performs a search for an appropriate
  5299. ** temporary file directory.
  5300. **
  5301. ** It is not safe to modify this variable once a [database connection]
  5302. ** has been opened. It is intended that this variable be set once
  5303. ** as part of process initialization and before any SQLite interface
  5304. ** routines have been call and remain unchanged thereafter.
  5305. */
  5306. SQLITE_API char *sqlite3_temp_directory;
  5307. /*
  5308. ** CAPI3REF: Test For Auto-Commit Mode {H12930} <S60200>
  5309. ** KEYWORDS: {autocommit mode}
  5310. **
  5311. ** The sqlite3_get_autocommit() interface returns non-zero or
  5312. ** zero if the given database connection is or is not in autocommit mode,
  5313. ** respectively. Autocommit mode is on by default.
  5314. ** Autocommit mode is disabled by a [BEGIN] statement.
  5315. ** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  5316. **
  5317. ** If certain kinds of errors occur on a statement within a multi-statement
  5318. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  5319. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  5320. ** transaction might be rolled back automatically. The only way to
  5321. ** find out whether SQLite automatically rolled back the transaction after
  5322. ** an error is to use this function.
  5323. **
  5324. ** INVARIANTS:
  5325. **
  5326. ** {H12931} The [sqlite3_get_autocommit(D)] interface returns non-zero or
  5327. ** zero if the [database connection] D is or is not in autocommit
  5328. ** mode, respectively.
  5329. **
  5330. ** {H12932} Autocommit mode is on by default.
  5331. **
  5332. ** {H12933} Autocommit mode is disabled by a successful [BEGIN] statement.
  5333. **
  5334. ** {H12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK]
  5335. ** statement.
  5336. **
  5337. ** ASSUMPTIONS:
  5338. **
  5339. ** {A12936} If another thread changes the autocommit status of the database
  5340. ** connection while this routine is running, then the return value
  5341. ** is undefined.
  5342. */
  5343. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  5344. /*
  5345. ** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} <S60600>
  5346. **
  5347. ** The sqlite3_db_handle interface returns the [database connection] handle
  5348. ** to which a [prepared statement] belongs. The database handle returned by
  5349. ** sqlite3_db_handle is the same database handle that was the first argument
  5350. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  5351. ** create the statement in the first place.
  5352. **
  5353. ** INVARIANTS:
  5354. **
  5355. ** {H13123} The [sqlite3_db_handle(S)] interface returns a pointer
  5356. ** to the [database connection] associated with the
  5357. ** [prepared statement] S.
  5358. */
  5359. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  5360. /*
  5361. ** CAPI3REF: Find the next prepared statement {H13140} <S60600>
  5362. **
  5363. ** This interface returns a pointer to the next [prepared statement] after
  5364. ** pStmt associated with the [database connection] pDb. If pStmt is NULL
  5365. ** then this interface returns a pointer to the first prepared statement
  5366. ** associated with the database connection pDb. If no prepared statement
  5367. ** satisfies the conditions of this routine, it returns NULL.
  5368. **
  5369. ** INVARIANTS:
  5370. **
  5371. ** {H13143} If D is a [database connection] that holds one or more
  5372. ** unfinalized [prepared statements] and S is a NULL pointer,
  5373. ** then [sqlite3_next_stmt(D, S)] routine shall return a pointer
  5374. ** to one of the prepared statements associated with D.
  5375. **
  5376. ** {H13146} If D is a [database connection] that holds no unfinalized
  5377. ** [prepared statements] and S is a NULL pointer, then
  5378. ** [sqlite3_next_stmt(D, S)] routine shall return a NULL pointer.
  5379. **
  5380. ** {H13149} If S is a [prepared statement] in the [database connection] D
  5381. ** and S is not the last prepared statement in D, then
  5382. ** [sqlite3_next_stmt(D, S)] routine shall return a pointer
  5383. ** to the next prepared statement in D after S.
  5384. **
  5385. ** {H13152} If S is the last [prepared statement] in the
  5386. ** [database connection] D then the [sqlite3_next_stmt(D, S)]
  5387. ** routine shall return a NULL pointer.
  5388. **
  5389. ** ASSUMPTIONS:
  5390. **
  5391. ** {A13154} The [database connection] pointer D in a call to
  5392. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  5393. ** connection and in particular must not be a NULL pointer.
  5394. */
  5395. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  5396. /*
  5397. ** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} <S60400>
  5398. **
  5399. ** The sqlite3_commit_hook() interface registers a callback
  5400. ** function to be invoked whenever a transaction is committed.
  5401. ** Any callback set by a previous call to sqlite3_commit_hook()
  5402. ** for the same database connection is overridden.
  5403. ** The sqlite3_rollback_hook() interface registers a callback
  5404. ** function to be invoked whenever a transaction is committed.
  5405. ** Any callback set by a previous call to sqlite3_commit_hook()
  5406. ** for the same database connection is overridden.
  5407. ** The pArg argument is passed through to the callback.
  5408. ** If the callback on a commit hook function returns non-zero,
  5409. ** then the commit is converted into a rollback.
  5410. **
  5411. ** If another function was previously registered, its
  5412. ** pArg value is returned. Otherwise NULL is returned.
  5413. **
  5414. ** The callback implementation must not do anything that will modify
  5415. ** the database connection that invoked the callback. Any actions
  5416. ** to modify the database connection must be deferred until after the
  5417. ** completion of the [sqlite3_step()] call that triggered the commit
  5418. ** or rollback hook in the first place.
  5419. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5420. ** database connections for the meaning of "modify" in this paragraph.
  5421. **
  5422. ** Registering a NULL function disables the callback.
  5423. **
  5424. ** For the purposes of this API, a transaction is said to have been
  5425. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  5426. ** an error or constraint causes an implicit rollback to occur.
  5427. ** The rollback callback is not invoked if a transaction is
  5428. ** automatically rolled back because the database connection is closed.
  5429. ** The rollback callback is not invoked if a transaction is
  5430. ** rolled back because a commit callback returned non-zero.
  5431. ** <todo> Check on this </todo>
  5432. **
  5433. ** INVARIANTS:
  5434. **
  5435. ** {H12951} The [sqlite3_commit_hook(D,F,P)] interface registers the
  5436. ** callback function F to be invoked with argument P whenever
  5437. ** a transaction commits on the [database connection] D.
  5438. **
  5439. ** {H12952} The [sqlite3_commit_hook(D,F,P)] interface returns the P argument
  5440. ** from the previous call with the same [database connection] D,
  5441. ** or NULL on the first call for a particular database connection D.
  5442. **
  5443. ** {H12953} Each call to [sqlite3_commit_hook()] overwrites the callback
  5444. ** registered by prior calls.
  5445. **
  5446. ** {H12954} If the F argument to [sqlite3_commit_hook(D,F,P)] is NULL
  5447. ** then the commit hook callback is canceled and no callback
  5448. ** is invoked when a transaction commits.
  5449. **
  5450. ** {H12955} If the commit callback returns non-zero then the commit is
  5451. ** converted into a rollback.
  5452. **
  5453. ** {H12961} The [sqlite3_rollback_hook(D,F,P)] interface registers the
  5454. ** callback function F to be invoked with argument P whenever
  5455. ** a transaction rolls back on the [database connection] D.
  5456. **
  5457. ** {H12962} The [sqlite3_rollback_hook(D,F,P)] interface returns the P
  5458. ** argument from the previous call with the same
  5459. ** [database connection] D, or NULL on the first call
  5460. ** for a particular database connection D.
  5461. **
  5462. ** {H12963} Each call to [sqlite3_rollback_hook()] overwrites the callback
  5463. ** registered by prior calls.
  5464. **
  5465. ** {H12964} If the F argument to [sqlite3_rollback_hook(D,F,P)] is NULL
  5466. ** then the rollback hook callback is canceled and no callback
  5467. ** is invoked when a transaction rolls back.
  5468. */
  5469. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  5470. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  5471. /*
  5472. ** CAPI3REF: Data Change Notification Callbacks {H12970} <S60400>
  5473. **
  5474. ** The sqlite3_update_hook() interface registers a callback function
  5475. ** with the [database connection] identified by the first argument
  5476. ** to be invoked whenever a row is updated, inserted or deleted.
  5477. ** Any callback set by a previous call to this function
  5478. ** for the same database connection is overridden.
  5479. **
  5480. ** The second argument is a pointer to the function to invoke when a
  5481. ** row is updated, inserted or deleted.
  5482. ** The first argument to the callback is a copy of the third argument
  5483. ** to sqlite3_update_hook().
  5484. ** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  5485. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  5486. ** to be invoked.
  5487. ** The third and fourth arguments to the callback contain pointers to the
  5488. ** database and table name containing the affected row.
  5489. ** The final callback parameter is the [rowid] of the row.
  5490. ** In the case of an update, this is the [rowid] after the update takes place.
  5491. **
  5492. ** The update hook is not invoked when internal system tables are
  5493. ** modified (i.e. sqlite_master and sqlite_sequence).
  5494. **
  5495. ** The update hook implementation must not do anything that will modify
  5496. ** the database connection that invoked the update hook. Any actions
  5497. ** to modify the database connection must be deferred until after the
  5498. ** completion of the [sqlite3_step()] call that triggered the update hook.
  5499. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5500. ** database connections for the meaning of "modify" in this paragraph.
  5501. **
  5502. ** If another function was previously registered, its pArg value
  5503. ** is returned. Otherwise NULL is returned.
  5504. **
  5505. ** INVARIANTS:
  5506. **
  5507. ** {H12971} The [sqlite3_update_hook(D,F,P)] interface causes the callback
  5508. ** function F to be invoked with first parameter P whenever
  5509. ** a table row is modified, inserted, or deleted on
  5510. ** the [database connection] D.
  5511. **
  5512. ** {H12973} The [sqlite3_update_hook(D,F,P)] interface returns the value
  5513. ** of P for the previous call on the same [database connection] D,
  5514. ** or NULL for the first call.
  5515. **
  5516. ** {H12975} If the update hook callback F in [sqlite3_update_hook(D,F,P)]
  5517. ** is NULL then the no update callbacks are made.
  5518. **
  5519. ** {H12977} Each call to [sqlite3_update_hook(D,F,P)] overrides prior calls
  5520. ** to the same interface on the same [database connection] D.
  5521. **
  5522. ** {H12979} The update hook callback is not invoked when internal system
  5523. ** tables such as sqlite_master and sqlite_sequence are modified.
  5524. **
  5525. ** {H12981} The second parameter to the update callback
  5526. ** is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
  5527. ** depending on the operation that caused the callback to be invoked.
  5528. **
  5529. ** {H12983} The third and fourth arguments to the callback contain pointers
  5530. ** to zero-terminated UTF-8 strings which are the names of the
  5531. ** database and table that is being updated.
  5532. ** {H12985} The final callback parameter is the [rowid] of the row after
  5533. ** the change occurs.
  5534. */
  5535. SQLITE_API void *sqlite3_update_hook(
  5536. sqlite3*,
  5537. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5538. void*
  5539. );
  5540. /*
  5541. ** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} <S30900>
  5542. ** KEYWORDS: {shared cache} {shared cache mode}
  5543. **
  5544. ** This routine enables or disables the sharing of the database cache
  5545. ** and schema data structures between [database connection | connections]
  5546. ** to the same database. Sharing is enabled if the argument is true
  5547. ** and disabled if the argument is false.
  5548. **
  5549. ** Cache sharing is enabled and disabled for an entire process. {END}
  5550. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  5551. ** sharing was enabled or disabled for each thread separately.
  5552. **
  5553. ** The cache sharing mode set by this interface effects all subsequent
  5554. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5555. ** Existing database connections continue use the sharing mode
  5556. ** that was in effect at the time they were opened.
  5557. **
  5558. ** Virtual tables cannot be used with a shared cache. When shared
  5559. ** cache is enabled, the [sqlite3_create_module()] API used to register
  5560. ** virtual tables will always return an error.
  5561. **
  5562. ** This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5563. ** successfully. An [error code] is returned otherwise.
  5564. **
  5565. ** Shared cache is disabled by default. But this might change in
  5566. ** future releases of SQLite. Applications that care about shared
  5567. ** cache setting should set it explicitly.
  5568. **
  5569. ** INVARIANTS:
  5570. **
  5571. ** {H10331} A successful invocation of [sqlite3_enable_shared_cache(B)]
  5572. ** will enable or disable shared cache mode for any subsequently
  5573. ** created [database connection] in the same process.
  5574. **
  5575. ** {H10336} When shared cache is enabled, the [sqlite3_create_module()]
  5576. ** interface will always return an error.
  5577. **
  5578. ** {H10337} The [sqlite3_enable_shared_cache(B)] interface returns
  5579. ** [SQLITE_OK] if shared cache was enabled or disabled successfully.
  5580. **
  5581. ** {H10339} Shared cache is disabled by default.
  5582. */
  5583. SQLITE_API int sqlite3_enable_shared_cache(int);
  5584. /*
  5585. ** CAPI3REF: Attempt To Free Heap Memory {H17340} <S30220>
  5586. **
  5587. ** The sqlite3_release_memory() interface attempts to free N bytes
  5588. ** of heap memory by deallocating non-essential memory allocations
  5589. ** held by the database library. {END} Memory used to cache database
  5590. ** pages to improve performance is an example of non-essential memory.
  5591. ** sqlite3_release_memory() returns the number of bytes actually freed,
  5592. ** which might be more or less than the amount requested.
  5593. **
  5594. ** INVARIANTS:
  5595. **
  5596. ** {H17341} The [sqlite3_release_memory(N)] interface attempts to
  5597. ** free N bytes of heap memory by deallocating non-essential
  5598. ** memory allocations held by the database library.
  5599. **
  5600. ** {H16342} The [sqlite3_release_memory(N)] returns the number
  5601. ** of bytes actually freed, which might be more or less
  5602. ** than the amount requested.
  5603. */
  5604. SQLITE_API int sqlite3_release_memory(int);
  5605. /*
  5606. ** CAPI3REF: Impose A Limit On Heap Size {H17350} <S30220>
  5607. **
  5608. ** The sqlite3_soft_heap_limit() interface places a "soft" limit
  5609. ** on the amount of heap memory that may be allocated by SQLite.
  5610. ** If an internal allocation is requested that would exceed the
  5611. ** soft heap limit, [sqlite3_release_memory()] is invoked one or
  5612. ** more times to free up some space before the allocation is performed.
  5613. **
  5614. ** The limit is called "soft", because if [sqlite3_release_memory()]
  5615. ** cannot free sufficient memory to prevent the limit from being exceeded,
  5616. ** the memory is allocated anyway and the current operation proceeds.
  5617. **
  5618. ** A negative or zero value for N means that there is no soft heap limit and
  5619. ** [sqlite3_release_memory()] will only be called when memory is exhausted.
  5620. ** The default value for the soft heap limit is zero.
  5621. **
  5622. ** SQLite makes a best effort to honor the soft heap limit.
  5623. ** But if the soft heap limit cannot be honored, execution will
  5624. ** continue without error or notification. This is why the limit is
  5625. ** called a "soft" limit. It is advisory only.
  5626. **
  5627. ** Prior to SQLite version 3.5.0, this routine only constrained the memory
  5628. ** allocated by a single thread - the same thread in which this routine
  5629. ** runs. Beginning with SQLite version 3.5.0, the soft heap limit is
  5630. ** applied to all threads. The value specified for the soft heap limit
  5631. ** is an upper bound on the total memory allocation for all threads. In
  5632. ** version 3.5.0 there is no mechanism for limiting the heap usage for
  5633. ** individual threads.
  5634. **
  5635. ** INVARIANTS:
  5636. **
  5637. ** {H16351} The [sqlite3_soft_heap_limit(N)] interface places a soft limit
  5638. ** of N bytes on the amount of heap memory that may be allocated
  5639. ** using [sqlite3_malloc()] or [sqlite3_realloc()] at any point
  5640. ** in time.
  5641. **
  5642. ** {H16352} If a call to [sqlite3_malloc()] or [sqlite3_realloc()] would
  5643. ** cause the total amount of allocated memory to exceed the
  5644. ** soft heap limit, then [sqlite3_release_memory()] is invoked
  5645. ** in an attempt to reduce the memory usage prior to proceeding
  5646. ** with the memory allocation attempt.
  5647. **
  5648. ** {H16353} Calls to [sqlite3_malloc()] or [sqlite3_realloc()] that trigger
  5649. ** attempts to reduce memory usage through the soft heap limit
  5650. ** mechanism continue even if the attempt to reduce memory
  5651. ** usage is unsuccessful.
  5652. **
  5653. ** {H16354} A negative or zero value for N in a call to
  5654. ** [sqlite3_soft_heap_limit(N)] means that there is no soft
  5655. ** heap limit and [sqlite3_release_memory()] will only be
  5656. ** called when memory is completely exhausted.
  5657. **
  5658. ** {H16355} The default value for the soft heap limit is zero.
  5659. **
  5660. ** {H16358} Each call to [sqlite3_soft_heap_limit(N)] overrides the
  5661. ** values set by all prior calls.
  5662. */
  5663. SQLITE_API void sqlite3_soft_heap_limit(int);
  5664. /*
  5665. ** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} <S60300>
  5666. **
  5667. ** This routine returns metadata about a specific column of a specific
  5668. ** database table accessible using the [database connection] handle
  5669. ** passed as the first function argument.
  5670. **
  5671. ** The column is identified by the second, third and fourth parameters to
  5672. ** this function. The second parameter is either the name of the database
  5673. ** (i.e. "main", "temp" or an attached database) containing the specified
  5674. ** table or NULL. If it is NULL, then all attached databases are searched
  5675. ** for the table using the same algorithm used by the database engine to
  5676. ** resolve unqualified table references.
  5677. **
  5678. ** The third and fourth parameters to this function are the table and column
  5679. ** name of the desired column, respectively. Neither of these parameters
  5680. ** may be NULL.
  5681. **
  5682. ** Metadata is returned by writing to the memory locations passed as the 5th
  5683. ** and subsequent parameters to this function. Any of these arguments may be
  5684. ** NULL, in which case the corresponding element of metadata is omitted.
  5685. **
  5686. ** <blockquote>
  5687. ** <table border="1">
  5688. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5689. **
  5690. ** <tr><td> 5th <td> const char* <td> Data type
  5691. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5692. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5693. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5694. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5695. ** </table>
  5696. ** </blockquote>
  5697. **
  5698. ** The memory pointed to by the character pointers returned for the
  5699. ** declaration type and collation sequence is valid only until the next
  5700. ** call to any SQLite API function.
  5701. **
  5702. ** If the specified table is actually a view, an [error code] is returned.
  5703. **
  5704. ** If the specified column is "rowid", "oid" or "_rowid_" and an
  5705. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5706. ** parameters are set for the explicitly declared column. If there is no
  5707. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  5708. ** parameters are set as follows:
  5709. **
  5710. ** <pre>
  5711. ** data type: "INTEGER"
  5712. ** collation sequence: "BINARY"
  5713. ** not null: 0
  5714. ** primary key: 1
  5715. ** auto increment: 0
  5716. ** </pre>
  5717. **
  5718. ** This function may load one or more schemas from database files. If an
  5719. ** error occurs during this process, or if the requested table or column
  5720. ** cannot be found, an [error code] is returned and an error message left
  5721. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).
  5722. **
  5723. ** This API is only available if the library was compiled with the
  5724. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  5725. */
  5726. SQLITE_API int sqlite3_table_column_metadata(
  5727. sqlite3 *db, /* Connection handle */
  5728. const char *zDbName, /* Database name or NULL */
  5729. const char *zTableName, /* Table name */
  5730. const char *zColumnName, /* Column name */
  5731. char const **pzDataType, /* OUTPUT: Declared data type */
  5732. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5733. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5734. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5735. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5736. );
  5737. /*
  5738. ** CAPI3REF: Load An Extension {H12600} <S20500>
  5739. **
  5740. ** This interface loads an SQLite extension library from the named file.
  5741. **
  5742. ** {H12601} The sqlite3_load_extension() interface attempts to load an
  5743. ** SQLite extension library contained in the file zFile.
  5744. **
  5745. ** {H12602} The entry point is zProc.
  5746. **
  5747. ** {H12603} zProc may be 0, in which case the name of the entry point
  5748. ** defaults to "sqlite3_extension_init".
  5749. **
  5750. ** {H12604} The sqlite3_load_extension() interface shall return
  5751. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5752. **
  5753. ** {H12605} If an error occurs and pzErrMsg is not 0, then the
  5754. ** [sqlite3_load_extension()] interface shall attempt to
  5755. ** fill *pzErrMsg with error message text stored in memory
  5756. ** obtained from [sqlite3_malloc()]. {END} The calling function
  5757. ** should free this memory by calling [sqlite3_free()].
  5758. **
  5759. ** {H12606} Extension loading must be enabled using
  5760. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5761. ** otherwise an error will be returned.
  5762. */
  5763. SQLITE_API int sqlite3_load_extension(
  5764. sqlite3 *db, /* Load the extension into this database connection */
  5765. const char *zFile, /* Name of the shared library containing extension */
  5766. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5767. char **pzErrMsg /* Put error message here if not 0 */
  5768. );
  5769. /*
  5770. ** CAPI3REF: Enable Or Disable Extension Loading {H12620} <S20500>
  5771. **
  5772. ** So as not to open security holes in older applications that are
  5773. ** unprepared to deal with extension loading, and as a means of disabling
  5774. ** extension loading while evaluating user-entered SQL, the following API
  5775. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5776. **
  5777. ** Extension loading is off by default. See ticket #1863.
  5778. **
  5779. ** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1
  5780. ** to turn extension loading on and call it with onoff==0 to turn
  5781. ** it back off again.
  5782. **
  5783. ** {H12622} Extension loading is off by default.
  5784. */
  5785. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5786. /*
  5787. ** CAPI3REF: Automatically Load An Extensions {H12640} <S20500>
  5788. **
  5789. ** This API can be invoked at program startup in order to register
  5790. ** one or more statically linked extensions that will be available
  5791. ** to all new [database connections]. {END}
  5792. **
  5793. ** This routine stores a pointer to the extension in an array that is
  5794. ** obtained from [sqlite3_malloc()]. If you run a memory leak checker
  5795. ** on your program and it reports a leak because of this array, invoke
  5796. ** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory.
  5797. **
  5798. ** {H12641} This function registers an extension entry point that is
  5799. ** automatically invoked whenever a new [database connection]
  5800. ** is opened using [sqlite3_open()], [sqlite3_open16()],
  5801. ** or [sqlite3_open_v2()].
  5802. **
  5803. ** {H12642} Duplicate extensions are detected so calling this routine
  5804. ** multiple times with the same extension is harmless.
  5805. **
  5806. ** {H12643} This routine stores a pointer to the extension in an array
  5807. ** that is obtained from [sqlite3_malloc()].
  5808. **
  5809. ** {H12644} Automatic extensions apply across all threads.
  5810. */
  5811. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  5812. /*
  5813. ** CAPI3REF: Reset Automatic Extension Loading {H12660} <S20500>
  5814. **
  5815. ** This function disables all previously registered automatic
  5816. ** extensions. {END} It undoes the effect of all prior
  5817. ** [sqlite3_auto_extension()] calls.
  5818. **
  5819. ** {H12661} This function disables all previously registered
  5820. ** automatic extensions.
  5821. **
  5822. ** {H12662} This function disables automatic extensions in all threads.
  5823. */
  5824. SQLITE_API void sqlite3_reset_auto_extension(void);
  5825. /*
  5826. ****** EXPERIMENTAL - subject to change without notice **************
  5827. **
  5828. ** The interface to the virtual-table mechanism is currently considered
  5829. ** to be experimental. The interface might change in incompatible ways.
  5830. ** If this is a problem for you, do not use the interface at this time.
  5831. **
  5832. ** When the virtual-table mechanism stabilizes, we will declare the
  5833. ** interface fixed, support it indefinitely, and remove this comment.
  5834. */
  5835. /*
  5836. ** Structures used by the virtual table interface
  5837. */
  5838. typedef struct sqlite3_vtab sqlite3_vtab;
  5839. typedef struct sqlite3_index_info sqlite3_index_info;
  5840. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5841. typedef struct sqlite3_module sqlite3_module;
  5842. /*
  5843. ** CAPI3REF: Virtual Table Object {H18000} <S20400>
  5844. ** KEYWORDS: sqlite3_module
  5845. ** EXPERIMENTAL
  5846. **
  5847. ** A module is a class of virtual tables. Each module is defined
  5848. ** by an instance of the following structure. This structure consists
  5849. ** mostly of methods for the module.
  5850. **
  5851. ** This interface is experimental and is subject to change or
  5852. ** removal in future releases of SQLite.
  5853. */
  5854. struct sqlite3_module {
  5855. int iVersion;
  5856. int (*xCreate)(sqlite3*, void *pAux,
  5857. int argc, const char *const*argv,
  5858. sqlite3_vtab **ppVTab, char**);
  5859. int (*xConnect)(sqlite3*, void *pAux,
  5860. int argc, const char *const*argv,
  5861. sqlite3_vtab **ppVTab, char**);
  5862. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5863. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5864. int (*xDestroy)(sqlite3_vtab *pVTab);
  5865. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5866. int (*xClose)(sqlite3_vtab_cursor*);
  5867. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5868. int argc, sqlite3_value **argv);
  5869. int (*xNext)(sqlite3_vtab_cursor*);
  5870. int (*xEof)(sqlite3_vtab_cursor*);
  5871. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5872. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5873. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5874. int (*xBegin)(sqlite3_vtab *pVTab);
  5875. int (*xSync)(sqlite3_vtab *pVTab);
  5876. int (*xCommit)(sqlite3_vtab *pVTab);
  5877. int (*xRollback)(sqlite3_vtab *pVTab);
  5878. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5879. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5880. void **ppArg);
  5881. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5882. };
  5883. /*
  5884. ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
  5885. ** KEYWORDS: sqlite3_index_info
  5886. ** EXPERIMENTAL
  5887. **
  5888. ** The sqlite3_index_info structure and its substructures is used to
  5889. ** pass information into and receive the reply from the xBestIndex
  5890. ** method of an sqlite3_module. The fields under **Inputs** are the
  5891. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5892. ** results into the **Outputs** fields.
  5893. **
  5894. ** The aConstraint[] array records WHERE clause constraints of the form:
  5895. **
  5896. ** <pre>column OP expr</pre>
  5897. **
  5898. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=. The particular operator is
  5899. ** stored in aConstraint[].op. The index of the column is stored in
  5900. ** aConstraint[].iColumn. aConstraint[].usable is TRUE if the
  5901. ** expr on the right-hand side can be evaluated (and thus the constraint
  5902. ** is usable) and false if it cannot.
  5903. **
  5904. ** The optimizer automatically inverts terms of the form "expr OP column"
  5905. ** and makes other simplifications to the WHERE clause in an attempt to
  5906. ** get as many WHERE clause terms into the form shown above as possible.
  5907. ** The aConstraint[] array only reports WHERE clause terms in the correct
  5908. ** form that refer to the particular virtual table being queried.
  5909. **
  5910. ** Information about the ORDER BY clause is stored in aOrderBy[].
  5911. ** Each term of aOrderBy records a column of the ORDER BY clause.
  5912. **
  5913. ** The xBestIndex method must fill aConstraintUsage[] with information
  5914. ** about what parameters to pass to xFilter. If argvIndex>0 then
  5915. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5916. ** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit
  5917. ** is true, then the constraint is assumed to be fully handled by the
  5918. ** virtual table and is not checked again by SQLite.
  5919. **
  5920. ** The idxNum and idxPtr values are recorded and passed into xFilter.
  5921. ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
  5922. **
  5923. ** The orderByConsumed means that output from xFilter will occur in
  5924. ** the correct order to satisfy the ORDER BY clause so that no separate
  5925. ** sorting step is required.
  5926. **
  5927. ** The estimatedCost value is an estimate of the cost of doing the
  5928. ** particular lookup. A full scan of a table with N entries should have
  5929. ** a cost of N. A binary search of a table of N entries should have a
  5930. ** cost of approximately log(N).
  5931. **
  5932. ** This interface is experimental and is subject to change or
  5933. ** removal in future releases of SQLite.
  5934. */
  5935. struct sqlite3_index_info {
  5936. /* Inputs */
  5937. int nConstraint; /* Number of entries in aConstraint */
  5938. struct sqlite3_index_constraint {
  5939. int iColumn; /* Column on left-hand side of constraint */
  5940. unsigned char op; /* Constraint operator */
  5941. unsigned char usable; /* True if this constraint is usable */
  5942. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5943. } *aConstraint; /* Table of WHERE clause constraints */
  5944. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5945. struct sqlite3_index_orderby {
  5946. int iColumn; /* Column number */
  5947. unsigned char desc; /* True for DESC. False for ASC. */
  5948. } *aOrderBy; /* The ORDER BY clause */
  5949. /* Outputs */
  5950. struct sqlite3_index_constraint_usage {
  5951. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5952. unsigned char omit; /* Do not code a test for this constraint */
  5953. } *aConstraintUsage;
  5954. int idxNum; /* Number used to identify the index */
  5955. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5956. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5957. int orderByConsumed; /* True if output is already ordered */
  5958. double estimatedCost; /* Estimated cost of using this index */
  5959. };
  5960. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5961. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5962. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5963. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5964. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5965. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5966. /*
  5967. ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
  5968. ** EXPERIMENTAL
  5969. **
  5970. ** This routine is used to register a new module name with a
  5971. ** [database connection]. Module names must be registered before
  5972. ** creating new virtual tables on the module, or before using
  5973. ** preexisting virtual tables of the module.
  5974. **
  5975. ** This interface is experimental and is subject to change or
  5976. ** removal in future releases of SQLite.
  5977. */
  5978. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
  5979. sqlite3 *db, /* SQLite connection to register module with */
  5980. const char *zName, /* Name of the module */
  5981. const sqlite3_module *, /* Methods for the module */
  5982. void * /* Client data for xCreate/xConnect */
  5983. );
  5984. /*
  5985. ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
  5986. ** EXPERIMENTAL
  5987. **
  5988. ** This routine is identical to the [sqlite3_create_module()] method above,
  5989. ** except that it allows a destructor function to be specified. It is
  5990. ** even more experimental than the rest of the virtual tables API.
  5991. */
  5992. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
  5993. sqlite3 *db, /* SQLite connection to register module with */
  5994. const char *zName, /* Name of the module */
  5995. const sqlite3_module *, /* Methods for the module */
  5996. void *, /* Client data for xCreate/xConnect */
  5997. void(*xDestroy)(void*) /* Module destructor function */
  5998. );
  5999. /*
  6000. ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
  6001. ** KEYWORDS: sqlite3_vtab
  6002. ** EXPERIMENTAL
  6003. **
  6004. ** Every module implementation uses a subclass of the following structure
  6005. ** to describe a particular instance of the module. Each subclass will
  6006. ** be tailored to the specific needs of the module implementation.
  6007. ** The purpose of this superclass is to define certain fields that are
  6008. ** common to all module implementations.
  6009. **
  6010. ** Virtual tables methods can set an error message by assigning a
  6011. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  6012. ** take care that any prior string is freed by a call to [sqlite3_free()]
  6013. ** prior to assigning a new string to zErrMsg. After the error message
  6014. ** is delivered up to the client application, the string will be automatically
  6015. ** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note
  6016. ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
  6017. ** since virtual tables are commonly implemented in loadable extensions which
  6018. ** do not have access to sqlite3MPrintf() or sqlite3Free().
  6019. **
  6020. ** This interface is experimental and is subject to change or
  6021. ** removal in future releases of SQLite.
  6022. */
  6023. struct sqlite3_vtab {
  6024. const sqlite3_module *pModule; /* The module for this virtual table */
  6025. int nRef; /* Used internally */
  6026. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  6027. /* Virtual table implementations will typically add additional fields */
  6028. };
  6029. /*
  6030. ** CAPI3REF: Virtual Table Cursor Object {H18020} <S20400>
  6031. ** KEYWORDS: sqlite3_vtab_cursor
  6032. ** EXPERIMENTAL
  6033. **
  6034. ** Every module implementation uses a subclass of the following structure
  6035. ** to describe cursors that point into the virtual table and are used
  6036. ** to loop through the virtual table. Cursors are created using the
  6037. ** xOpen method of the module. Each module implementation will define
  6038. ** the content of a cursor structure to suit its own needs.
  6039. **
  6040. ** This superclass exists in order to define fields of the cursor that
  6041. ** are common to all implementations.
  6042. **
  6043. ** This interface is experimental and is subject to change or
  6044. ** removal in future releases of SQLite.
  6045. */
  6046. struct sqlite3_vtab_cursor {
  6047. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  6048. /* Virtual table implementations will typically add additional fields */
  6049. };
  6050. /*
  6051. ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
  6052. ** EXPERIMENTAL
  6053. **
  6054. ** The xCreate and xConnect methods of a module use the following API
  6055. ** to declare the format (the names and datatypes of the columns) of
  6056. ** the virtual tables they implement.
  6057. **
  6058. ** This interface is experimental and is subject to change or
  6059. ** removal in future releases of SQLite.
  6060. */
  6061. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
  6062. /*
  6063. ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
  6064. ** EXPERIMENTAL
  6065. **
  6066. ** Virtual tables can provide alternative implementations of functions
  6067. ** using the xFindFunction method. But global versions of those functions
  6068. ** must exist in order to be overloaded.
  6069. **
  6070. ** This API makes sure a global version of a function with a particular
  6071. ** name and number of parameters exists. If no such function exists
  6072. ** before this API is called, a new function is created. The implementation
  6073. ** of the new function always causes an exception to be thrown. So
  6074. ** the new function is not good for anything by itself. Its only
  6075. ** purpose is to be a placeholder function that can be overloaded
  6076. ** by virtual tables.
  6077. **
  6078. ** This API should be considered part of the virtual table interface,
  6079. ** which is experimental and subject to change.
  6080. */
  6081. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  6082. /*
  6083. ** The interface to the virtual-table mechanism defined above (back up
  6084. ** to a comment remarkably similar to this one) is currently considered
  6085. ** to be experimental. The interface might change in incompatible ways.
  6086. ** If this is a problem for you, do not use the interface at this time.
  6087. **
  6088. ** When the virtual-table mechanism stabilizes, we will declare the
  6089. ** interface fixed, support it indefinitely, and remove this comment.
  6090. **
  6091. ****** EXPERIMENTAL - subject to change without notice **************
  6092. */
  6093. /*
  6094. ** CAPI3REF: A Handle To An Open BLOB {H17800} <S30230>
  6095. ** KEYWORDS: {BLOB handle} {BLOB handles}
  6096. **
  6097. ** An instance of this object represents an open BLOB on which
  6098. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  6099. ** Objects of this type are created by [sqlite3_blob_open()]
  6100. ** and destroyed by [sqlite3_blob_close()].
  6101. ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  6102. ** can be used to read or write small subsections of the BLOB.
  6103. ** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  6104. */
  6105. typedef struct sqlite3_blob sqlite3_blob;
  6106. /*
  6107. ** CAPI3REF: Open A BLOB For Incremental I/O {H17810} <S30230>
  6108. **
  6109. ** This interfaces opens a [BLOB handle | handle] to the BLOB located
  6110. ** in row iRow, column zColumn, table zTable in database zDb;
  6111. ** in other words, the same BLOB that would be selected by:
  6112. **
  6113. ** <pre>
  6114. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  6115. ** </pre> {END}
  6116. **
  6117. ** If the flags parameter is non-zero, the the BLOB is opened for read
  6118. ** and write access. If it is zero, the BLOB is opened for read access.
  6119. **
  6120. ** Note that the database name is not the filename that contains
  6121. ** the database but rather the symbolic name of the database that
  6122. ** is assigned when the database is connected using [ATTACH].
  6123. ** For the main database file, the database name is "main".
  6124. ** For TEMP tables, the database name is "temp".
  6125. **
  6126. ** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  6127. ** to *ppBlob. Otherwise an [error code] is returned and any value written
  6128. ** to *ppBlob should not be used by the caller.
  6129. ** This function sets the [database connection] error code and message
  6130. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
  6131. **
  6132. ** If the row that a BLOB handle points to is modified by an
  6133. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  6134. ** then the BLOB handle is marked as "expired".
  6135. ** This is true if any column of the row is changed, even a column
  6136. ** other than the one the BLOB handle is open on.
  6137. ** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  6138. ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
  6139. ** Changes written into a BLOB prior to the BLOB expiring are not
  6140. ** rollback by the expiration of the BLOB. Such changes will eventually
  6141. ** commit if the transaction continues to completion.
  6142. **
  6143. ** INVARIANTS:
  6144. **
  6145. ** {H17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)]
  6146. ** interface shall open an [sqlite3_blob] object P on the BLOB
  6147. ** in column C of the table T in the database B on
  6148. ** the [database connection] D.
  6149. **
  6150. ** {H17814} A successful invocation of [sqlite3_blob_open(D,...)] shall start
  6151. ** a new transaction on the [database connection] D if that
  6152. ** connection is not already in a transaction.
  6153. **
  6154. ** {H17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface shall open
  6155. ** the BLOB for read and write access if and only if the F
  6156. ** parameter is non-zero.
  6157. **
  6158. ** {H17819} The [sqlite3_blob_open()] interface shall return [SQLITE_OK] on
  6159. ** success and an appropriate [error code] on failure.
  6160. **
  6161. ** {H17821} If an error occurs during evaluation of [sqlite3_blob_open(D,...)]
  6162. ** then subsequent calls to [sqlite3_errcode(D)],
  6163. ** [sqlite3_extended_errcode()],
  6164. ** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
  6165. ** information appropriate for that error.
  6166. **
  6167. ** {H17824} If any column in the row that a [sqlite3_blob] has open is
  6168. ** changed by a separate [UPDATE] or [DELETE] statement or by
  6169. ** an [ON CONFLICT] side effect, then the [sqlite3_blob] shall
  6170. ** be marked as invalid.
  6171. */
  6172. SQLITE_API int sqlite3_blob_open(
  6173. sqlite3*,
  6174. const char *zDb,
  6175. const char *zTable,
  6176. const char *zColumn,
  6177. sqlite3_int64 iRow,
  6178. int flags,
  6179. sqlite3_blob **ppBlob
  6180. );
  6181. /*
  6182. ** CAPI3REF: Close A BLOB Handle {H17830} <S30230>
  6183. **
  6184. ** Closes an open [BLOB handle].
  6185. **
  6186. ** Closing a BLOB shall cause the current transaction to commit
  6187. ** if there are no other BLOBs, no pending prepared statements, and the
  6188. ** database connection is in [autocommit mode].
  6189. ** If any writes were made to the BLOB, they might be held in cache
  6190. ** until the close operation if they will fit. {END}
  6191. **
  6192. ** Closing the BLOB often forces the changes
  6193. ** out to disk and so if any I/O errors occur, they will likely occur
  6194. ** at the time when the BLOB is closed. {H17833} Any errors that occur during
  6195. ** closing are reported as a non-zero return value.
  6196. **
  6197. ** The BLOB is closed unconditionally. Even if this routine returns
  6198. ** an error code, the BLOB is still closed.
  6199. **
  6200. ** INVARIANTS:
  6201. **
  6202. ** {H17833} The [sqlite3_blob_close(P)] interface closes an [sqlite3_blob]
  6203. ** object P previously opened using [sqlite3_blob_open()].
  6204. **
  6205. ** {H17836} Closing an [sqlite3_blob] object using
  6206. ** [sqlite3_blob_close()] shall cause the current transaction to
  6207. ** commit if there are no other open [sqlite3_blob] objects
  6208. ** or [prepared statements] on the same [database connection] and
  6209. ** the database connection is in [autocommit mode].
  6210. **
  6211. ** {H17839} The [sqlite3_blob_close(P)] interfaces shall close the
  6212. ** [sqlite3_blob] object P unconditionally, even if
  6213. ** [sqlite3_blob_close(P)] returns something other than [SQLITE_OK].
  6214. */
  6215. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  6216. /*
  6217. ** CAPI3REF: Return The Size Of An Open BLOB {H17840} <S30230>
  6218. **
  6219. ** Returns the size in bytes of the BLOB accessible via the open
  6220. ** []BLOB handle] in its only argument.
  6221. **
  6222. ** INVARIANTS:
  6223. **
  6224. ** {H17843} The [sqlite3_blob_bytes(P)] interface returns the size
  6225. ** in bytes of the BLOB that the [sqlite3_blob] object P
  6226. ** refers to.
  6227. */
  6228. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  6229. /*
  6230. ** CAPI3REF: Read Data From A BLOB Incrementally {H17850} <S30230>
  6231. **
  6232. ** This function is used to read data from an open [BLOB handle] into a
  6233. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  6234. ** from the open BLOB, starting at offset iOffset.
  6235. **
  6236. ** If offset iOffset is less than N bytes from the end of the BLOB,
  6237. ** [SQLITE_ERROR] is returned and no data is read. If N or iOffset is
  6238. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  6239. **
  6240. ** An attempt to read from an expired [BLOB handle] fails with an
  6241. ** error code of [SQLITE_ABORT].
  6242. **
  6243. ** On success, SQLITE_OK is returned.
  6244. ** Otherwise, an [error code] or an [extended error code] is returned.
  6245. **
  6246. ** INVARIANTS:
  6247. **
  6248. ** {H17853} A successful invocation of [sqlite3_blob_read(P,Z,N,X)]
  6249. ** shall reads N bytes of data out of the BLOB referenced by
  6250. ** [BLOB handle] P beginning at offset X and store those bytes
  6251. ** into buffer Z.
  6252. **
  6253. ** {H17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the BLOB
  6254. ** is less than N+X bytes, then the function shall leave the
  6255. ** Z buffer unchanged and return [SQLITE_ERROR].
  6256. **
  6257. ** {H17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero
  6258. ** then the function shall leave the Z buffer unchanged
  6259. ** and return [SQLITE_ERROR].
  6260. **
  6261. ** {H17862} The [sqlite3_blob_read(P,Z,N,X)] interface shall return [SQLITE_OK]
  6262. ** if N bytes are successfully read into buffer Z.
  6263. **
  6264. ** {H17863} If the [BLOB handle] P is expired and X and N are within bounds
  6265. ** then [sqlite3_blob_read(P,Z,N,X)] shall leave the Z buffer
  6266. ** unchanged and return [SQLITE_ABORT].
  6267. **
  6268. ** {H17865} If the requested read could not be completed,
  6269. ** the [sqlite3_blob_read(P,Z,N,X)] interface shall return an
  6270. ** appropriate [error code] or [extended error code].
  6271. **
  6272. ** {H17868} If an error occurs during evaluation of [sqlite3_blob_read(P,...)]
  6273. ** then subsequent calls to [sqlite3_errcode(D)],
  6274. ** [sqlite3_extended_errcode()],
  6275. ** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
  6276. ** information appropriate for that error, where D is the
  6277. ** [database connection] that was used to open the [BLOB handle] P.
  6278. */
  6279. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  6280. /*
  6281. ** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} <S30230>
  6282. **
  6283. ** This function is used to write data into an open [BLOB handle] from a
  6284. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  6285. ** into the open BLOB, starting at offset iOffset.
  6286. **
  6287. ** If the [BLOB handle] passed as the first argument was not opened for
  6288. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  6289. ** this function returns [SQLITE_READONLY].
  6290. **
  6291. ** This function may only modify the contents of the BLOB; it is
  6292. ** not possible to increase the size of a BLOB using this API.
  6293. ** If offset iOffset is less than N bytes from the end of the BLOB,
  6294. ** [SQLITE_ERROR] is returned and no data is written. If N is
  6295. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  6296. **
  6297. ** An attempt to write to an expired [BLOB handle] fails with an
  6298. ** error code of [SQLITE_ABORT]. Writes to the BLOB that occurred
  6299. ** before the [BLOB handle] expired are not rolled back by the
  6300. ** expiration of the handle, though of course those changes might
  6301. ** have been overwritten by the statement that expired the BLOB handle
  6302. ** or by other independent statements.
  6303. **
  6304. ** On success, SQLITE_OK is returned.
  6305. ** Otherwise, an [error code] or an [extended error code] is returned.
  6306. **
  6307. ** INVARIANTS:
  6308. **
  6309. ** {H17873} A successful invocation of [sqlite3_blob_write(P,Z,N,X)]
  6310. ** shall write N bytes of data from buffer Z into the BLOB
  6311. ** referenced by [BLOB handle] P beginning at offset X into
  6312. ** the BLOB.
  6313. **
  6314. ** {H17874} In the absence of other overridding changes, the changes
  6315. ** written to a BLOB by [sqlite3_blob_write()] shall
  6316. ** remain in effect after the associated [BLOB handle] expires.
  6317. **
  6318. ** {H17875} If the [BLOB handle] P was opened for reading only then
  6319. ** an invocation of [sqlite3_blob_write(P,Z,N,X)] shall leave
  6320. ** the referenced BLOB unchanged and return [SQLITE_READONLY].
  6321. **
  6322. ** {H17876} If the size of the BLOB referenced by [BLOB handle] P is
  6323. ** less than N+X bytes then [sqlite3_blob_write(P,Z,N,X)] shall
  6324. ** leave the BLOB unchanged and return [SQLITE_ERROR].
  6325. **
  6326. ** {H17877} If the [BLOB handle] P is expired and X and N are within bounds
  6327. ** then [sqlite3_blob_read(P,Z,N,X)] shall leave the BLOB
  6328. ** unchanged and return [SQLITE_ABORT].
  6329. **
  6330. ** {H17879} If X or N are less than zero then [sqlite3_blob_write(P,Z,N,X)]
  6331. ** shall leave the BLOB referenced by [BLOB handle] P unchanged
  6332. ** and return [SQLITE_ERROR].
  6333. **
  6334. ** {H17882} The [sqlite3_blob_write(P,Z,N,X)] interface shall return
  6335. ** [SQLITE_OK] if N bytes where successfully written into the BLOB.
  6336. **
  6337. ** {H17885} If the requested write could not be completed,
  6338. ** the [sqlite3_blob_write(P,Z,N,X)] interface shall return an
  6339. ** appropriate [error code] or [extended error code].
  6340. **
  6341. ** {H17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)]
  6342. ** then subsequent calls to [sqlite3_errcode(D)],
  6343. ** [sqlite3_extended_errcode()],
  6344. ** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
  6345. ** information appropriate for that error.
  6346. */
  6347. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  6348. /*
  6349. ** CAPI3REF: Virtual File System Objects {H11200} <S20100>
  6350. **
  6351. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  6352. ** that SQLite uses to interact
  6353. ** with the underlying operating system. Most SQLite builds come with a
  6354. ** single default VFS that is appropriate for the host computer.
  6355. ** New VFSes can be registered and existing VFSes can be unregistered.
  6356. ** The following interfaces are provided.
  6357. **
  6358. ** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  6359. ** Names are case sensitive.
  6360. ** Names are zero-terminated UTF-8 strings.
  6361. ** If there is no match, a NULL pointer is returned.
  6362. ** If zVfsName is NULL then the default VFS is returned.
  6363. **
  6364. ** New VFSes are registered with sqlite3_vfs_register().
  6365. ** Each new VFS becomes the default VFS if the makeDflt flag is set.
  6366. ** The same VFS can be registered multiple times without injury.
  6367. ** To make an existing VFS into the default VFS, register it again
  6368. ** with the makeDflt flag set. If two different VFSes with the
  6369. ** same name are registered, the behavior is undefined. If a
  6370. ** VFS is registered with a name that is NULL or an empty string,
  6371. ** then the behavior is undefined.
  6372. **
  6373. ** Unregister a VFS with the sqlite3_vfs_unregister() interface.
  6374. ** If the default VFS is unregistered, another VFS is chosen as
  6375. ** the default. The choice for the new VFS is arbitrary.
  6376. **
  6377. ** INVARIANTS:
  6378. **
  6379. ** {H11203} The [sqlite3_vfs_find(N)] interface returns a pointer to the
  6380. ** registered [sqlite3_vfs] object whose name exactly matches
  6381. ** the zero-terminated UTF-8 string N, or it returns NULL if
  6382. ** there is no match.
  6383. **
  6384. ** {H11206} If the N parameter to [sqlite3_vfs_find(N)] is NULL then
  6385. ** the function returns a pointer to the default [sqlite3_vfs]
  6386. ** object if there is one, or NULL if there is no default
  6387. ** [sqlite3_vfs] object.
  6388. **
  6389. ** {H11209} The [sqlite3_vfs_register(P,F)] interface registers the
  6390. ** well-formed [sqlite3_vfs] object P using the name given
  6391. ** by the zName field of the object.
  6392. **
  6393. ** {H11212} Using the [sqlite3_vfs_register(P,F)] interface to register
  6394. ** the same [sqlite3_vfs] object multiple times is a harmless no-op.
  6395. **
  6396. ** {H11215} The [sqlite3_vfs_register(P,F)] interface makes the [sqlite3_vfs]
  6397. ** object P the default [sqlite3_vfs] object if F is non-zero.
  6398. **
  6399. ** {H11218} The [sqlite3_vfs_unregister(P)] interface unregisters the
  6400. ** [sqlite3_vfs] object P so that it is no longer returned by
  6401. ** subsequent calls to [sqlite3_vfs_find()].
  6402. */
  6403. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  6404. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  6405. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  6406. /*
  6407. ** CAPI3REF: Mutexes {H17000} <S20000>
  6408. **
  6409. ** The SQLite core uses these routines for thread
  6410. ** synchronization. Though they are intended for internal
  6411. ** use by SQLite, code that links against SQLite is
  6412. ** permitted to use any of these routines.
  6413. **
  6414. ** The SQLite source code contains multiple implementations
  6415. ** of these mutex routines. An appropriate implementation
  6416. ** is selected automatically at compile-time. The following
  6417. ** implementations are available in the SQLite core:
  6418. **
  6419. ** <ul>
  6420. ** <li> SQLITE_MUTEX_OS2
  6421. ** <li> SQLITE_MUTEX_PTHREAD
  6422. ** <li> SQLITE_MUTEX_W32
  6423. ** <li> SQLITE_MUTEX_NOOP
  6424. ** </ul>
  6425. **
  6426. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  6427. ** that does no real locking and is appropriate for use in
  6428. ** a single-threaded application. The SQLITE_MUTEX_OS2,
  6429. ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
  6430. ** are appropriate for use on OS/2, Unix, and Windows.
  6431. **
  6432. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  6433. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  6434. ** implementation is included with the library. In this case the
  6435. ** application must supply a custom mutex implementation using the
  6436. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  6437. ** before calling sqlite3_initialize() or any other public sqlite3_
  6438. ** function that calls sqlite3_initialize().
  6439. **
  6440. ** {H17011} The sqlite3_mutex_alloc() routine allocates a new
  6441. ** mutex and returns a pointer to it. {H17012} If it returns NULL
  6442. ** that means that a mutex could not be allocated. {H17013} SQLite
  6443. ** will unwind its stack and return an error. {H17014} The argument
  6444. ** to sqlite3_mutex_alloc() is one of these integer constants:
  6445. **
  6446. ** <ul>
  6447. ** <li> SQLITE_MUTEX_FAST
  6448. ** <li> SQLITE_MUTEX_RECURSIVE
  6449. ** <li> SQLITE_MUTEX_STATIC_MASTER
  6450. ** <li> SQLITE_MUTEX_STATIC_MEM
  6451. ** <li> SQLITE_MUTEX_STATIC_MEM2
  6452. ** <li> SQLITE_MUTEX_STATIC_PRNG
  6453. ** <li> SQLITE_MUTEX_STATIC_LRU
  6454. ** <li> SQLITE_MUTEX_STATIC_LRU2
  6455. ** </ul>
  6456. **
  6457. ** {H17015} The first two constants cause sqlite3_mutex_alloc() to create
  6458. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  6459. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
  6460. ** The mutex implementation does not need to make a distinction
  6461. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  6462. ** not want to. {H17016} But SQLite will only request a recursive mutex in
  6463. ** cases where it really needs one. {END} If a faster non-recursive mutex
  6464. ** implementation is available on the host platform, the mutex subsystem
  6465. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  6466. **
  6467. ** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return
  6468. ** a pointer to a static preexisting mutex. {END} Four static mutexes are
  6469. ** used by the current version of SQLite. Future versions of SQLite
  6470. ** may add additional static mutexes. Static mutexes are for internal
  6471. ** use by SQLite only. Applications that use SQLite mutexes should
  6472. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  6473. ** SQLITE_MUTEX_RECURSIVE.
  6474. **
  6475. ** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  6476. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  6477. ** returns a different mutex on every call. {H17034} But for the static
  6478. ** mutex types, the same mutex is returned on every call that has
  6479. ** the same type number.
  6480. **
  6481. ** {H17019} The sqlite3_mutex_free() routine deallocates a previously
  6482. ** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every
  6483. ** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in
  6484. ** use when they are deallocated. {A17022} Attempting to deallocate a static
  6485. ** mutex results in undefined behavior. {H17023} SQLite never deallocates
  6486. ** a static mutex. {END}
  6487. **
  6488. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  6489. ** to enter a mutex. {H17024} If another thread is already within the mutex,
  6490. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  6491. ** SQLITE_BUSY. {H17025} The sqlite3_mutex_try() interface returns [SQLITE_OK]
  6492. ** upon successful entry. {H17026} Mutexes created using
  6493. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  6494. ** {H17027} In such cases the,
  6495. ** mutex must be exited an equal number of times before another thread
  6496. ** can enter. {A17028} If the same thread tries to enter any other
  6497. ** kind of mutex more than once, the behavior is undefined.
  6498. ** {H17029} SQLite will never exhibit
  6499. ** such behavior in its own use of mutexes.
  6500. **
  6501. ** Some systems (for example, Windows 95) do not support the operation
  6502. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  6503. ** will always return SQLITE_BUSY. {H17030} The SQLite core only ever uses
  6504. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.
  6505. **
  6506. ** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was
  6507. ** previously entered by the same thread. {A17032} The behavior
  6508. ** is undefined if the mutex is not currently entered by the
  6509. ** calling thread or is not currently allocated. {H17033} SQLite will
  6510. ** never do either. {END}
  6511. **
  6512. ** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  6513. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  6514. ** behave as no-ops.
  6515. **
  6516. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  6517. */
  6518. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  6519. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  6520. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  6521. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  6522. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  6523. /*
  6524. ** CAPI3REF: Mutex Methods Object {H17120} <S20130>
  6525. ** EXPERIMENTAL
  6526. **
  6527. ** An instance of this structure defines the low-level routines
  6528. ** used to allocate and use mutexes.
  6529. **
  6530. ** Usually, the default mutex implementations provided by SQLite are
  6531. ** sufficient, however the user has the option of substituting a custom
  6532. ** implementation for specialized deployments or systems for which SQLite
  6533. ** does not provide a suitable implementation. In this case, the user
  6534. ** creates and populates an instance of this structure to pass
  6535. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  6536. ** Additionally, an instance of this structure can be used as an
  6537. ** output variable when querying the system for the current mutex
  6538. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  6539. **
  6540. ** The xMutexInit method defined by this structure is invoked as
  6541. ** part of system initialization by the sqlite3_initialize() function.
  6542. ** {H17001} The xMutexInit routine shall be called by SQLite once for each
  6543. ** effective call to [sqlite3_initialize()].
  6544. **
  6545. ** The xMutexEnd method defined by this structure is invoked as
  6546. ** part of system shutdown by the sqlite3_shutdown() function. The
  6547. ** implementation of this method is expected to release all outstanding
  6548. ** resources obtained by the mutex methods implementation, especially
  6549. ** those obtained by the xMutexInit method. {H17003} The xMutexEnd()
  6550. ** interface shall be invoked once for each call to [sqlite3_shutdown()].
  6551. **
  6552. ** The remaining seven methods defined by this structure (xMutexAlloc,
  6553. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  6554. ** xMutexNotheld) implement the following interfaces (respectively):
  6555. **
  6556. ** <ul>
  6557. ** <li> [sqlite3_mutex_alloc()] </li>
  6558. ** <li> [sqlite3_mutex_free()] </li>
  6559. ** <li> [sqlite3_mutex_enter()] </li>
  6560. ** <li> [sqlite3_mutex_try()] </li>
  6561. ** <li> [sqlite3_mutex_leave()] </li>
  6562. ** <li> [sqlite3_mutex_held()] </li>
  6563. ** <li> [sqlite3_mutex_notheld()] </li>
  6564. ** </ul>
  6565. **
  6566. ** The only difference is that the public sqlite3_XXX functions enumerated
  6567. ** above silently ignore any invocations that pass a NULL pointer instead
  6568. ** of a valid mutex handle. The implementations of the methods defined
  6569. ** by this structure are not required to handle this case, the results
  6570. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6571. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6572. ** it is passed a NULL pointer).
  6573. */
  6574. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6575. struct sqlite3_mutex_methods {
  6576. int (*xMutexInit)(void);
  6577. int (*xMutexEnd)(void);
  6578. sqlite3_mutex *(*xMutexAlloc)(int);
  6579. void (*xMutexFree)(sqlite3_mutex *);
  6580. void (*xMutexEnter)(sqlite3_mutex *);
  6581. int (*xMutexTry)(sqlite3_mutex *);
  6582. void (*xMutexLeave)(sqlite3_mutex *);
  6583. int (*xMutexHeld)(sqlite3_mutex *);
  6584. int (*xMutexNotheld)(sqlite3_mutex *);
  6585. };
  6586. /*
  6587. ** CAPI3REF: Mutex Verification Routines {H17080} <S20130> <S30800>
  6588. **
  6589. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6590. ** are intended for use inside assert() statements. {H17081} The SQLite core
  6591. ** never uses these routines except inside an assert() and applications
  6592. ** are advised to follow the lead of the core. {H17082} The core only
  6593. ** provides implementations for these routines when it is compiled
  6594. ** with the SQLITE_DEBUG flag. {A17087} External mutex implementations
  6595. ** are only required to provide these routines if SQLITE_DEBUG is
  6596. ** defined and if NDEBUG is not defined.
  6597. **
  6598. ** {H17083} These routines should return true if the mutex in their argument
  6599. ** is held or not held, respectively, by the calling thread.
  6600. **
  6601. ** {X17084} The implementation is not required to provided versions of these
  6602. ** routines that actually work. If the implementation does not provide working
  6603. ** versions of these routines, it should at least provide stubs that always
  6604. ** return true so that one does not get spurious assertion failures.
  6605. **
  6606. ** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
  6607. ** the routine should return 1. {END} This seems counter-intuitive since
  6608. ** clearly the mutex cannot be held if it does not exist. But the
  6609. ** the reason the mutex does not exist is because the build is not
  6610. ** using mutexes. And we do not want the assert() containing the
  6611. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6612. ** the appropriate thing to do. {H17086} The sqlite3_mutex_notheld()
  6613. ** interface should also return 1 when given a NULL pointer.
  6614. */
  6615. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  6616. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  6617. /*
  6618. ** CAPI3REF: Mutex Types {H17001} <H17000>
  6619. **
  6620. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6621. ** which is one of these integer constants.
  6622. **
  6623. ** The set of static mutexes may change from one SQLite release to the
  6624. ** next. Applications that override the built-in mutex logic must be
  6625. ** prepared to accommodate additional static mutexes.
  6626. */
  6627. #define SQLITE_MUTEX_FAST 0
  6628. #define SQLITE_MUTEX_RECURSIVE 1
  6629. #define SQLITE_MUTEX_STATIC_MASTER 2
  6630. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6631. #define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */
  6632. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6633. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6634. #define SQLITE_MUTEX_STATIC_LRU2 7 /* lru page list */
  6635. /*
  6636. ** CAPI3REF: Retrieve the mutex for a database connection {H17002} <H17000>
  6637. **
  6638. ** This interface returns a pointer the [sqlite3_mutex] object that
  6639. ** serializes access to the [database connection] given in the argument
  6640. ** when the [threading mode] is Serialized.
  6641. ** If the [threading mode] is Single-thread or Multi-thread then this
  6642. ** routine returns a NULL pointer.
  6643. */
  6644. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  6645. /*
  6646. ** CAPI3REF: Low-Level Control Of Database Files {H11300} <S30800>
  6647. **
  6648. ** {H11301} The [sqlite3_file_control()] interface makes a direct call to the
  6649. ** xFileControl method for the [sqlite3_io_methods] object associated
  6650. ** with a particular database identified by the second argument. {H11302} The
  6651. ** name of the database is the name assigned to the database by the
  6652. ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
  6653. ** database. {H11303} To control the main database file, use the name "main"
  6654. ** or a NULL pointer. {H11304} The third and fourth parameters to this routine
  6655. ** are passed directly through to the second and third parameters of
  6656. ** the xFileControl method. {H11305} The return value of the xFileControl
  6657. ** method becomes the return value of this routine.
  6658. **
  6659. ** {H11306} If the second parameter (zDbName) does not match the name of any
  6660. ** open database file, then SQLITE_ERROR is returned. {H11307} This error
  6661. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6662. ** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might
  6663. ** also return SQLITE_ERROR. {A11309} There is no way to distinguish between
  6664. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6665. ** xFileControl method. {END}
  6666. **
  6667. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6668. */
  6669. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6670. /*
  6671. ** CAPI3REF: Testing Interface {H11400} <S30800>
  6672. **
  6673. ** The sqlite3_test_control() interface is used to read out internal
  6674. ** state of SQLite and to inject faults into SQLite for testing
  6675. ** purposes. The first parameter is an operation code that determines
  6676. ** the number, meaning, and operation of all subsequent parameters.
  6677. **
  6678. ** This interface is not for use by applications. It exists solely
  6679. ** for verifying the correct operation of the SQLite library. Depending
  6680. ** on how the SQLite library is compiled, this interface might not exist.
  6681. **
  6682. ** The details of the operation codes, their meanings, the parameters
  6683. ** they take, and what they do are all subject to change without notice.
  6684. ** Unlike most of the SQLite API, this function is not guaranteed to
  6685. ** operate consistently from one release to the next.
  6686. */
  6687. SQLITE_API int sqlite3_test_control(int op, ...);
  6688. /*
  6689. ** CAPI3REF: Testing Interface Operation Codes {H11410} <H11400>
  6690. **
  6691. ** These constants are the valid operation code parameters used
  6692. ** as the first argument to [sqlite3_test_control()].
  6693. **
  6694. ** These parameters and their meanings are subject to change
  6695. ** without notice. These values are for testing purposes only.
  6696. ** Applications should not use any of these parameters or the
  6697. ** [sqlite3_test_control()] interface.
  6698. */
  6699. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6700. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6701. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6702. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6703. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6704. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6705. /*
  6706. ** CAPI3REF: SQLite Runtime Status {H17200} <S60200>
  6707. ** EXPERIMENTAL
  6708. **
  6709. ** This interface is used to retrieve runtime status information
  6710. ** about the preformance of SQLite, and optionally to reset various
  6711. ** highwater marks. The first argument is an integer code for
  6712. ** the specific parameter to measure. Recognized integer codes
  6713. ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].
  6714. ** The current value of the parameter is returned into *pCurrent.
  6715. ** The highest recorded value is returned in *pHighwater. If the
  6716. ** resetFlag is true, then the highest record value is reset after
  6717. ** *pHighwater is written. Some parameters do not record the highest
  6718. ** value. For those parameters
  6719. ** nothing is written into *pHighwater and the resetFlag is ignored.
  6720. ** Other parameters record only the highwater mark and not the current
  6721. ** value. For these latter parameters nothing is written into *pCurrent.
  6722. **
  6723. ** This routine returns SQLITE_OK on success and a non-zero
  6724. ** [error code] on failure.
  6725. **
  6726. ** This routine is threadsafe but is not atomic. This routine can
  6727. ** called while other threads are running the same or different SQLite
  6728. ** interfaces. However the values returned in *pCurrent and
  6729. ** *pHighwater reflect the status of SQLite at different points in time
  6730. ** and it is possible that another thread might change the parameter
  6731. ** in between the times when *pCurrent and *pHighwater are written.
  6732. **
  6733. ** See also: [sqlite3_db_status()]
  6734. */
  6735. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6736. /*
  6737. ** CAPI3REF: Status Parameters {H17250} <H17200>
  6738. ** EXPERIMENTAL
  6739. **
  6740. ** These integer constants designate various run-time status parameters
  6741. ** that can be returned by [sqlite3_status()].
  6742. **
  6743. ** <dl>
  6744. ** <dt>SQLITE_STATUS_MEMORY_USED</dt>
  6745. ** <dd>This parameter is the current amount of memory checked out
  6746. ** using [sqlite3_malloc()], either directly or indirectly. The
  6747. ** figure includes calls made to [sqlite3_malloc()] by the application
  6748. ** and internal memory usage by the SQLite library. Scratch memory
  6749. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6750. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6751. ** this parameter. The amount returned is the sum of the allocation
  6752. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>
  6753. **
  6754. ** <dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6755. ** <dd>This parameter records the largest memory allocation request
  6756. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6757. ** internal equivalents). Only the value returned in the
  6758. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6759. ** The value written into the *pCurrent parameter is undefined.</dd>
  6760. **
  6761. ** <dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6762. ** <dd>This parameter returns the number of pages used out of the
  6763. ** [pagecache memory allocator] that was configured using
  6764. ** [SQLITE_CONFIG_PAGECACHE]. The
  6765. ** value returned is in pages, not in bytes.</dd>
  6766. **
  6767. ** <dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6768. ** <dd>This parameter returns the number of bytes of page cache
  6769. ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
  6770. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6771. ** returned value includes allocations that overflowed because they
  6772. ** where too large (they were larger than the "sz" parameter to
  6773. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6774. ** no space was left in the page cache.</dd>
  6775. **
  6776. ** <dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6777. ** <dd>This parameter records the largest memory allocation request
  6778. ** handed to [pagecache memory allocator]. Only the value returned in the
  6779. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6780. ** The value written into the *pCurrent parameter is undefined.</dd>
  6781. **
  6782. ** <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6783. ** <dd>This parameter returns the number of allocations used out of the
  6784. ** [scratch memory allocator] configured using
  6785. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6786. ** in bytes. Since a single thread may only have one scratch allocation
  6787. ** outstanding at time, this parameter also reports the number of threads
  6788. ** using scratch memory at the same time.</dd>
  6789. **
  6790. ** <dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6791. ** <dd>This parameter returns the number of bytes of scratch memory
  6792. ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
  6793. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6794. ** returned include overflows because the requested allocation was too
  6795. ** larger (that is, because the requested allocation was larger than the
  6796. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6797. ** slots were available.
  6798. ** </dd>
  6799. **
  6800. ** <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6801. ** <dd>This parameter records the largest memory allocation request
  6802. ** handed to [scratch memory allocator]. Only the value returned in the
  6803. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6804. ** The value written into the *pCurrent parameter is undefined.</dd>
  6805. **
  6806. ** <dt>SQLITE_STATUS_PARSER_STACK</dt>
  6807. ** <dd>This parameter records the deepest parser stack. It is only
  6808. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>
  6809. ** </dl>
  6810. **
  6811. ** New status parameters may be added from time to time.
  6812. */
  6813. #define SQLITE_STATUS_MEMORY_USED 0
  6814. #define SQLITE_STATUS_PAGECACHE_USED 1
  6815. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6816. #define SQLITE_STATUS_SCRATCH_USED 3
  6817. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6818. #define SQLITE_STATUS_MALLOC_SIZE 5
  6819. #define SQLITE_STATUS_PARSER_STACK 6
  6820. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6821. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6822. /*
  6823. ** CAPI3REF: Database Connection Status {H17500} <S60200>
  6824. ** EXPERIMENTAL
  6825. **
  6826. ** This interface is used to retrieve runtime status information
  6827. ** about a single [database connection]. The first argument is the
  6828. ** database connection object to be interrogated. The second argument
  6829. ** is the parameter to interrogate. Currently, the only allowed value
  6830. ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
  6831. ** Additional options will likely appear in future releases of SQLite.
  6832. **
  6833. ** The current value of the requested parameter is written into *pCur
  6834. ** and the highest instantaneous value is written into *pHiwtr. If
  6835. ** the resetFlg is true, then the highest instantaneous value is
  6836. ** reset back down to the current value.
  6837. **
  6838. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6839. */
  6840. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6841. /*
  6842. ** CAPI3REF: Status Parameters for database connections {H17520} <H17500>
  6843. ** EXPERIMENTAL
  6844. **
  6845. ** Status verbs for [sqlite3_db_status()].
  6846. **
  6847. ** <dl>
  6848. ** <dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6849. ** <dd>This parameter returns the number of lookaside memory slots currently
  6850. ** checked out.</dd>
  6851. ** </dl>
  6852. */
  6853. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6854. /*
  6855. ** CAPI3REF: Prepared Statement Status {H17550} <S60200>
  6856. ** EXPERIMENTAL
  6857. **
  6858. ** Each prepared statement maintains various
  6859. ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
  6860. ** of times it has performed specific operations. These counters can
  6861. ** be used to monitor the performance characteristics of the prepared
  6862. ** statements. For example, if the number of table steps greatly exceeds
  6863. ** the number of table searches or result rows, that would tend to indicate
  6864. ** that the prepared statement is using a full table scan rather than
  6865. ** an index.
  6866. **
  6867. ** This interface is used to retrieve and reset counter values from
  6868. ** a [prepared statement]. The first argument is the prepared statement
  6869. ** object to be interrogated. The second argument
  6870. ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
  6871. ** to be interrogated.
  6872. ** The current value of the requested counter is returned.
  6873. ** If the resetFlg is true, then the counter is reset to zero after this
  6874. ** interface call returns.
  6875. **
  6876. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6877. */
  6878. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6879. /*
  6880. ** CAPI3REF: Status Parameters for prepared statements {H17570} <H17550>
  6881. ** EXPERIMENTAL
  6882. **
  6883. ** These preprocessor macros define integer codes that name counter
  6884. ** values associated with the [sqlite3_stmt_status()] interface.
  6885. ** The meanings of the various counters are as follows:
  6886. **
  6887. ** <dl>
  6888. ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6889. ** <dd>This is the number of times that SQLite has stepped forward in
  6890. ** a table as part of a full table scan. Large numbers for this counter
  6891. ** may indicate opportunities for performance improvement through
  6892. ** careful use of indices.</dd>
  6893. **
  6894. ** <dt>SQLITE_STMTSTATUS_SORT</dt>
  6895. ** <dd>This is the number of sort operations that have occurred.
  6896. ** A non-zero value in this counter may indicate an opportunity to
  6897. ** improvement performance through careful use of indices.</dd>
  6898. **
  6899. ** </dl>
  6900. */
  6901. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6902. #define SQLITE_STMTSTATUS_SORT 2
  6903. /*
  6904. ** CAPI3REF: Custom Page Cache Object
  6905. ** EXPERIMENTAL
  6906. **
  6907. ** The sqlite3_pcache type is opaque. It is implemented by
  6908. ** the pluggable module. The SQLite core has no knowledge of
  6909. ** its size or internal structure and never deals with the
  6910. ** sqlite3_pcache object except by holding and passing pointers
  6911. ** to the object.
  6912. **
  6913. ** See [sqlite3_pcache_methods] for additional information.
  6914. */
  6915. typedef struct sqlite3_pcache sqlite3_pcache;
  6916. /*
  6917. ** CAPI3REF: Application Defined Page Cache.
  6918. ** EXPERIMENTAL
  6919. **
  6920. ** The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
  6921. ** register an alternative page cache implementation by passing in an
  6922. ** instance of the sqlite3_pcache_methods structure. The majority of the
  6923. ** heap memory used by sqlite is used by the page cache to cache data read
  6924. ** from, or ready to be written to, the database file. By implementing a
  6925. ** custom page cache using this API, an application can control more
  6926. ** precisely the amount of memory consumed by sqlite, the way in which
  6927. ** said memory is allocated and released, and the policies used to
  6928. ** determine exactly which parts of a database file are cached and for
  6929. ** how long.
  6930. **
  6931. ** The contents of the structure are copied to an internal buffer by sqlite
  6932. ** within the call to [sqlite3_config].
  6933. **
  6934. ** The xInit() method is called once for each call to [sqlite3_initialize()]
  6935. ** (usually only once during the lifetime of the process). It is passed
  6936. ** a copy of the sqlite3_pcache_methods.pArg value. It can be used to set
  6937. ** up global structures and mutexes required by the custom page cache
  6938. ** implementation. The xShutdown() method is called from within
  6939. ** [sqlite3_shutdown()], if the application invokes this API. It can be used
  6940. ** to clean up any outstanding resources before process shutdown, if required.
  6941. **
  6942. ** The xCreate() method is used to construct a new cache instance. The
  6943. ** first parameter, szPage, is the size in bytes of the pages that must
  6944. ** be allocated by the cache. szPage will not be a power of two. The
  6945. ** second argument, bPurgeable, is true if the cache being created will
  6946. ** be used to cache database pages read from a file stored on disk, or
  6947. ** false if it is used for an in-memory database. The cache implementation
  6948. ** does not have to do anything special based on the value of bPurgeable,
  6949. ** it is purely advisory.
  6950. **
  6951. ** The xCachesize() method may be called at any time by SQLite to set the
  6952. ** suggested maximum cache-size (number of pages stored by) the cache
  6953. ** instance passed as the first argument. This is the value configured using
  6954. ** the SQLite "[PRAGMA cache_size]" command. As with the bPurgeable parameter,
  6955. ** the implementation is not required to do anything special with this
  6956. ** value, it is advisory only.
  6957. **
  6958. ** The xPagecount() method should return the number of pages currently
  6959. ** stored in the cache supplied as an argument.
  6960. **
  6961. ** The xFetch() method is used to fetch a page and return a pointer to it.
  6962. ** A 'page', in this context, is a buffer of szPage bytes aligned at an
  6963. ** 8-byte boundary. The page to be fetched is determined by the key. The
  6964. ** mimimum key value is 1. After it has been retrieved using xFetch, the page
  6965. ** is considered to be pinned.
  6966. **
  6967. ** If the requested page is already in the page cache, then a pointer to
  6968. ** the cached buffer should be returned with its contents intact. If the
  6969. ** page is not already in the cache, then the expected behaviour of the
  6970. ** cache is determined by the value of the createFlag parameter passed
  6971. ** to xFetch, according to the following table:
  6972. **
  6973. ** <table border=1 width=85% align=center>
  6974. ** <tr><th>createFlag<th>Expected Behaviour
  6975. ** <tr><td>0<td>NULL should be returned. No new cache entry is created.
  6976. ** <tr><td>1<td>If createFlag is set to 1, this indicates that
  6977. ** SQLite is holding pinned pages that can be unpinned
  6978. ** by writing their contents to the database file (a
  6979. ** relatively expensive operation). In this situation the
  6980. ** cache implementation has two choices: it can return NULL,
  6981. ** in which case SQLite will attempt to unpin one or more
  6982. ** pages before re-requesting the same page, or it can
  6983. ** allocate a new page and return a pointer to it. If a new
  6984. ** page is allocated, then it must be completely zeroed before
  6985. ** it is returned.
  6986. ** <tr><td>2<td>If createFlag is set to 2, then SQLite is not holding any
  6987. ** pinned pages associated with the specific cache passed
  6988. ** as the first argument to xFetch() that can be unpinned. The
  6989. ** cache implementation should attempt to allocate a new
  6990. ** cache entry and return a pointer to it. Again, the new
  6991. ** page should be zeroed before it is returned. If the xFetch()
  6992. ** method returns NULL when createFlag==2, SQLite assumes that
  6993. ** a memory allocation failed and returns SQLITE_NOMEM to the
  6994. ** user.
  6995. ** </table>
  6996. **
  6997. ** xUnpin() is called by SQLite with a pointer to a currently pinned page
  6998. ** as its second argument. If the third parameter, discard, is non-zero,
  6999. ** then the page should be evicted from the cache. In this case SQLite
  7000. ** assumes that the next time the page is retrieved from the cache using
  7001. ** the xFetch() method, it will be zeroed. If the discard parameter is
  7002. ** zero, then the page is considered to be unpinned. The cache implementation
  7003. ** may choose to reclaim (free or recycle) unpinned pages at any time.
  7004. ** SQLite assumes that next time the page is retrieved from the cache
  7005. ** it will either be zeroed, or contain the same data that it did when it
  7006. ** was unpinned.
  7007. **
  7008. ** The cache is not required to perform any reference counting. A single
  7009. ** call to xUnpin() unpins the page regardless of the number of prior calls
  7010. ** to xFetch().
  7011. **
  7012. ** The xRekey() method is used to change the key value associated with the
  7013. ** page passed as the second argument from oldKey to newKey. If the cache
  7014. ** previously contains an entry associated with newKey, it should be
  7015. ** discarded. Any prior cache entry associated with newKey is guaranteed not
  7016. ** to be pinned.
  7017. **
  7018. ** When SQLite calls the xTruncate() method, the cache must discard all
  7019. ** existing cache entries with page numbers (keys) greater than or equal
  7020. ** to the value of the iLimit parameter passed to xTruncate(). If any
  7021. ** of these pages are pinned, they are implicitly unpinned, meaning that
  7022. ** they can be safely discarded.
  7023. **
  7024. ** The xDestroy() method is used to delete a cache allocated by xCreate().
  7025. ** All resources associated with the specified cache should be freed. After
  7026. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  7027. ** handle invalid, and will not use it with any other sqlite3_pcache_methods
  7028. ** functions.
  7029. */
  7030. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  7031. struct sqlite3_pcache_methods {
  7032. void *pArg;
  7033. int (*xInit)(void*);
  7034. void (*xShutdown)(void*);
  7035. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  7036. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7037. int (*xPagecount)(sqlite3_pcache*);
  7038. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7039. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  7040. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  7041. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7042. void (*xDestroy)(sqlite3_pcache*);
  7043. };
  7044. /*
  7045. ** Undo the hack that converts floating point types to integer for
  7046. ** builds on processors without floating point support.
  7047. */
  7048. #ifdef SQLITE_OMIT_FLOATING_POINT
  7049. # undef double
  7050. #endif
  7051. #if 0
  7052. } /* End of the 'extern "C"' block */
  7053. #endif
  7054. #endif
  7055. /************** End of sqlite3.h *********************************************/
  7056. /************** Continuing where we left off in sqliteInt.h ******************/
  7057. /************** Include hash.h in the middle of sqliteInt.h ******************/
  7058. /************** Begin file hash.h ********************************************/
  7059. /*
  7060. ** 2001 September 22
  7061. **
  7062. ** The author disclaims copyright to this source code. In place of
  7063. ** a legal notice, here is a blessing:
  7064. **
  7065. ** May you do good and not evil.
  7066. ** May you find forgiveness for yourself and forgive others.
  7067. ** May you share freely, never taking more than you give.
  7068. **
  7069. *************************************************************************
  7070. ** This is the header file for the generic hash-table implemenation
  7071. ** used in SQLite.
  7072. **
  7073. ** $Id: hash.h,v 1.12 2008/10/10 17:41:29 drh Exp $
  7074. */
  7075. #ifndef _SQLITE_HASH_H_
  7076. #define _SQLITE_HASH_H_
  7077. /* Forward declarations of structures. */
  7078. typedef struct Hash Hash;
  7079. typedef struct HashElem HashElem;
  7080. /* A complete hash table is an instance of the following structure.
  7081. ** The internals of this structure are intended to be opaque -- client
  7082. ** code should not attempt to access or modify the fields of this structure
  7083. ** directly. Change this structure only by using the routines below.
  7084. ** However, many of the "procedures" and "functions" for modifying and
  7085. ** accessing this structure are really macros, so we can't really make
  7086. ** this structure opaque.
  7087. */
  7088. struct Hash {
  7089. unsigned int copyKey: 1; /* True if copy of key made on insert */
  7090. unsigned int htsize : 31; /* Number of buckets in the hash table */
  7091. unsigned int count; /* Number of entries in this table */
  7092. HashElem *first; /* The first element of the array */
  7093. struct _ht { /* the hash table */
  7094. int count; /* Number of entries with this hash */
  7095. HashElem *chain; /* Pointer to first entry with this hash */
  7096. } *ht;
  7097. };
  7098. /* Each element in the hash table is an instance of the following
  7099. ** structure. All elements are stored on a single doubly-linked list.
  7100. **
  7101. ** Again, this structure is intended to be opaque, but it can't really
  7102. ** be opaque because it is used by macros.
  7103. */
  7104. struct HashElem {
  7105. HashElem *next, *prev; /* Next and previous elements in the table */
  7106. void *data; /* Data associated with this element */
  7107. void *pKey; int nKey; /* Key associated with this element */
  7108. };
  7109. /*
  7110. ** Access routines. To delete, insert a NULL pointer.
  7111. */
  7112. SQLITE_PRIVATE void sqlite3HashInit(Hash*, int copyKey);
  7113. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
  7114. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
  7115. SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
  7116. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  7117. /*
  7118. ** Macros for looping over all elements of a hash table. The idiom is
  7119. ** like this:
  7120. **
  7121. ** Hash h;
  7122. ** HashElem *p;
  7123. ** ...
  7124. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  7125. ** SomeStructure *pData = sqliteHashData(p);
  7126. ** // do something with pData
  7127. ** }
  7128. */
  7129. #define sqliteHashFirst(H) ((H)->first)
  7130. #define sqliteHashNext(E) ((E)->next)
  7131. #define sqliteHashData(E) ((E)->data)
  7132. #define sqliteHashKey(E) ((E)->pKey)
  7133. #define sqliteHashKeysize(E) ((E)->nKey)
  7134. /*
  7135. ** Number of entries in a hash table
  7136. */
  7137. #define sqliteHashCount(H) ((H)->count)
  7138. #endif /* _SQLITE_HASH_H_ */
  7139. /************** End of hash.h ************************************************/
  7140. /************** Continuing where we left off in sqliteInt.h ******************/
  7141. /************** Include parse.h in the middle of sqliteInt.h *****************/
  7142. /************** Begin file parse.h *******************************************/
  7143. #define TK_SEMI 1
  7144. #define TK_EXPLAIN 2
  7145. #define TK_QUERY 3
  7146. #define TK_PLAN 4
  7147. #define TK_BEGIN 5
  7148. #define TK_TRANSACTION 6
  7149. #define TK_DEFERRED 7
  7150. #define TK_IMMEDIATE 8
  7151. #define TK_EXCLUSIVE 9
  7152. #define TK_COMMIT 10
  7153. #define TK_END 11
  7154. #define TK_ROLLBACK 12
  7155. #define TK_SAVEPOINT 13
  7156. #define TK_RELEASE 14
  7157. #define TK_TO 15
  7158. #define TK_CREATE 16
  7159. #define TK_TABLE 17
  7160. #define TK_IF 18
  7161. #define TK_NOT 19
  7162. #define TK_EXISTS 20
  7163. #define TK_TEMP 21
  7164. #define TK_LP 22
  7165. #define TK_RP 23
  7166. #define TK_AS 24
  7167. #define TK_COMMA 25
  7168. #define TK_ID 26
  7169. #define TK_ABORT 27
  7170. #define TK_AFTER 28
  7171. #define TK_ANALYZE 29
  7172. #define TK_ASC 30
  7173. #define TK_ATTACH 31
  7174. #define TK_BEFORE 32
  7175. #define TK_CASCADE 33
  7176. #define TK_CAST 34
  7177. #define TK_CONFLICT 35
  7178. #define TK_DATABASE 36
  7179. #define TK_DESC 37
  7180. #define TK_DETACH 38
  7181. #define TK_EACH 39
  7182. #define TK_FAIL 40
  7183. #define TK_FOR 41
  7184. #define TK_IGNORE 42
  7185. #define TK_INITIALLY 43
  7186. #define TK_INSTEAD 44
  7187. #define TK_LIKE_KW 45
  7188. #define TK_MATCH 46
  7189. #define TK_KEY 47
  7190. #define TK_OF 48
  7191. #define TK_OFFSET 49
  7192. #define TK_PRAGMA 50
  7193. #define TK_RAISE 51
  7194. #define TK_REPLACE 52
  7195. #define TK_RESTRICT 53
  7196. #define TK_ROW 54
  7197. #define TK_TRIGGER 55
  7198. #define TK_VACUUM 56
  7199. #define TK_VIEW 57
  7200. #define TK_VIRTUAL 58
  7201. #define TK_REINDEX 59
  7202. #define TK_RENAME 60
  7203. #define TK_CTIME_KW 61
  7204. #define TK_ANY 62
  7205. #define TK_OR 63
  7206. #define TK_AND 64
  7207. #define TK_IS 65
  7208. #define TK_BETWEEN 66
  7209. #define TK_IN 67
  7210. #define TK_ISNULL 68
  7211. #define TK_NOTNULL 69
  7212. #define TK_NE 70
  7213. #define TK_EQ 71
  7214. #define TK_GT 72
  7215. #define TK_LE 73
  7216. #define TK_LT 74
  7217. #define TK_GE 75
  7218. #define TK_ESCAPE 76
  7219. #define TK_BITAND 77
  7220. #define TK_BITOR 78
  7221. #define TK_LSHIFT 79
  7222. #define TK_RSHIFT 80
  7223. #define TK_PLUS 81
  7224. #define TK_MINUS 82
  7225. #define TK_STAR 83
  7226. #define TK_SLASH 84
  7227. #define TK_REM 85
  7228. #define TK_CONCAT 86
  7229. #define TK_COLLATE 87
  7230. #define TK_UMINUS 88
  7231. #define TK_UPLUS 89
  7232. #define TK_BITNOT 90
  7233. #define TK_STRING 91
  7234. #define TK_JOIN_KW 92
  7235. #define TK_CONSTRAINT 93
  7236. #define TK_DEFAULT 94
  7237. #define TK_NULL 95
  7238. #define TK_PRIMARY 96
  7239. #define TK_UNIQUE 97
  7240. #define TK_CHECK 98
  7241. #define TK_REFERENCES 99
  7242. #define TK_AUTOINCR 100
  7243. #define TK_ON 101
  7244. #define TK_DELETE 102
  7245. #define TK_UPDATE 103
  7246. #define TK_INSERT 104
  7247. #define TK_SET 105
  7248. #define TK_DEFERRABLE 106
  7249. #define TK_FOREIGN 107
  7250. #define TK_DROP 108
  7251. #define TK_UNION 109
  7252. #define TK_ALL 110
  7253. #define TK_EXCEPT 111
  7254. #define TK_INTERSECT 112
  7255. #define TK_SELECT 113
  7256. #define TK_DISTINCT 114
  7257. #define TK_DOT 115
  7258. #define TK_FROM 116
  7259. #define TK_JOIN 117
  7260. #define TK_INDEXED 118
  7261. #define TK_BY 119
  7262. #define TK_USING 120
  7263. #define TK_ORDER 121
  7264. #define TK_GROUP 122
  7265. #define TK_HAVING 123
  7266. #define TK_LIMIT 124
  7267. #define TK_WHERE 125
  7268. #define TK_INTO 126
  7269. #define TK_VALUES 127
  7270. #define TK_INTEGER 128
  7271. #define TK_FLOAT 129
  7272. #define TK_BLOB 130
  7273. #define TK_REGISTER 131
  7274. #define TK_VARIABLE 132
  7275. #define TK_CASE 133
  7276. #define TK_WHEN 134
  7277. #define TK_THEN 135
  7278. #define TK_ELSE 136
  7279. #define TK_INDEX 137
  7280. #define TK_ALTER 138
  7281. #define TK_ADD 139
  7282. #define TK_COLUMNKW 140
  7283. #define TK_TO_TEXT 141
  7284. #define TK_TO_BLOB 142
  7285. #define TK_TO_NUMERIC 143
  7286. #define TK_TO_INT 144
  7287. #define TK_TO_REAL 145
  7288. #define TK_END_OF_FILE 146
  7289. #define TK_ILLEGAL 147
  7290. #define TK_SPACE 148
  7291. #define TK_UNCLOSED_STRING 149
  7292. #define TK_FUNCTION 150
  7293. #define TK_COLUMN 151
  7294. #define TK_AGG_FUNCTION 152
  7295. #define TK_AGG_COLUMN 153
  7296. #define TK_CONST_FUNC 154
  7297. /************** End of parse.h ***********************************************/
  7298. /************** Continuing where we left off in sqliteInt.h ******************/
  7299. #include <stdio.h>
  7300. #include <stdlib.h>
  7301. #include <string.h>
  7302. #include <assert.h>
  7303. #include <stddef.h>
  7304. /*
  7305. ** If compiling for a processor that lacks floating point support,
  7306. ** substitute integer for floating-point
  7307. */
  7308. #ifdef SQLITE_OMIT_FLOATING_POINT
  7309. # define double sqlite_int64
  7310. # define LONGDOUBLE_TYPE sqlite_int64
  7311. # ifndef SQLITE_BIG_DBL
  7312. # define SQLITE_BIG_DBL (0x7fffffffffffffff)
  7313. # endif
  7314. # define SQLITE_OMIT_DATETIME_FUNCS 1
  7315. # define SQLITE_OMIT_TRACE 1
  7316. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  7317. #endif
  7318. #ifndef SQLITE_BIG_DBL
  7319. # define SQLITE_BIG_DBL (1e99)
  7320. #endif
  7321. /*
  7322. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  7323. ** afterward. Having this macro allows us to cause the C compiler
  7324. ** to omit code used by TEMP tables without messy #ifndef statements.
  7325. */
  7326. #ifdef SQLITE_OMIT_TEMPDB
  7327. #define OMIT_TEMPDB 1
  7328. #else
  7329. #define OMIT_TEMPDB 0
  7330. #endif
  7331. /*
  7332. ** If the following macro is set to 1, then NULL values are considered
  7333. ** distinct when determining whether or not two entries are the same
  7334. ** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL,
  7335. ** OCELOT, and Firebird all work. The SQL92 spec explicitly says this
  7336. ** is the way things are suppose to work.
  7337. **
  7338. ** If the following macro is set to 0, the NULLs are indistinct for
  7339. ** a UNIQUE index. In this mode, you can only have a single NULL entry
  7340. ** for a column declared UNIQUE. This is the way Informix and SQL Server
  7341. ** work.
  7342. */
  7343. #define NULL_DISTINCT_FOR_UNIQUE 1
  7344. /*
  7345. ** The "file format" number is an integer that is incremented whenever
  7346. ** the VDBE-level file format changes. The following macros define the
  7347. ** the default file format for new databases and the maximum file format
  7348. ** that the library can read.
  7349. */
  7350. #define SQLITE_MAX_FILE_FORMAT 4
  7351. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  7352. # define SQLITE_DEFAULT_FILE_FORMAT 1
  7353. #endif
  7354. /*
  7355. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  7356. ** on the command-line
  7357. */
  7358. #ifndef SQLITE_TEMP_STORE
  7359. # define SQLITE_TEMP_STORE 1
  7360. #endif
  7361. /*
  7362. ** GCC does not define the offsetof() macro so we'll have to do it
  7363. ** ourselves.
  7364. */
  7365. #ifndef offsetof
  7366. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  7367. #endif
  7368. /*
  7369. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  7370. ** not, there are still machines out there that use EBCDIC.)
  7371. */
  7372. #if 'A' == '\301'
  7373. # define SQLITE_EBCDIC 1
  7374. #else
  7375. # define SQLITE_ASCII 1
  7376. #endif
  7377. /*
  7378. ** Integers of known sizes. These typedefs might change for architectures
  7379. ** where the sizes very. Preprocessor macros are available so that the
  7380. ** types can be conveniently redefined at compile-type. Like this:
  7381. **
  7382. ** cc '-DUINTPTR_TYPE=long long int' ...
  7383. */
  7384. #ifndef UINT32_TYPE
  7385. # ifdef HAVE_UINT32_T
  7386. # define UINT32_TYPE uint32_t
  7387. # else
  7388. # define UINT32_TYPE unsigned int
  7389. # endif
  7390. #endif
  7391. #ifndef UINT16_TYPE
  7392. # ifdef HAVE_UINT16_T
  7393. # define UINT16_TYPE uint16_t
  7394. # else
  7395. # define UINT16_TYPE unsigned short int
  7396. # endif
  7397. #endif
  7398. #ifndef INT16_TYPE
  7399. # ifdef HAVE_INT16_T
  7400. # define INT16_TYPE int16_t
  7401. # else
  7402. # define INT16_TYPE short int
  7403. # endif
  7404. #endif
  7405. #ifndef UINT8_TYPE
  7406. # ifdef HAVE_UINT8_T
  7407. # define UINT8_TYPE uint8_t
  7408. # else
  7409. # define UINT8_TYPE unsigned char
  7410. # endif
  7411. #endif
  7412. #ifndef INT8_TYPE
  7413. # ifdef HAVE_INT8_T
  7414. # define INT8_TYPE int8_t
  7415. # else
  7416. # define INT8_TYPE signed char
  7417. # endif
  7418. #endif
  7419. #ifndef LONGDOUBLE_TYPE
  7420. # define LONGDOUBLE_TYPE long double
  7421. #endif
  7422. typedef sqlite_int64 i64; /* 8-byte signed integer */
  7423. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  7424. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  7425. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  7426. typedef INT16_TYPE i16; /* 2-byte signed integer */
  7427. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  7428. typedef INT8_TYPE i8; /* 1-byte signed integer */
  7429. /*
  7430. ** Macros to determine whether the machine is big or little endian,
  7431. ** evaluated at runtime.
  7432. */
  7433. #ifdef SQLITE_AMALGAMATION
  7434. SQLITE_PRIVATE const int sqlite3one = 1;
  7435. #else
  7436. SQLITE_PRIVATE const int sqlite3one;
  7437. #endif
  7438. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  7439. || defined(__x86_64) || defined(__x86_64__)
  7440. # define SQLITE_BIGENDIAN 0
  7441. # define SQLITE_LITTLEENDIAN 1
  7442. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  7443. #else
  7444. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  7445. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  7446. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  7447. #endif
  7448. /*
  7449. ** Constants for the largest and smallest possible 64-bit signed integers.
  7450. ** These macros are designed to work correctly on both 32-bit and 64-bit
  7451. ** compilers.
  7452. */
  7453. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  7454. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  7455. /*
  7456. ** An instance of the following structure is used to store the busy-handler
  7457. ** callback for a given sqlite handle.
  7458. **
  7459. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  7460. ** callback for the database handle. Each pager opened via the sqlite
  7461. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  7462. ** callback is currently invoked only from within pager.c.
  7463. */
  7464. typedef struct BusyHandler BusyHandler;
  7465. struct BusyHandler {
  7466. int (*xFunc)(void *,int); /* The busy callback */
  7467. void *pArg; /* First arg to busy callback */
  7468. int nBusy; /* Incremented with each busy call */
  7469. };
  7470. /*
  7471. ** Name of the master database table. The master database table
  7472. ** is a special table that holds the names and attributes of all
  7473. ** user tables and indices.
  7474. */
  7475. #define MASTER_NAME "sqlite_master"
  7476. #define TEMP_MASTER_NAME "sqlite_temp_master"
  7477. /*
  7478. ** The root-page of the master database table.
  7479. */
  7480. #define MASTER_ROOT 1
  7481. /*
  7482. ** The name of the schema table.
  7483. */
  7484. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  7485. /*
  7486. ** A convenience macro that returns the number of elements in
  7487. ** an array.
  7488. */
  7489. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  7490. /*
  7491. ** The following value as a destructor means to use sqlite3DbFree().
  7492. ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
  7493. */
  7494. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree)
  7495. /*
  7496. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  7497. ** not support Writable Static Data (WSD) such as global and static variables.
  7498. ** All variables must either be on the stack or dynamically allocated from
  7499. ** the heap. When WSD is unsupported, the variable declarations scattered
  7500. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  7501. ** macro is used for this purpose. And instead of referencing the variable
  7502. ** directly, we use its constant as a key to lookup the run-time allocated
  7503. ** buffer that holds real variable. The constant is also the initializer
  7504. ** for the run-time allocated buffer.
  7505. **
  7506. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  7507. ** macros become no-ops and have zero performance impact.
  7508. */
  7509. #ifdef SQLITE_OMIT_WSD
  7510. #define SQLITE_WSD const
  7511. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  7512. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  7513. SQLITE_API int sqlite3_wsd_init(int N, int J);
  7514. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  7515. #else
  7516. #define SQLITE_WSD
  7517. #define GLOBAL(t,v) v
  7518. #define sqlite3GlobalConfig sqlite3Config
  7519. #endif
  7520. /*
  7521. ** The following macros are used to suppress compiler warnings and to
  7522. ** make it clear to human readers when a function parameter is deliberately
  7523. ** left unused within the body of a function. This usually happens when
  7524. ** a function is called via a function pointer. For example the
  7525. ** implementation of an SQL aggregate step callback may not use the
  7526. ** parameter indicating the number of arguments passed to the aggregate,
  7527. ** if it knows that this is enforced elsewhere.
  7528. **
  7529. ** When a function parameter is not used at all within the body of a function,
  7530. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  7531. ** However, these macros may also be used to suppress warnings related to
  7532. ** parameters that may or may not be used depending on compilation options.
  7533. ** For example those parameters only used in assert() statements. In these
  7534. ** cases the parameters are named as per the usual conventions.
  7535. */
  7536. #define UNUSED_PARAMETER(x) (void)(x)
  7537. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  7538. /*
  7539. ** Forward references to structures
  7540. */
  7541. typedef struct AggInfo AggInfo;
  7542. typedef struct AuthContext AuthContext;
  7543. typedef struct Bitvec Bitvec;
  7544. typedef struct RowSet RowSet;
  7545. typedef struct CollSeq CollSeq;
  7546. typedef struct Column Column;
  7547. typedef struct Db Db;
  7548. typedef struct Schema Schema;
  7549. typedef struct Expr Expr;
  7550. typedef struct ExprList ExprList;
  7551. typedef struct FKey FKey;
  7552. typedef struct FuncDef FuncDef;
  7553. typedef struct FuncDefHash FuncDefHash;
  7554. typedef struct IdList IdList;
  7555. typedef struct Index Index;
  7556. typedef struct KeyClass KeyClass;
  7557. typedef struct KeyInfo KeyInfo;
  7558. typedef struct Lookaside Lookaside;
  7559. typedef struct LookasideSlot LookasideSlot;
  7560. typedef struct Module Module;
  7561. typedef struct NameContext NameContext;
  7562. typedef struct Parse Parse;
  7563. typedef struct Savepoint Savepoint;
  7564. typedef struct Select Select;
  7565. typedef struct SrcList SrcList;
  7566. typedef struct StrAccum StrAccum;
  7567. typedef struct Table Table;
  7568. typedef struct TableLock TableLock;
  7569. typedef struct Token Token;
  7570. typedef struct TriggerStack TriggerStack;
  7571. typedef struct TriggerStep TriggerStep;
  7572. typedef struct Trigger Trigger;
  7573. typedef struct UnpackedRecord UnpackedRecord;
  7574. typedef struct Walker Walker;
  7575. typedef struct WherePlan WherePlan;
  7576. typedef struct WhereInfo WhereInfo;
  7577. typedef struct WhereLevel WhereLevel;
  7578. /*
  7579. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  7580. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  7581. ** pointer types (i.e. FuncDef) defined above.
  7582. */
  7583. /************** Include btree.h in the middle of sqliteInt.h *****************/
  7584. /************** Begin file btree.h *******************************************/
  7585. /*
  7586. ** 2001 September 15
  7587. **
  7588. ** The author disclaims copyright to this source code. In place of
  7589. ** a legal notice, here is a blessing:
  7590. **
  7591. ** May you do good and not evil.
  7592. ** May you find forgiveness for yourself and forgive others.
  7593. ** May you share freely, never taking more than you give.
  7594. **
  7595. *************************************************************************
  7596. ** This header file defines the interface that the sqlite B-Tree file
  7597. ** subsystem. See comments in the source code for a detailed description
  7598. ** of what each interface routine does.
  7599. **
  7600. ** @(#) $Id: btree.h,v 1.106 2008/12/17 17:30:26 danielk1977 Exp $
  7601. */
  7602. #ifndef _BTREE_H_
  7603. #define _BTREE_H_
  7604. /* TODO: This definition is just included so other modules compile. It
  7605. ** needs to be revisited.
  7606. */
  7607. #define SQLITE_N_BTREE_META 10
  7608. /*
  7609. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  7610. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  7611. */
  7612. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  7613. #define SQLITE_DEFAULT_AUTOVACUUM 0
  7614. #endif
  7615. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  7616. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  7617. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  7618. /*
  7619. ** Forward declarations of structure
  7620. */
  7621. typedef struct Btree Btree;
  7622. typedef struct BtCursor BtCursor;
  7623. typedef struct BtShared BtShared;
  7624. typedef struct BtreeMutexArray BtreeMutexArray;
  7625. /*
  7626. ** This structure records all of the Btrees that need to hold
  7627. ** a mutex before we enter sqlite3VdbeExec(). The Btrees are
  7628. ** are placed in aBtree[] in order of aBtree[]->pBt. That way,
  7629. ** we can always lock and unlock them all quickly.
  7630. */
  7631. struct BtreeMutexArray {
  7632. int nMutex;
  7633. Btree *aBtree[SQLITE_MAX_ATTACHED+1];
  7634. };
  7635. SQLITE_PRIVATE int sqlite3BtreeOpen(
  7636. const char *zFilename, /* Name of database file to open */
  7637. sqlite3 *db, /* Associated database connection */
  7638. Btree **, /* Return open Btree* here */
  7639. int flags, /* Flags */
  7640. int vfsFlags /* Flags passed through to VFS open */
  7641. );
  7642. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  7643. ** following values.
  7644. **
  7645. ** NOTE: These values must match the corresponding PAGER_ values in
  7646. ** pager.h.
  7647. */
  7648. #define BTREE_OMIT_JOURNAL 1 /* Do not use journal. No argument */
  7649. #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
  7650. #define BTREE_MEMORY 4 /* In-memory DB. No argument */
  7651. #define BTREE_READONLY 8 /* Open the database in read-only mode */
  7652. #define BTREE_READWRITE 16 /* Open for both reading and writing */
  7653. #define BTREE_CREATE 32 /* Create the database if it does not exist */
  7654. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  7655. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  7656. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
  7657. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  7658. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int);
  7659. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  7660. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  7661. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  7662. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  7663. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  7664. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  7665. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  7666. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
  7667. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  7668. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
  7669. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*);
  7670. SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree*);
  7671. SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree*);
  7672. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  7673. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  7674. SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree*);
  7675. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  7676. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  7677. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
  7678. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);
  7679. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  7680. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  7681. SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *);
  7682. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  7683. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  7684. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  7685. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  7686. ** of the following flags:
  7687. */
  7688. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  7689. #define BTREE_ZERODATA 2 /* Table has keys only - no data */
  7690. #define BTREE_LEAFDATA 4 /* Data stored in leaves only. Implies INTKEY */
  7691. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  7692. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  7693. SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
  7694. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  7695. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  7696. SQLITE_PRIVATE int sqlite3BtreeCursor(
  7697. Btree*, /* BTree containing table to open */
  7698. int iTable, /* Index of root page */
  7699. int wrFlag, /* 1 for writing. 0 for read-only */
  7700. struct KeyInfo*, /* First argument to compare function */
  7701. BtCursor *pCursor /* Space to write cursor structure */
  7702. );
  7703. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  7704. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  7705. SQLITE_PRIVATE int sqlite3BtreeMoveto(
  7706. BtCursor*,
  7707. const void *pKey,
  7708. i64 nKey,
  7709. int bias,
  7710. int *pRes
  7711. );
  7712. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  7713. BtCursor*,
  7714. UnpackedRecord *pUnKey,
  7715. i64 intKey,
  7716. int bias,
  7717. int *pRes
  7718. );
  7719. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  7720. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  7721. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  7722. const void *pData, int nData,
  7723. int nZero, int bias);
  7724. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  7725. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  7726. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  7727. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  7728. SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
  7729. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  7730. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  7731. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  7732. SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor*);
  7733. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
  7734. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
  7735. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  7736. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  7737. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  7738. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  7739. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  7740. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  7741. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  7742. #ifdef SQLITE_TEST
  7743. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  7744. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  7745. #endif
  7746. /*
  7747. ** If we are not using shared cache, then there is no need to
  7748. ** use mutexes to access the BtShared structures. So make the
  7749. ** Enter and Leave procedures no-ops.
  7750. */
  7751. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  7752. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  7753. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  7754. #ifndef NDEBUG
  7755. /* This routine is used inside assert() statements only. */
  7756. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  7757. #endif
  7758. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  7759. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  7760. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  7761. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  7762. #ifndef NDEBUG
  7763. /* This routine is used inside assert() statements only. */
  7764. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  7765. #endif
  7766. SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
  7767. SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
  7768. SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
  7769. #else
  7770. # define sqlite3BtreeEnter(X)
  7771. # define sqlite3BtreeLeave(X)
  7772. #ifndef NDEBUG
  7773. /* This routine is used inside assert() statements only. */
  7774. # define sqlite3BtreeHoldsMutex(X) 1
  7775. #endif
  7776. # define sqlite3BtreeEnterCursor(X)
  7777. # define sqlite3BtreeLeaveCursor(X)
  7778. # define sqlite3BtreeEnterAll(X)
  7779. # define sqlite3BtreeLeaveAll(X)
  7780. #ifndef NDEBUG
  7781. /* This routine is used inside assert() statements only. */
  7782. # define sqlite3BtreeHoldsAllMutexes(X) 1
  7783. #endif
  7784. # define sqlite3BtreeMutexArrayEnter(X)
  7785. # define sqlite3BtreeMutexArrayLeave(X)
  7786. # define sqlite3BtreeMutexArrayInsert(X,Y)
  7787. #endif
  7788. #endif /* _BTREE_H_ */
  7789. /************** End of btree.h ***********************************************/
  7790. /************** Continuing where we left off in sqliteInt.h ******************/
  7791. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  7792. /************** Begin file vdbe.h ********************************************/
  7793. /*
  7794. ** 2001 September 15
  7795. **
  7796. ** The author disclaims copyright to this source code. In place of
  7797. ** a legal notice, here is a blessing:
  7798. **
  7799. ** May you do good and not evil.
  7800. ** May you find forgiveness for yourself and forgive others.
  7801. ** May you share freely, never taking more than you give.
  7802. **
  7803. *************************************************************************
  7804. ** Header file for the Virtual DataBase Engine (VDBE)
  7805. **
  7806. ** This header defines the interface to the virtual database engine
  7807. ** or VDBE. The VDBE implements an abstract machine that runs a
  7808. ** simple program to access and modify the underlying database.
  7809. **
  7810. ** $Id: vdbe.h,v 1.139 2008/10/31 10:53:23 danielk1977 Exp $
  7811. */
  7812. #ifndef _SQLITE_VDBE_H_
  7813. #define _SQLITE_VDBE_H_
  7814. /*
  7815. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  7816. ** in the source file sqliteVdbe.c are allowed to see the insides
  7817. ** of this structure.
  7818. */
  7819. typedef struct Vdbe Vdbe;
  7820. /*
  7821. ** The names of the following types declared in vdbeInt.h are required
  7822. ** for the VdbeOp definition.
  7823. */
  7824. typedef struct VdbeFunc VdbeFunc;
  7825. typedef struct Mem Mem;
  7826. /*
  7827. ** A single instruction of the virtual machine has an opcode
  7828. ** and as many as three operands. The instruction is recorded
  7829. ** as an instance of the following structure:
  7830. */
  7831. struct VdbeOp {
  7832. u8 opcode; /* What operation to perform */
  7833. signed char p4type; /* One of the P4_xxx constants for p4 */
  7834. u8 opflags; /* Not currently used */
  7835. u8 p5; /* Fifth parameter is an unsigned character */
  7836. int p1; /* First operand */
  7837. int p2; /* Second parameter (often the jump destination) */
  7838. int p3; /* The third parameter */
  7839. union { /* forth parameter */
  7840. int i; /* Integer value if p4type==P4_INT32 */
  7841. void *p; /* Generic pointer */
  7842. char *z; /* Pointer to data for string (char array) types */
  7843. i64 *pI64; /* Used when p4type is P4_INT64 */
  7844. double *pReal; /* Used when p4type is P4_REAL */
  7845. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  7846. VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
  7847. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  7848. Mem *pMem; /* Used when p4type is P4_MEM */
  7849. sqlite3_vtab *pVtab; /* Used when p4type is P4_VTAB */
  7850. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  7851. int *ai; /* Used when p4type is P4_INTARRAY */
  7852. } p4;
  7853. #ifdef SQLITE_DEBUG
  7854. char *zComment; /* Comment to improve readability */
  7855. #endif
  7856. #ifdef VDBE_PROFILE
  7857. int cnt; /* Number of times this instruction was executed */
  7858. u64 cycles; /* Total time spent executing this instruction */
  7859. #endif
  7860. };
  7861. typedef struct VdbeOp VdbeOp;
  7862. /*
  7863. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  7864. ** it takes up less space.
  7865. */
  7866. struct VdbeOpList {
  7867. u8 opcode; /* What operation to perform */
  7868. signed char p1; /* First operand */
  7869. signed char p2; /* Second parameter (often the jump destination) */
  7870. signed char p3; /* Third parameter */
  7871. };
  7872. typedef struct VdbeOpList VdbeOpList;
  7873. /*
  7874. ** Allowed values of VdbeOp.p3type
  7875. */
  7876. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  7877. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  7878. #define P4_STATIC (-2) /* Pointer to a static string */
  7879. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  7880. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  7881. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  7882. #define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */
  7883. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  7884. #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
  7885. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  7886. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  7887. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  7888. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  7889. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  7890. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  7891. /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
  7892. ** is made. That copy is freed when the Vdbe is finalized. But if the
  7893. ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
  7894. ** gets freed when the Vdbe is finalized so it still should be obtained
  7895. ** from a single sqliteMalloc(). But no copy is made and the calling
  7896. ** function should *not* try to free the KeyInfo.
  7897. */
  7898. #define P4_KEYINFO_HANDOFF (-16)
  7899. #define P4_KEYINFO_STATIC (-17)
  7900. /*
  7901. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  7902. ** number of columns of data returned by the statement.
  7903. */
  7904. #define COLNAME_NAME 0
  7905. #define COLNAME_DECLTYPE 1
  7906. #define COLNAME_DATABASE 2
  7907. #define COLNAME_TABLE 3
  7908. #define COLNAME_COLUMN 4
  7909. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  7910. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  7911. #else
  7912. # ifdef SQLITE_OMIT_DECLTYPE
  7913. # define COLNAME_N 1 /* Store only the name */
  7914. # else
  7915. # define COLNAME_N 2 /* Store the name and decltype */
  7916. # endif
  7917. #endif
  7918. /*
  7919. ** The following macro converts a relative address in the p2 field
  7920. ** of a VdbeOp structure into a negative number so that
  7921. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  7922. ** the macro again restores the address.
  7923. */
  7924. #define ADDR(X) (-1-(X))
  7925. /*
  7926. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  7927. ** header file that defines a number for each opcode used by the VDBE.
  7928. */
  7929. /************** Include opcodes.h in the middle of vdbe.h ********************/
  7930. /************** Begin file opcodes.h *****************************************/
  7931. /* Automatically generated. Do not edit */
  7932. /* See the mkopcodeh.awk script for details */
  7933. #define OP_VNext 1
  7934. #define OP_Affinity 2
  7935. #define OP_Column 3
  7936. #define OP_SetCookie 4
  7937. #define OP_Seek 5
  7938. #define OP_Real 129 /* same as TK_FLOAT */
  7939. #define OP_Sequence 6
  7940. #define OP_Savepoint 7
  7941. #define OP_Ge 75 /* same as TK_GE */
  7942. #define OP_RowKey 8
  7943. #define OP_SCopy 9
  7944. #define OP_Eq 71 /* same as TK_EQ */
  7945. #define OP_OpenWrite 10
  7946. #define OP_NotNull 69 /* same as TK_NOTNULL */
  7947. #define OP_If 11
  7948. #define OP_ToInt 144 /* same as TK_TO_INT */
  7949. #define OP_String8 91 /* same as TK_STRING */
  7950. #define OP_VRowid 12
  7951. #define OP_CollSeq 13
  7952. #define OP_OpenRead 14
  7953. #define OP_Expire 15
  7954. #define OP_AutoCommit 16
  7955. #define OP_Gt 72 /* same as TK_GT */
  7956. #define OP_Pagecount 17
  7957. #define OP_IntegrityCk 18
  7958. #define OP_Sort 20
  7959. #define OP_Copy 21
  7960. #define OP_Trace 22
  7961. #define OP_Function 23
  7962. #define OP_IfNeg 24
  7963. #define OP_And 64 /* same as TK_AND */
  7964. #define OP_Subtract 82 /* same as TK_MINUS */
  7965. #define OP_Noop 25
  7966. #define OP_Return 26
  7967. #define OP_Remainder 85 /* same as TK_REM */
  7968. #define OP_NewRowid 27
  7969. #define OP_Multiply 83 /* same as TK_STAR */
  7970. #define OP_Variable 28
  7971. #define OP_String 29
  7972. #define OP_RealAffinity 30
  7973. #define OP_VRename 31
  7974. #define OP_ParseSchema 32
  7975. #define OP_VOpen 33
  7976. #define OP_Close 34
  7977. #define OP_CreateIndex 35
  7978. #define OP_IsUnique 36
  7979. #define OP_NotFound 37
  7980. #define OP_Int64 38
  7981. #define OP_MustBeInt 39
  7982. #define OP_Halt 40
  7983. #define OP_Rowid 41
  7984. #define OP_IdxLT 42
  7985. #define OP_AddImm 43
  7986. #define OP_Statement 44
  7987. #define OP_RowData 45
  7988. #define OP_MemMax 46
  7989. #define OP_Or 63 /* same as TK_OR */
  7990. #define OP_NotExists 47
  7991. #define OP_Gosub 48
  7992. #define OP_Divide 84 /* same as TK_SLASH */
  7993. #define OP_Integer 49
  7994. #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
  7995. #define OP_Prev 50
  7996. #define OP_RowSetRead 51
  7997. #define OP_Concat 86 /* same as TK_CONCAT */
  7998. #define OP_RowSetAdd 52
  7999. #define OP_BitAnd 77 /* same as TK_BITAND */
  8000. #define OP_VColumn 53
  8001. #define OP_CreateTable 54
  8002. #define OP_Last 55
  8003. #define OP_SeekLe 56
  8004. #define OP_IsNull 68 /* same as TK_ISNULL */
  8005. #define OP_IncrVacuum 57
  8006. #define OP_IdxRowid 58
  8007. #define OP_ShiftRight 80 /* same as TK_RSHIFT */
  8008. #define OP_ResetCount 59
  8009. #define OP_ContextPush 60
  8010. #define OP_Yield 61
  8011. #define OP_DropTrigger 62
  8012. #define OP_DropIndex 65
  8013. #define OP_IdxGE 66
  8014. #define OP_IdxDelete 67
  8015. #define OP_Vacuum 76
  8016. #define OP_IfNot 87
  8017. #define OP_DropTable 88
  8018. #define OP_SeekLt 89
  8019. #define OP_MakeRecord 92
  8020. #define OP_ToBlob 142 /* same as TK_TO_BLOB */
  8021. #define OP_ResultRow 93
  8022. #define OP_Delete 94
  8023. #define OP_AggFinal 95
  8024. #define OP_Compare 96
  8025. #define OP_ShiftLeft 79 /* same as TK_LSHIFT */
  8026. #define OP_Goto 97
  8027. #define OP_TableLock 98
  8028. #define OP_Clear 99
  8029. #define OP_Le 73 /* same as TK_LE */
  8030. #define OP_VerifyCookie 100
  8031. #define OP_AggStep 101
  8032. #define OP_ToText 141 /* same as TK_TO_TEXT */
  8033. #define OP_Not 19 /* same as TK_NOT */
  8034. #define OP_ToReal 145 /* same as TK_TO_REAL */
  8035. #define OP_SetNumColumns 102
  8036. #define OP_Transaction 103
  8037. #define OP_VFilter 104
  8038. #define OP_Ne 70 /* same as TK_NE */
  8039. #define OP_VDestroy 105
  8040. #define OP_ContextPop 106
  8041. #define OP_BitOr 78 /* same as TK_BITOR */
  8042. #define OP_Next 107
  8043. #define OP_IdxInsert 108
  8044. #define OP_Lt 74 /* same as TK_LT */
  8045. #define OP_SeekGe 109
  8046. #define OP_Insert 110
  8047. #define OP_Destroy 111
  8048. #define OP_ReadCookie 112
  8049. #define OP_LoadAnalysis 113
  8050. #define OP_Explain 114
  8051. #define OP_OpenPseudo 115
  8052. #define OP_OpenEphemeral 116
  8053. #define OP_Null 117
  8054. #define OP_Move 118
  8055. #define OP_Blob 119
  8056. #define OP_Add 81 /* same as TK_PLUS */
  8057. #define OP_Rewind 120
  8058. #define OP_SeekGt 121
  8059. #define OP_VBegin 122
  8060. #define OP_VUpdate 123
  8061. #define OP_IfZero 124
  8062. #define OP_BitNot 90 /* same as TK_BITNOT */
  8063. #define OP_VCreate 125
  8064. #define OP_Found 126
  8065. #define OP_IfPos 127
  8066. #define OP_NullRow 128
  8067. #define OP_Jump 130
  8068. #define OP_Permutation 131
  8069. /* The following opcode values are never used */
  8070. #define OP_NotUsed_132 132
  8071. #define OP_NotUsed_133 133
  8072. #define OP_NotUsed_134 134
  8073. #define OP_NotUsed_135 135
  8074. #define OP_NotUsed_136 136
  8075. #define OP_NotUsed_137 137
  8076. #define OP_NotUsed_138 138
  8077. #define OP_NotUsed_139 139
  8078. #define OP_NotUsed_140 140
  8079. /* Properties such as "out2" or "jump" that are specified in
  8080. ** comments following the "case" for each opcode in the vdbe.c
  8081. ** are encoded into bitvectors as follows:
  8082. */
  8083. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  8084. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  8085. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  8086. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  8087. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  8088. #define OPFLG_OUT3 0x0020 /* out3: P3 is an output */
  8089. #define OPFLG_INITIALIZER {\
  8090. /* 0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00,\
  8091. /* 8 */ 0x00, 0x04, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00,\
  8092. /* 16 */ 0x00, 0x02, 0x00, 0x04, 0x01, 0x04, 0x00, 0x00,\
  8093. /* 24 */ 0x05, 0x00, 0x04, 0x02, 0x02, 0x02, 0x04, 0x00,\
  8094. /* 32 */ 0x00, 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05,\
  8095. /* 40 */ 0x00, 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11,\
  8096. /* 48 */ 0x01, 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01,\
  8097. /* 56 */ 0x11, 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x2c,\
  8098. /* 64 */ 0x2c, 0x00, 0x11, 0x00, 0x05, 0x05, 0x15, 0x15,\
  8099. /* 72 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x2c, 0x2c, 0x2c,\
  8100. /* 80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x05,\
  8101. /* 88 */ 0x00, 0x11, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00,\
  8102. /* 96 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8103. /* 104 */ 0x01, 0x00, 0x00, 0x01, 0x08, 0x11, 0x00, 0x02,\
  8104. /* 112 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02,\
  8105. /* 120 */ 0x01, 0x11, 0x00, 0x00, 0x05, 0x00, 0x11, 0x05,\
  8106. /* 128 */ 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8107. /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
  8108. /* 144 */ 0x04, 0x04,}
  8109. /************** End of opcodes.h *********************************************/
  8110. /************** Continuing where we left off in vdbe.h ***********************/
  8111. /*
  8112. ** Prototypes for the VDBE interface. See comments on the implementation
  8113. ** for a description of what each of these routines does.
  8114. */
  8115. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
  8116. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  8117. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  8118. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  8119. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  8120. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  8121. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  8122. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
  8123. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
  8124. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
  8125. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  8126. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  8127. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
  8128. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  8129. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  8130. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  8131. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  8132. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  8133. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
  8134. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  8135. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  8136. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  8137. #ifdef SQLITE_DEBUG
  8138. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
  8139. #endif
  8140. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  8141. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  8142. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  8143. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  8144. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  8145. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  8146. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
  8147. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  8148. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  8149. SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int);
  8150. #endif
  8151. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,
  8152. UnpackedRecord*,int);
  8153. SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
  8154. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  8155. #ifndef NDEBUG
  8156. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  8157. # define VdbeComment(X) sqlite3VdbeComment X
  8158. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  8159. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  8160. #else
  8161. # define VdbeComment(X)
  8162. # define VdbeNoopComment(X)
  8163. #endif
  8164. #endif
  8165. /************** End of vdbe.h ************************************************/
  8166. /************** Continuing where we left off in sqliteInt.h ******************/
  8167. /************** Include pager.h in the middle of sqliteInt.h *****************/
  8168. /************** Begin file pager.h *******************************************/
  8169. /*
  8170. ** 2001 September 15
  8171. **
  8172. ** The author disclaims copyright to this source code. In place of
  8173. ** a legal notice, here is a blessing:
  8174. **
  8175. ** May you do good and not evil.
  8176. ** May you find forgiveness for yourself and forgive others.
  8177. ** May you share freely, never taking more than you give.
  8178. **
  8179. *************************************************************************
  8180. ** This header file defines the interface that the sqlite page cache
  8181. ** subsystem. The page cache subsystem reads and writes a file a page
  8182. ** at a time and provides a journal for rollback.
  8183. **
  8184. ** @(#) $Id: pager.h,v 1.93 2009/01/07 15:18:21 danielk1977 Exp $
  8185. */
  8186. #ifndef _PAGER_H_
  8187. #define _PAGER_H_
  8188. /*
  8189. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  8190. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  8191. */
  8192. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  8193. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  8194. #endif
  8195. /*
  8196. ** The type used to represent a page number. The first page in a file
  8197. ** is called page 1. 0 is used to represent "not a page".
  8198. */
  8199. typedef u32 Pgno;
  8200. /*
  8201. ** Each open file is managed by a separate instance of the "Pager" structure.
  8202. */
  8203. typedef struct Pager Pager;
  8204. /*
  8205. ** Handle type for pages.
  8206. */
  8207. typedef struct PgHdr DbPage;
  8208. /*
  8209. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  8210. **
  8211. ** NOTE: This values must match the corresponding BTREE_ values in btree.h.
  8212. */
  8213. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  8214. #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
  8215. /*
  8216. ** Valid values for the second argument to sqlite3PagerLockingMode().
  8217. */
  8218. #define PAGER_LOCKINGMODE_QUERY -1
  8219. #define PAGER_LOCKINGMODE_NORMAL 0
  8220. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  8221. /*
  8222. ** Valid values for the second argument to sqlite3PagerJournalMode().
  8223. */
  8224. #define PAGER_JOURNALMODE_QUERY -1
  8225. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  8226. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  8227. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  8228. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  8229. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  8230. /*
  8231. ** See source code comments for a detailed description of the following
  8232. ** routines:
  8233. */
  8234. SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);
  8235. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  8236. SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*));
  8237. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
  8238. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  8239. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  8240. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  8241. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  8242. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  8243. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  8244. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  8245. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  8246. SQLITE_PRIVATE int sqlite3PagerRef(DbPage*);
  8247. SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*);
  8248. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  8249. SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
  8250. SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag);
  8251. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  8252. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  8253. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  8254. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  8255. SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage*);
  8256. SQLITE_PRIVATE int sqlite3PagerDontWrite(DbPage*);
  8257. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  8258. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
  8259. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
  8260. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  8261. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  8262. SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager*);
  8263. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  8264. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  8265. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  8266. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  8267. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  8268. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  8269. SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
  8270. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  8271. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  8272. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
  8273. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  8274. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  8275. #ifndef SQLITE_OMIT_AUTOVACUUM
  8276. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  8277. SQLITE_PRIVATE Pgno sqlite3PagerImageSize(Pager *);
  8278. #endif
  8279. #ifdef SQLITE_HAS_CODEC
  8280. SQLITE_PRIVATE void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
  8281. #endif
  8282. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  8283. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  8284. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  8285. #endif
  8286. #ifdef SQLITE_TEST
  8287. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  8288. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  8289. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  8290. #endif
  8291. #ifdef SQLITE_TEST
  8292. void disable_simulated_io_errors(void);
  8293. void enable_simulated_io_errors(void);
  8294. #else
  8295. # define disable_simulated_io_errors()
  8296. # define enable_simulated_io_errors()
  8297. #endif
  8298. #endif /* _PAGER_H_ */
  8299. /************** End of pager.h ***********************************************/
  8300. /************** Continuing where we left off in sqliteInt.h ******************/
  8301. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  8302. /************** Begin file pcache.h ******************************************/
  8303. /*
  8304. ** 2008 August 05
  8305. **
  8306. ** The author disclaims copyright to this source code. In place of
  8307. ** a legal notice, here is a blessing:
  8308. **
  8309. ** May you do good and not evil.
  8310. ** May you find forgiveness for yourself and forgive others.
  8311. ** May you share freely, never taking more than you give.
  8312. **
  8313. *************************************************************************
  8314. ** This header file defines the interface that the sqlite page cache
  8315. ** subsystem.
  8316. **
  8317. ** @(#) $Id: pcache.h,v 1.16 2008/11/19 16:52:44 danielk1977 Exp $
  8318. */
  8319. #ifndef _PCACHE_H_
  8320. typedef struct PgHdr PgHdr;
  8321. typedef struct PCache PCache;
  8322. /*
  8323. ** Every page in the cache is controlled by an instance of the following
  8324. ** structure.
  8325. */
  8326. struct PgHdr {
  8327. void *pData; /* Content of this page */
  8328. void *pExtra; /* Extra content */
  8329. PgHdr *pDirty; /* Transient list of dirty pages */
  8330. Pgno pgno; /* Page number for this page */
  8331. Pager *pPager; /* The pager this page is part of */
  8332. #ifdef SQLITE_CHECK_PAGES
  8333. u32 pageHash; /* Hash of page content */
  8334. #endif
  8335. u16 flags; /* PGHDR flags defined below */
  8336. /**********************************************************************
  8337. ** Elements above are public. All that follows is private to pcache.c
  8338. ** and should not be accessed by other modules.
  8339. */
  8340. i16 nRef; /* Number of users of this page */
  8341. PCache *pCache; /* Cache that owns this page */
  8342. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  8343. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  8344. };
  8345. /* Bit values for PgHdr.flags */
  8346. #define PGHDR_DIRTY 0x002 /* Page has changed */
  8347. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  8348. ** writing this page to the database */
  8349. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  8350. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  8351. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  8352. /* Initialize and shutdown the page cache subsystem */
  8353. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  8354. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  8355. /* Page cache buffer management:
  8356. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  8357. */
  8358. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  8359. /* Create a new pager cache.
  8360. ** Under memory stress, invoke xStress to try to make pages clean.
  8361. ** Only clean and unpinned pages can be reclaimed.
  8362. */
  8363. SQLITE_PRIVATE void sqlite3PcacheOpen(
  8364. int szPage, /* Size of every page */
  8365. int szExtra, /* Extra space associated with each page */
  8366. int bPurgeable, /* True if pages are on backing store */
  8367. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  8368. void *pStress, /* Argument to xStress */
  8369. PCache *pToInit /* Preallocated space for the PCache */
  8370. );
  8371. /* Modify the page-size after the cache has been created. */
  8372. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  8373. /* Return the size in bytes of a PCache object. Used to preallocate
  8374. ** storage space.
  8375. */
  8376. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  8377. /* One release per successful fetch. Page is pinned until released.
  8378. ** Reference counted.
  8379. */
  8380. SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  8381. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  8382. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  8383. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  8384. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  8385. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  8386. /* Change a page number. Used by incr-vacuum. */
  8387. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  8388. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  8389. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  8390. /* Get a list of all dirty pages in the cache, sorted by page number */
  8391. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  8392. /* Reset and close the cache object */
  8393. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  8394. /* Clear flags from pages of the page cache */
  8395. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  8396. /* Discard the contents of the cache */
  8397. SQLITE_PRIVATE int sqlite3PcacheClear(PCache*);
  8398. /* Return the total number of outstanding page references */
  8399. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  8400. /* Increment the reference count of an existing page */
  8401. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  8402. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  8403. /* Return the total number of pages stored in the cache */
  8404. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  8405. #ifdef SQLITE_CHECK_PAGES
  8406. /* Iterate through all dirty pages currently stored in the cache. This
  8407. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  8408. ** library is built.
  8409. */
  8410. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  8411. #endif
  8412. /* Set and get the suggested cache-size for the specified pager-cache.
  8413. **
  8414. ** If no global maximum is configured, then the system attempts to limit
  8415. ** the total number of pages cached by purgeable pager-caches to the sum
  8416. ** of the suggested cache-sizes.
  8417. */
  8418. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  8419. #ifdef SQLITE_TEST
  8420. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  8421. #endif
  8422. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  8423. /* Try to return memory used by the pcache module to the main memory heap */
  8424. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  8425. #endif
  8426. #ifdef SQLITE_TEST
  8427. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  8428. #endif
  8429. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  8430. #endif /* _PCACHE_H_ */
  8431. /************** End of pcache.h **********************************************/
  8432. /************** Continuing where we left off in sqliteInt.h ******************/
  8433. /************** Include os.h in the middle of sqliteInt.h ********************/
  8434. /************** Begin file os.h **********************************************/
  8435. /*
  8436. ** 2001 September 16
  8437. **
  8438. ** The author disclaims copyright to this source code. In place of
  8439. ** a legal notice, here is a blessing:
  8440. **
  8441. ** May you do good and not evil.
  8442. ** May you find forgiveness for yourself and forgive others.
  8443. ** May you share freely, never taking more than you give.
  8444. **
  8445. ******************************************************************************
  8446. **
  8447. ** This header file (together with is companion C source-code file
  8448. ** "os.c") attempt to abstract the underlying operating system so that
  8449. ** the SQLite library will work on both POSIX and windows systems.
  8450. **
  8451. ** This header file is #include-ed by sqliteInt.h and thus ends up
  8452. ** being included by every source file.
  8453. **
  8454. ** $Id: os.h,v 1.107 2009/01/14 23:03:41 drh Exp $
  8455. */
  8456. #ifndef _SQLITE_OS_H_
  8457. #define _SQLITE_OS_H_
  8458. /*
  8459. ** Figure out if we are dealing with Unix, Windows, or some other
  8460. ** operating system. After the following block of preprocess macros,
  8461. ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
  8462. ** will defined to either 1 or 0. One of the four will be 1. The other
  8463. ** three will be 0.
  8464. */
  8465. #if defined(SQLITE_OS_OTHER)
  8466. # if SQLITE_OS_OTHER==1
  8467. # undef SQLITE_OS_UNIX
  8468. # define SQLITE_OS_UNIX 0
  8469. # undef SQLITE_OS_WIN
  8470. # define SQLITE_OS_WIN 0
  8471. # undef SQLITE_OS_OS2
  8472. # define SQLITE_OS_OS2 0
  8473. # else
  8474. # undef SQLITE_OS_OTHER
  8475. # endif
  8476. #endif
  8477. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  8478. # define SQLITE_OS_OTHER 0
  8479. # ifndef SQLITE_OS_WIN
  8480. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  8481. # define SQLITE_OS_WIN 1
  8482. # define SQLITE_OS_UNIX 0
  8483. # define SQLITE_OS_OS2 0
  8484. # elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
  8485. # define SQLITE_OS_WIN 0
  8486. # define SQLITE_OS_UNIX 0
  8487. # define SQLITE_OS_OS2 1
  8488. # else
  8489. # define SQLITE_OS_WIN 0
  8490. # define SQLITE_OS_UNIX 1
  8491. # define SQLITE_OS_OS2 0
  8492. # endif
  8493. # else
  8494. # define SQLITE_OS_UNIX 0
  8495. # define SQLITE_OS_OS2 0
  8496. # endif
  8497. #else
  8498. # ifndef SQLITE_OS_WIN
  8499. # define SQLITE_OS_WIN 0
  8500. # endif
  8501. #endif
  8502. /*
  8503. ** Determine if we are dealing with WindowsCE - which has a much
  8504. ** reduced API.
  8505. */
  8506. #if defined(_WIN32_WCE)
  8507. # define SQLITE_OS_WINCE 1
  8508. #else
  8509. # define SQLITE_OS_WINCE 0
  8510. #endif
  8511. /*
  8512. ** Define the maximum size of a temporary filename
  8513. */
  8514. #if SQLITE_OS_WIN
  8515. # include <windows.h>
  8516. # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
  8517. #elif SQLITE_OS_OS2
  8518. # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
  8519. # include <os2safe.h> /* has to be included before os2.h for linking to work */
  8520. # endif
  8521. # define INCL_DOSDATETIME
  8522. # define INCL_DOSFILEMGR
  8523. # define INCL_DOSERRORS
  8524. # define INCL_DOSMISC
  8525. # define INCL_DOSPROCESS
  8526. # define INCL_DOSMODULEMGR
  8527. # define INCL_DOSSEMAPHORES
  8528. # include <os2.h>
  8529. # include <uconv.h>
  8530. # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
  8531. #else
  8532. # define SQLITE_TEMPNAME_SIZE 200
  8533. #endif
  8534. /* If the SET_FULLSYNC macro is not defined above, then make it
  8535. ** a no-op
  8536. */
  8537. #ifndef SET_FULLSYNC
  8538. # define SET_FULLSYNC(x,y)
  8539. #endif
  8540. /*
  8541. ** The default size of a disk sector
  8542. */
  8543. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  8544. # define SQLITE_DEFAULT_SECTOR_SIZE 512
  8545. #endif
  8546. /*
  8547. ** Temporary files are named starting with this prefix followed by 16 random
  8548. ** alphanumeric characters, and no file extension. They are stored in the
  8549. ** OS's standard temporary file directory, and are deleted prior to exit.
  8550. ** If sqlite is being embedded in another program, you may wish to change the
  8551. ** prefix to reflect your program's name, so that if your program exits
  8552. ** prematurely, old temporary files can be easily identified. This can be done
  8553. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  8554. **
  8555. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  8556. ** Mcafee started using SQLite in their anti-virus product and it
  8557. ** started putting files with the "sqlite" name in the c:/temp folder.
  8558. ** This annoyed many windows users. Those users would then do a
  8559. ** Google search for "sqlite", find the telephone numbers of the
  8560. ** developers and call to wake them up at night and complain.
  8561. ** For this reason, the default name prefix is changed to be "sqlite"
  8562. ** spelled backwards. So the temp files are still identified, but
  8563. ** anybody smart enough to figure out the code is also likely smart
  8564. ** enough to know that calling the developer will not help get rid
  8565. ** of the file.
  8566. */
  8567. #ifndef SQLITE_TEMP_FILE_PREFIX
  8568. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  8569. #endif
  8570. /*
  8571. ** The following values may be passed as the second argument to
  8572. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  8573. **
  8574. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  8575. ** RESERVED: A single process may hold a RESERVED lock on a file at
  8576. ** any time. Other processes may hold and obtain new SHARED locks.
  8577. ** PENDING: A single process may hold a PENDING lock on a file at
  8578. ** any one time. Existing SHARED locks may persist, but no new
  8579. ** SHARED locks may be obtained by other processes.
  8580. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  8581. **
  8582. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  8583. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  8584. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  8585. ** sqlite3OsLock().
  8586. */
  8587. #define NO_LOCK 0
  8588. #define SHARED_LOCK 1
  8589. #define RESERVED_LOCK 2
  8590. #define PENDING_LOCK 3
  8591. #define EXCLUSIVE_LOCK 4
  8592. /*
  8593. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  8594. **
  8595. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  8596. ** those functions are not available. So we use only LockFile() and
  8597. ** UnlockFile().
  8598. **
  8599. ** LockFile() prevents not just writing but also reading by other processes.
  8600. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  8601. ** byte out of a specific range of bytes. The lock byte is obtained at
  8602. ** random so two separate readers can probably access the file at the
  8603. ** same time, unless they are unlucky and choose the same lock byte.
  8604. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  8605. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  8606. ** a single byte of the file that is designated as the reserved lock byte.
  8607. ** A PENDING_LOCK is obtained by locking a designated byte different from
  8608. ** the RESERVED_LOCK byte.
  8609. **
  8610. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  8611. ** which means we can use reader/writer locks. When reader/writer locks
  8612. ** are used, the lock is placed on the same range of bytes that is used
  8613. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  8614. ** will support two or more Win95 readers or two or more WinNT readers.
  8615. ** But a single Win95 reader will lock out all WinNT readers and a single
  8616. ** WinNT reader will lock out all other Win95 readers.
  8617. **
  8618. ** The following #defines specify the range of bytes used for locking.
  8619. ** SHARED_SIZE is the number of bytes available in the pool from which
  8620. ** a random byte is selected for a shared lock. The pool of bytes for
  8621. ** shared locks begins at SHARED_FIRST.
  8622. **
  8623. ** These #defines are available in sqlite_aux.h so that adaptors for
  8624. ** connecting SQLite to other operating systems can use the same byte
  8625. ** ranges for locking. In particular, the same locking strategy and
  8626. ** byte ranges are used for Unix. This leaves open the possiblity of having
  8627. ** clients on win95, winNT, and unix all talking to the same shared file
  8628. ** and all locking correctly. To do so would require that samba (or whatever
  8629. ** tool is being used for file sharing) implements locks correctly between
  8630. ** windows and unix. I'm guessing that isn't likely to happen, but by
  8631. ** using the same locking range we are at least open to the possibility.
  8632. **
  8633. ** Locking in windows is manditory. For this reason, we cannot store
  8634. ** actual data in the bytes used for locking. The pager never allocates
  8635. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  8636. ** that all locks will fit on a single page even at the minimum page size.
  8637. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  8638. ** is set high so that we don't have to allocate an unused page except
  8639. ** for very large databases. But one should test the page skipping logic
  8640. ** by setting PENDING_BYTE low and running the entire regression suite.
  8641. **
  8642. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  8643. ** file format. Depending on how it is changed, you might not notice
  8644. ** the incompatibility right away, even running a full regression test.
  8645. ** The default location of PENDING_BYTE is the first byte past the
  8646. ** 1GB boundary.
  8647. **
  8648. */
  8649. #ifndef SQLITE_TEST
  8650. #define PENDING_BYTE 0x40000000 /* First byte past the 1GB boundary */
  8651. #else
  8652. SQLITE_API extern unsigned int sqlite3_pending_byte;
  8653. #define PENDING_BYTE sqlite3_pending_byte
  8654. #endif
  8655. #define RESERVED_BYTE (PENDING_BYTE+1)
  8656. #define SHARED_FIRST (PENDING_BYTE+2)
  8657. #define SHARED_SIZE 510
  8658. /*
  8659. ** Functions for accessing sqlite3_file methods
  8660. */
  8661. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  8662. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  8663. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  8664. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  8665. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  8666. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  8667. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  8668. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  8669. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  8670. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  8671. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  8672. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  8673. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  8674. /*
  8675. ** Functions for accessing sqlite3_vfs methods
  8676. */
  8677. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  8678. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  8679. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  8680. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  8681. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  8682. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  8683. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  8684. void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  8685. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  8686. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  8687. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  8688. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  8689. SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
  8690. /*
  8691. ** Convenience functions for opening and closing files using
  8692. ** sqlite3_malloc() to obtain space for the file-handle structure.
  8693. */
  8694. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  8695. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  8696. #endif /* _SQLITE_OS_H_ */
  8697. /************** End of os.h **************************************************/
  8698. /************** Continuing where we left off in sqliteInt.h ******************/
  8699. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  8700. /************** Begin file mutex.h *******************************************/
  8701. /*
  8702. ** 2007 August 28
  8703. **
  8704. ** The author disclaims copyright to this source code. In place of
  8705. ** a legal notice, here is a blessing:
  8706. **
  8707. ** May you do good and not evil.
  8708. ** May you find forgiveness for yourself and forgive others.
  8709. ** May you share freely, never taking more than you give.
  8710. **
  8711. *************************************************************************
  8712. **
  8713. ** This file contains the common header for all mutex implementations.
  8714. ** The sqliteInt.h header #includes this file so that it is available
  8715. ** to all source files. We break it out in an effort to keep the code
  8716. ** better organized.
  8717. **
  8718. ** NOTE: source files should *not* #include this header file directly.
  8719. ** Source files should #include the sqliteInt.h file and let that file
  8720. ** include this one indirectly.
  8721. **
  8722. ** $Id: mutex.h,v 1.9 2008/10/07 15:25:48 drh Exp $
  8723. */
  8724. /*
  8725. ** Figure out what version of the code to use. The choices are
  8726. **
  8727. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  8728. ** mutexes implemention cannot be overridden
  8729. ** at start-time.
  8730. **
  8731. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  8732. ** mutual exclusion is provided. But this
  8733. ** implementation can be overridden at
  8734. ** start-time.
  8735. **
  8736. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  8737. **
  8738. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  8739. **
  8740. ** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2.
  8741. */
  8742. #if !SQLITE_THREADSAFE
  8743. # define SQLITE_MUTEX_OMIT
  8744. #endif
  8745. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  8746. # if SQLITE_OS_UNIX
  8747. # define SQLITE_MUTEX_PTHREADS
  8748. # elif SQLITE_OS_WIN
  8749. # define SQLITE_MUTEX_W32
  8750. # elif SQLITE_OS_OS2
  8751. # define SQLITE_MUTEX_OS2
  8752. # else
  8753. # define SQLITE_MUTEX_NOOP
  8754. # endif
  8755. #endif
  8756. #ifdef SQLITE_MUTEX_OMIT
  8757. /*
  8758. ** If this is a no-op implementation, implement everything as macros.
  8759. */
  8760. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  8761. #define sqlite3_mutex_free(X)
  8762. #define sqlite3_mutex_enter(X)
  8763. #define sqlite3_mutex_try(X) SQLITE_OK
  8764. #define sqlite3_mutex_leave(X)
  8765. #define sqlite3_mutex_held(X) 1
  8766. #define sqlite3_mutex_notheld(X) 1
  8767. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  8768. #define sqlite3MutexInit() SQLITE_OK
  8769. #define sqlite3MutexEnd()
  8770. #endif /* defined(SQLITE_OMIT_MUTEX) */
  8771. /************** End of mutex.h ***********************************************/
  8772. /************** Continuing where we left off in sqliteInt.h ******************/
  8773. /*
  8774. ** Each database file to be accessed by the system is an instance
  8775. ** of the following structure. There are normally two of these structures
  8776. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  8777. ** aDb[1] is the database file used to hold temporary tables. Additional
  8778. ** databases may be attached.
  8779. */
  8780. struct Db {
  8781. char *zName; /* Name of this database */
  8782. Btree *pBt; /* The B*Tree structure for this database file */
  8783. u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
  8784. u8 safety_level; /* How aggressive at syncing data to disk */
  8785. void *pAux; /* Auxiliary data. Usually NULL */
  8786. void (*xFreeAux)(void*); /* Routine to free pAux */
  8787. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  8788. };
  8789. /*
  8790. ** An instance of the following structure stores a database schema.
  8791. **
  8792. ** If there are no virtual tables configured in this schema, the
  8793. ** Schema.db variable is set to NULL. After the first virtual table
  8794. ** has been added, it is set to point to the database connection
  8795. ** used to create the connection. Once a virtual table has been
  8796. ** added to the Schema structure and the Schema.db variable populated,
  8797. ** only that database connection may use the Schema to prepare
  8798. ** statements.
  8799. */
  8800. struct Schema {
  8801. int schema_cookie; /* Database schema version number for this file */
  8802. Hash tblHash; /* All tables indexed by name */
  8803. Hash idxHash; /* All (named) indices indexed by name */
  8804. Hash trigHash; /* All triggers indexed by name */
  8805. Hash aFKey; /* Foreign keys indexed by to-table */
  8806. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  8807. u8 file_format; /* Schema format version for this file */
  8808. u8 enc; /* Text encoding used by this database */
  8809. u16 flags; /* Flags associated with this schema */
  8810. int cache_size; /* Number of pages to use in the cache */
  8811. #ifndef SQLITE_OMIT_VIRTUALTABLE
  8812. sqlite3 *db; /* "Owner" connection. See comment above */
  8813. #endif
  8814. };
  8815. /*
  8816. ** These macros can be used to test, set, or clear bits in the
  8817. ** Db.flags field.
  8818. */
  8819. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  8820. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  8821. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  8822. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  8823. /*
  8824. ** Allowed values for the DB.flags field.
  8825. **
  8826. ** The DB_SchemaLoaded flag is set after the database schema has been
  8827. ** read into internal hash tables.
  8828. **
  8829. ** DB_UnresetViews means that one or more views have column names that
  8830. ** have been filled out. If the schema changes, these column names might
  8831. ** changes and so the view will need to be reset.
  8832. */
  8833. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  8834. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  8835. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  8836. /*
  8837. ** The number of different kinds of things that can be limited
  8838. ** using the sqlite3_limit() interface.
  8839. */
  8840. #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
  8841. /*
  8842. ** Lookaside malloc is a set of fixed-size buffers that can be used
  8843. ** to satisfy small transient memory allocation requests for objects
  8844. ** associated with a particular database connection. The use of
  8845. ** lookaside malloc provides a significant performance enhancement
  8846. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  8847. ** SQL statements.
  8848. **
  8849. ** The Lookaside structure holds configuration information about the
  8850. ** lookaside malloc subsystem. Each available memory allocation in
  8851. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  8852. ** objects.
  8853. */
  8854. struct Lookaside {
  8855. u16 sz; /* Size of each buffer in bytes */
  8856. u8 bEnabled; /* True if use lookaside. False to ignore it */
  8857. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  8858. int nOut; /* Number of buffers currently checked out */
  8859. int mxOut; /* Highwater mark for nOut */
  8860. LookasideSlot *pFree; /* List of available buffers */
  8861. void *pStart; /* First byte of available memory space */
  8862. void *pEnd; /* First byte past end of available space */
  8863. };
  8864. struct LookasideSlot {
  8865. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  8866. };
  8867. /*
  8868. ** A hash table for function definitions.
  8869. **
  8870. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  8871. ** Collisions are on the FuncDef.pHash chain.
  8872. */
  8873. struct FuncDefHash {
  8874. FuncDef *a[23]; /* Hash table for functions */
  8875. };
  8876. /*
  8877. ** Each database is an instance of the following structure.
  8878. **
  8879. ** The sqlite.lastRowid records the last insert rowid generated by an
  8880. ** insert statement. Inserts on views do not affect its value. Each
  8881. ** trigger has its own context, so that lastRowid can be updated inside
  8882. ** triggers as usual. The previous value will be restored once the trigger
  8883. ** exits. Upon entering a before or instead of trigger, lastRowid is no
  8884. ** longer (since after version 2.8.12) reset to -1.
  8885. **
  8886. ** The sqlite.nChange does not count changes within triggers and keeps no
  8887. ** context. It is reset at start of sqlite3_exec.
  8888. ** The sqlite.lsChange represents the number of changes made by the last
  8889. ** insert, update, or delete statement. It remains constant throughout the
  8890. ** length of a statement and is then updated by OP_SetCounts. It keeps a
  8891. ** context stack just like lastRowid so that the count of changes
  8892. ** within a trigger is not seen outside the trigger. Changes to views do not
  8893. ** affect the value of lsChange.
  8894. ** The sqlite.csChange keeps track of the number of current changes (since
  8895. ** the last statement) and is used to update sqlite_lsChange.
  8896. **
  8897. ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
  8898. ** store the most recent error code and, if applicable, string. The
  8899. ** internal function sqlite3Error() is used to set these variables
  8900. ** consistently.
  8901. */
  8902. struct sqlite3 {
  8903. sqlite3_vfs *pVfs; /* OS Interface */
  8904. int nDb; /* Number of backends currently in use */
  8905. Db *aDb; /* All backends */
  8906. int flags; /* Miscellaneous flags. See below */
  8907. int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  8908. int errCode; /* Most recent error code (SQLITE_*) */
  8909. int errMask; /* & result codes with this before returning */
  8910. u8 autoCommit; /* The auto-commit flag. */
  8911. u8 temp_store; /* 1: file 2: memory 0: default */
  8912. u8 mallocFailed; /* True if we have seen a malloc failure */
  8913. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  8914. u8 dfltJournalMode; /* Default journal mode for attached dbs */
  8915. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  8916. int nextPagesize; /* Pagesize after VACUUM if >0 */
  8917. int nTable; /* Number of tables in the database */
  8918. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  8919. i64 lastRowid; /* ROWID of most recent insert (see above) */
  8920. i64 priorNewRowid; /* Last randomly generated ROWID */
  8921. u32 magic; /* Magic number for detect library misuse */
  8922. int nChange; /* Value returned by sqlite3_changes() */
  8923. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  8924. sqlite3_mutex *mutex; /* Connection mutex */
  8925. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  8926. struct sqlite3InitInfo { /* Information used during initialization */
  8927. int iDb; /* When back is being initialized */
  8928. int newTnum; /* Rootpage of table being initialized */
  8929. u8 busy; /* TRUE if currently initializing */
  8930. } init;
  8931. int nExtension; /* Number of loaded extensions */
  8932. void **aExtension; /* Array of shared library handles */
  8933. struct Vdbe *pVdbe; /* List of active virtual machines */
  8934. int activeVdbeCnt; /* Number of VDBEs currently executing */
  8935. int writeVdbeCnt; /* Number of active VDBEs that are writing */
  8936. void (*xTrace)(void*,const char*); /* Trace function */
  8937. void *pTraceArg; /* Argument to the trace function */
  8938. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  8939. void *pProfileArg; /* Argument to profile function */
  8940. void *pCommitArg; /* Argument to xCommitCallback() */
  8941. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  8942. void *pRollbackArg; /* Argument to xRollbackCallback() */
  8943. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  8944. void *pUpdateArg;
  8945. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  8946. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  8947. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  8948. void *pCollNeededArg;
  8949. sqlite3_value *pErr; /* Most recent error message */
  8950. char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
  8951. char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
  8952. union {
  8953. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  8954. double notUsed1; /* Spacer */
  8955. } u1;
  8956. Lookaside lookaside; /* Lookaside malloc configuration */
  8957. #ifndef SQLITE_OMIT_AUTHORIZATION
  8958. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  8959. /* Access authorization function */
  8960. void *pAuthArg; /* 1st argument to the access auth function */
  8961. #endif
  8962. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  8963. int (*xProgress)(void *); /* The progress callback */
  8964. void *pProgressArg; /* Argument to the progress callback */
  8965. int nProgressOps; /* Number of opcodes for progress callback */
  8966. #endif
  8967. #ifndef SQLITE_OMIT_VIRTUALTABLE
  8968. Hash aModule; /* populated by sqlite3_create_module() */
  8969. Table *pVTab; /* vtab with active Connect/Create method */
  8970. sqlite3_vtab **aVTrans; /* Virtual tables with open transactions */
  8971. int nVTrans; /* Allocated size of aVTrans */
  8972. #endif
  8973. FuncDefHash aFunc; /* Hash table of connection functions */
  8974. Hash aCollSeq; /* All collating sequences */
  8975. BusyHandler busyHandler; /* Busy callback */
  8976. int busyTimeout; /* Busy handler timeout, in msec */
  8977. Db aDbStatic[2]; /* Static space for the 2 default backends */
  8978. #ifdef SQLITE_SSE
  8979. sqlite3_stmt *pFetch; /* Used by SSE to fetch stored statements */
  8980. #endif
  8981. Savepoint *pSavepoint; /* List of active savepoints */
  8982. int nSavepoint; /* Number of non-transaction savepoints */
  8983. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  8984. };
  8985. /*
  8986. ** A macro to discover the encoding of a database.
  8987. */
  8988. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  8989. /*
  8990. ** Possible values for the sqlite.flags and or Db.flags fields.
  8991. **
  8992. ** On sqlite.flags, the SQLITE_InTrans value means that we have
  8993. ** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement
  8994. ** transaction is active on that particular database file.
  8995. */
  8996. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  8997. #define SQLITE_InTrans 0x00000008 /* True if in a transaction */
  8998. #define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */
  8999. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  9000. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  9001. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  9002. /* DELETE, or UPDATE and return */
  9003. /* the count using a callback. */
  9004. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  9005. /* result set is empty */
  9006. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  9007. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  9008. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  9009. #define SQLITE_NoReadlock 0x00001000 /* Readlocks are omitted when
  9010. ** accessing read-only databases */
  9011. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  9012. #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
  9013. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  9014. #define SQLITE_FullFSync 0x00010000 /* Use full fsync on the backend */
  9015. #define SQLITE_LoadExtension 0x00020000 /* Enable load_extension */
  9016. #define SQLITE_RecoveryMode 0x00040000 /* Ignore schema errors */
  9017. #define SQLITE_SharedCache 0x00080000 /* Cache sharing is enabled */
  9018. #define SQLITE_Vtab 0x00100000 /* There exists a virtual table */
  9019. #define SQLITE_CommitBusy 0x00200000 /* In the process of committing */
  9020. /*
  9021. ** Possible values for the sqlite.magic field.
  9022. ** The numbers are obtained at random and have no special meaning, other
  9023. ** than being distinct from one another.
  9024. */
  9025. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  9026. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  9027. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  9028. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  9029. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  9030. /*
  9031. ** Each SQL function is defined by an instance of the following
  9032. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  9033. ** hash table. When multiple functions have the same name, the hash table
  9034. ** points to a linked list of these structures.
  9035. */
  9036. struct FuncDef {
  9037. i16 nArg; /* Number of arguments. -1 means unlimited */
  9038. u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
  9039. u8 flags; /* Some combination of SQLITE_FUNC_* */
  9040. void *pUserData; /* User data parameter */
  9041. FuncDef *pNext; /* Next function with same name */
  9042. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  9043. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  9044. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  9045. char *zName; /* SQL name of the function. */
  9046. FuncDef *pHash; /* Next with a different name but the same hash */
  9047. };
  9048. /*
  9049. ** Possible values for FuncDef.flags
  9050. */
  9051. #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
  9052. #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
  9053. #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
  9054. #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
  9055. #define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */
  9056. /*
  9057. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  9058. ** used to create the initializers for the FuncDef structures.
  9059. **
  9060. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  9061. ** Used to create a scalar function definition of a function zName
  9062. ** implemented by C function xFunc that accepts nArg arguments. The
  9063. ** value passed as iArg is cast to a (void*) and made available
  9064. ** as the user-data (sqlite3_user_data()) for the function. If
  9065. ** argument bNC is true, then the FuncDef.needCollate flag is set.
  9066. **
  9067. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  9068. ** Used to create an aggregate function definition implemented by
  9069. ** the C functions xStep and xFinal. The first four parameters
  9070. ** are interpreted in the same way as the first 4 parameters to
  9071. ** FUNCTION().
  9072. **
  9073. ** LIKEFUNC(zName, nArg, pArg, flags)
  9074. ** Used to create a scalar function definition of a function zName
  9075. ** that accepts nArg arguments and is implemented by a call to C
  9076. ** function likeFunc. Argument pArg is cast to a (void *) and made
  9077. ** available as the function user-data (sqlite3_user_data()). The
  9078. ** FuncDef.flags variable is set to the value passed as the flags
  9079. ** parameter.
  9080. */
  9081. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  9082. {nArg, SQLITE_UTF8, bNC*8, SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
  9083. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  9084. {nArg, SQLITE_UTF8, bNC*8, pArg, 0, xFunc, 0, 0, #zName, 0}
  9085. #define LIKEFUNC(zName, nArg, arg, flags) \
  9086. {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
  9087. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  9088. {nArg, SQLITE_UTF8, nc*8, SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
  9089. /*
  9090. ** All current savepoints are stored in a linked list starting at
  9091. ** sqlite3.pSavepoint. The first element in the list is the most recently
  9092. ** opened savepoint. Savepoints are added to the list by the vdbe
  9093. ** OP_Savepoint instruction.
  9094. */
  9095. struct Savepoint {
  9096. char *zName; /* Savepoint name (nul-terminated) */
  9097. Savepoint *pNext; /* Parent savepoint (if any) */
  9098. };
  9099. /*
  9100. ** The following are used as the second parameter to sqlite3Savepoint(),
  9101. ** and as the P1 argument to the OP_Savepoint instruction.
  9102. */
  9103. #define SAVEPOINT_BEGIN 0
  9104. #define SAVEPOINT_RELEASE 1
  9105. #define SAVEPOINT_ROLLBACK 2
  9106. /*
  9107. ** Each SQLite module (virtual table definition) is defined by an
  9108. ** instance of the following structure, stored in the sqlite3.aModule
  9109. ** hash table.
  9110. */
  9111. struct Module {
  9112. const sqlite3_module *pModule; /* Callback pointers */
  9113. const char *zName; /* Name passed to create_module() */
  9114. void *pAux; /* pAux passed to create_module() */
  9115. void (*xDestroy)(void *); /* Module destructor function */
  9116. };
  9117. /*
  9118. ** information about each column of an SQL table is held in an instance
  9119. ** of this structure.
  9120. */
  9121. struct Column {
  9122. char *zName; /* Name of this column */
  9123. Expr *pDflt; /* Default value of this column */
  9124. char *zType; /* Data type for this column */
  9125. char *zColl; /* Collating sequence. If NULL, use the default */
  9126. u8 notNull; /* True if there is a NOT NULL constraint */
  9127. u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
  9128. char affinity; /* One of the SQLITE_AFF_... values */
  9129. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9130. u8 isHidden; /* True if this column is 'hidden' */
  9131. #endif
  9132. };
  9133. /*
  9134. ** A "Collating Sequence" is defined by an instance of the following
  9135. ** structure. Conceptually, a collating sequence consists of a name and
  9136. ** a comparison routine that defines the order of that sequence.
  9137. **
  9138. ** There may two separate implementations of the collation function, one
  9139. ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
  9140. ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
  9141. ** native byte order. When a collation sequence is invoked, SQLite selects
  9142. ** the version that will require the least expensive encoding
  9143. ** translations, if any.
  9144. **
  9145. ** The CollSeq.pUser member variable is an extra parameter that passed in
  9146. ** as the first argument to the UTF-8 comparison function, xCmp.
  9147. ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
  9148. ** xCmp16.
  9149. **
  9150. ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
  9151. ** collating sequence is undefined. Indices built on an undefined
  9152. ** collating sequence may not be read or written.
  9153. */
  9154. struct CollSeq {
  9155. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  9156. u8 enc; /* Text encoding handled by xCmp() */
  9157. u8 type; /* One of the SQLITE_COLL_... values below */
  9158. void *pUser; /* First argument to xCmp() */
  9159. int (*xCmp)(void*,int, const void*, int, const void*);
  9160. void (*xDel)(void*); /* Destructor for pUser */
  9161. };
  9162. /*
  9163. ** Allowed values of CollSeq.type:
  9164. */
  9165. #define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */
  9166. #define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */
  9167. #define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */
  9168. #define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */
  9169. /*
  9170. ** A sort order can be either ASC or DESC.
  9171. */
  9172. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  9173. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  9174. /*
  9175. ** Column affinity types.
  9176. **
  9177. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  9178. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  9179. ** the speed a little by numbering the values consecutively.
  9180. **
  9181. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  9182. ** when multiple affinity types are concatenated into a string and
  9183. ** used as the P4 operand, they will be more readable.
  9184. **
  9185. ** Note also that the numeric types are grouped together so that testing
  9186. ** for a numeric type is a single comparison.
  9187. */
  9188. #define SQLITE_AFF_TEXT 'a'
  9189. #define SQLITE_AFF_NONE 'b'
  9190. #define SQLITE_AFF_NUMERIC 'c'
  9191. #define SQLITE_AFF_INTEGER 'd'
  9192. #define SQLITE_AFF_REAL 'e'
  9193. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  9194. /*
  9195. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  9196. ** affinity value.
  9197. */
  9198. #define SQLITE_AFF_MASK 0x67
  9199. /*
  9200. ** Additional bit values that can be ORed with an affinity without
  9201. ** changing the affinity.
  9202. */
  9203. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  9204. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  9205. /*
  9206. ** Each SQL table is represented in memory by an instance of the
  9207. ** following structure.
  9208. **
  9209. ** Table.zName is the name of the table. The case of the original
  9210. ** CREATE TABLE statement is stored, but case is not significant for
  9211. ** comparisons.
  9212. **
  9213. ** Table.nCol is the number of columns in this table. Table.aCol is a
  9214. ** pointer to an array of Column structures, one for each column.
  9215. **
  9216. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  9217. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  9218. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  9219. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  9220. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  9221. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  9222. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  9223. **
  9224. ** Table.tnum is the page number for the root BTree page of the table in the
  9225. ** database file. If Table.iDb is the index of the database table backend
  9226. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  9227. ** holds temporary tables and indices. If TF_Ephemeral is set
  9228. ** then the table is stored in a file that is automatically deleted
  9229. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  9230. ** refers VDBE cursor number that holds the table open, not to the root
  9231. ** page number. Transient tables are used to hold the results of a
  9232. ** sub-query that appears instead of a real table name in the FROM clause
  9233. ** of a SELECT statement.
  9234. */
  9235. struct Table {
  9236. sqlite3 *db; /* Associated database connection. Might be NULL. */
  9237. char *zName; /* Name of the table or view */
  9238. int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  9239. int nCol; /* Number of columns in this table */
  9240. Column *aCol; /* Information about each column */
  9241. Index *pIndex; /* List of SQL indexes on this table. */
  9242. int tnum; /* Root BTree node for this table (see note above) */
  9243. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  9244. u16 nRef; /* Number of pointers to this Table */
  9245. u8 tabFlags; /* Mask of TF_* values */
  9246. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  9247. Trigger *pTrigger; /* List of SQL triggers on this table */
  9248. FKey *pFKey; /* Linked list of all foreign keys in this table */
  9249. char *zColAff; /* String defining the affinity of each column */
  9250. #ifndef SQLITE_OMIT_CHECK
  9251. Expr *pCheck; /* The AND of all CHECK constraints */
  9252. #endif
  9253. #ifndef SQLITE_OMIT_ALTERTABLE
  9254. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  9255. #endif
  9256. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9257. Module *pMod; /* Pointer to the implementation of the module */
  9258. sqlite3_vtab *pVtab; /* Pointer to the module instance */
  9259. int nModuleArg; /* Number of arguments to the module */
  9260. char **azModuleArg; /* Text of all module args. [0] is module name */
  9261. #endif
  9262. Schema *pSchema; /* Schema that contains this table */
  9263. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  9264. };
  9265. /*
  9266. ** Allowed values for Tabe.tabFlags.
  9267. */
  9268. #define TF_Readonly 0x01 /* Read-only system table */
  9269. #define TF_Ephemeral 0x02 /* An ephemeral table */
  9270. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  9271. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  9272. #define TF_Virtual 0x10 /* Is a virtual table */
  9273. #define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */
  9274. /*
  9275. ** Test to see whether or not a table is a virtual table. This is
  9276. ** done as a macro so that it will be optimized out when virtual
  9277. ** table support is omitted from the build.
  9278. */
  9279. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9280. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  9281. # define IsHiddenColumn(X) ((X)->isHidden)
  9282. #else
  9283. # define IsVirtual(X) 0
  9284. # define IsHiddenColumn(X) 0
  9285. #endif
  9286. /*
  9287. ** Each foreign key constraint is an instance of the following structure.
  9288. **
  9289. ** A foreign key is associated with two tables. The "from" table is
  9290. ** the table that contains the REFERENCES clause that creates the foreign
  9291. ** key. The "to" table is the table that is named in the REFERENCES clause.
  9292. ** Consider this example:
  9293. **
  9294. ** CREATE TABLE ex1(
  9295. ** a INTEGER PRIMARY KEY,
  9296. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  9297. ** );
  9298. **
  9299. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  9300. **
  9301. ** Each REFERENCES clause generates an instance of the following structure
  9302. ** which is attached to the from-table. The to-table need not exist when
  9303. ** the from-table is created. The existence of the to-table is not checked
  9304. ** until an attempt is made to insert data into the from-table.
  9305. **
  9306. ** The sqlite.aFKey hash table stores pointers to this structure
  9307. ** given the name of a to-table. For each to-table, all foreign keys
  9308. ** associated with that table are on a linked list using the FKey.pNextTo
  9309. ** field.
  9310. */
  9311. struct FKey {
  9312. Table *pFrom; /* The table that contains the REFERENCES clause */
  9313. FKey *pNextFrom; /* Next foreign key in pFrom */
  9314. char *zTo; /* Name of table that the key points to */
  9315. FKey *pNextTo; /* Next foreign key that points to zTo */
  9316. int nCol; /* Number of columns in this key */
  9317. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  9318. int iFrom; /* Index of column in pFrom */
  9319. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  9320. } *aCol; /* One entry for each of nCol column s */
  9321. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  9322. u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
  9323. u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
  9324. u8 insertConf; /* How to resolve conflicts that occur on INSERT */
  9325. };
  9326. /*
  9327. ** SQLite supports many different ways to resolve a constraint
  9328. ** error. ROLLBACK processing means that a constraint violation
  9329. ** causes the operation in process to fail and for the current transaction
  9330. ** to be rolled back. ABORT processing means the operation in process
  9331. ** fails and any prior changes from that one operation are backed out,
  9332. ** but the transaction is not rolled back. FAIL processing means that
  9333. ** the operation in progress stops and returns an error code. But prior
  9334. ** changes due to the same operation are not backed out and no rollback
  9335. ** occurs. IGNORE means that the particular row that caused the constraint
  9336. ** error is not inserted or updated. Processing continues and no error
  9337. ** is returned. REPLACE means that preexisting database rows that caused
  9338. ** a UNIQUE constraint violation are removed so that the new insert or
  9339. ** update can proceed. Processing continues and no error is reported.
  9340. **
  9341. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  9342. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  9343. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  9344. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  9345. ** referenced table row is propagated into the row that holds the
  9346. ** foreign key.
  9347. **
  9348. ** The following symbolic values are used to record which type
  9349. ** of action to take.
  9350. */
  9351. #define OE_None 0 /* There is no constraint to check */
  9352. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  9353. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  9354. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  9355. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  9356. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  9357. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  9358. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  9359. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  9360. #define OE_Cascade 9 /* Cascade the changes */
  9361. #define OE_Default 99 /* Do whatever the default action is */
  9362. /*
  9363. ** An instance of the following structure is passed as the first
  9364. ** argument to sqlite3VdbeKeyCompare and is used to control the
  9365. ** comparison of the two index keys.
  9366. */
  9367. struct KeyInfo {
  9368. sqlite3 *db; /* The database connection */
  9369. u8 enc; /* Text encoding - one of the TEXT_Utf* values */
  9370. u16 nField; /* Number of entries in aColl[] */
  9371. u8 *aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */
  9372. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  9373. };
  9374. /*
  9375. ** An instance of the following structure holds information about a
  9376. ** single index record that has already been parsed out into individual
  9377. ** values.
  9378. **
  9379. ** A record is an object that contains one or more fields of data.
  9380. ** Records are used to store the content of a table row and to store
  9381. ** the key of an index. A blob encoding of a record is created by
  9382. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  9383. ** OP_Column opcode.
  9384. **
  9385. ** This structure holds a record that has already been disassembled
  9386. ** into its constituent fields.
  9387. */
  9388. struct UnpackedRecord {
  9389. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  9390. u16 nField; /* Number of entries in apMem[] */
  9391. u16 flags; /* Boolean settings. UNPACKED_... below */
  9392. Mem *aMem; /* Values */
  9393. };
  9394. /*
  9395. ** Allowed values of UnpackedRecord.flags
  9396. */
  9397. #define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */
  9398. #define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */
  9399. #define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */
  9400. #define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */
  9401. #define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */
  9402. /*
  9403. ** Each SQL index is represented in memory by an
  9404. ** instance of the following structure.
  9405. **
  9406. ** The columns of the table that are to be indexed are described
  9407. ** by the aiColumn[] field of this structure. For example, suppose
  9408. ** we have the following table and index:
  9409. **
  9410. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  9411. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  9412. **
  9413. ** In the Table structure describing Ex1, nCol==3 because there are
  9414. ** three columns in the table. In the Index structure describing
  9415. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  9416. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  9417. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  9418. ** The second column to be indexed (c1) has an index of 0 in
  9419. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  9420. **
  9421. ** The Index.onError field determines whether or not the indexed columns
  9422. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  9423. ** it means this is not a unique index. Otherwise it is a unique index
  9424. ** and the value of Index.onError indicate the which conflict resolution
  9425. ** algorithm to employ whenever an attempt is made to insert a non-unique
  9426. ** element.
  9427. */
  9428. struct Index {
  9429. char *zName; /* Name of this index */
  9430. int nColumn; /* Number of columns in the table used by this index */
  9431. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  9432. unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
  9433. Table *pTable; /* The SQL table being indexed */
  9434. int tnum; /* Page containing root of this index in database file */
  9435. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  9436. u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
  9437. char *zColAff; /* String defining the affinity of each column */
  9438. Index *pNext; /* The next index associated with the same table */
  9439. Schema *pSchema; /* Schema containing this index */
  9440. u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
  9441. char **azColl; /* Array of collation sequence names for index */
  9442. };
  9443. /*
  9444. ** Each token coming out of the lexer is an instance of
  9445. ** this structure. Tokens are also used as part of an expression.
  9446. **
  9447. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  9448. ** may contain random values. Do not make any assumptions about Token.dyn
  9449. ** and Token.n when Token.z==0.
  9450. */
  9451. struct Token {
  9452. const unsigned char *z; /* Text of the token. Not NULL-terminated! */
  9453. unsigned dyn : 1; /* True for malloced memory, false for static */
  9454. unsigned n : 31; /* Number of characters in this token */
  9455. };
  9456. /*
  9457. ** An instance of this structure contains information needed to generate
  9458. ** code for a SELECT that contains aggregate functions.
  9459. **
  9460. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  9461. ** pointer to this structure. The Expr.iColumn field is the index in
  9462. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  9463. ** code for that node.
  9464. **
  9465. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  9466. ** original Select structure that describes the SELECT statement. These
  9467. ** fields do not need to be freed when deallocating the AggInfo structure.
  9468. */
  9469. struct AggInfo {
  9470. u8 directMode; /* Direct rendering mode means take data directly
  9471. ** from source tables rather than from accumulators */
  9472. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  9473. ** than the source table */
  9474. int sortingIdx; /* Cursor number of the sorting index */
  9475. ExprList *pGroupBy; /* The group by clause */
  9476. int nSortingColumn; /* Number of columns in the sorting index */
  9477. struct AggInfo_col { /* For each column used in source tables */
  9478. Table *pTab; /* Source table */
  9479. int iTable; /* Cursor number of the source table */
  9480. int iColumn; /* Column number within the source table */
  9481. int iSorterColumn; /* Column number in the sorting index */
  9482. int iMem; /* Memory location that acts as accumulator */
  9483. Expr *pExpr; /* The original expression */
  9484. } *aCol;
  9485. int nColumn; /* Number of used entries in aCol[] */
  9486. int nColumnAlloc; /* Number of slots allocated for aCol[] */
  9487. int nAccumulator; /* Number of columns that show through to the output.
  9488. ** Additional columns are used only as parameters to
  9489. ** aggregate functions */
  9490. struct AggInfo_func { /* For each aggregate function */
  9491. Expr *pExpr; /* Expression encoding the function */
  9492. FuncDef *pFunc; /* The aggregate function implementation */
  9493. int iMem; /* Memory location that acts as accumulator */
  9494. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  9495. } *aFunc;
  9496. int nFunc; /* Number of entries in aFunc[] */
  9497. int nFuncAlloc; /* Number of slots allocated for aFunc[] */
  9498. };
  9499. /*
  9500. ** Each node of an expression in the parse tree is an instance
  9501. ** of this structure.
  9502. **
  9503. ** Expr.op is the opcode. The integer parser token codes are reused
  9504. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  9505. ** code representing the ">=" operator. This same integer code is reused
  9506. ** to represent the greater-than-or-equal-to operator in the expression
  9507. ** tree.
  9508. **
  9509. ** Expr.pRight and Expr.pLeft are subexpressions. Expr.pList is a list
  9510. ** of argument if the expression is a function.
  9511. **
  9512. ** Expr.token is the operator token for this node. For some expressions
  9513. ** that have subexpressions, Expr.token can be the complete text that gave
  9514. ** rise to the Expr. In the latter case, the token is marked as being
  9515. ** a compound token.
  9516. **
  9517. ** An expression of the form ID or ID.ID refers to a column in a table.
  9518. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  9519. ** the integer cursor number of a VDBE cursor pointing to that table and
  9520. ** Expr.iColumn is the column number for the specific column. If the
  9521. ** expression is used as a result in an aggregate SELECT, then the
  9522. ** value is also stored in the Expr.iAgg column in the aggregate so that
  9523. ** it can be accessed after all aggregates are computed.
  9524. **
  9525. ** If the expression is a function, the Expr.iTable is an integer code
  9526. ** representing which function. If the expression is an unbound variable
  9527. ** marker (a question mark character '?' in the original SQL) then the
  9528. ** Expr.iTable holds the index number for that variable.
  9529. **
  9530. ** If the expression is a subquery then Expr.iColumn holds an integer
  9531. ** register number containing the result of the subquery. If the
  9532. ** subquery gives a constant result, then iTable is -1. If the subquery
  9533. ** gives a different answer at different times during statement processing
  9534. ** then iTable is the address of a subroutine that computes the subquery.
  9535. **
  9536. ** The Expr.pSelect field points to a SELECT statement. The SELECT might
  9537. ** be the right operand of an IN operator. Or, if a scalar SELECT appears
  9538. ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
  9539. ** operand.
  9540. **
  9541. ** If the Expr is of type OP_Column, and the table it is selecting from
  9542. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  9543. ** corresponding table definition.
  9544. */
  9545. struct Expr {
  9546. u8 op; /* Operation performed by this node */
  9547. char affinity; /* The affinity of the column or 0 if not a column */
  9548. u16 flags; /* Various flags. See below */
  9549. CollSeq *pColl; /* The collation type of the column or 0 */
  9550. Expr *pLeft, *pRight; /* Left and right subnodes */
  9551. ExprList *pList; /* A list of expressions used as function arguments
  9552. ** or in "<expr> IN (<expr-list)" */
  9553. Token token; /* An operand token */
  9554. Token span; /* Complete text of the expression */
  9555. int iTable, iColumn; /* When op==TK_COLUMN, then this expr node means the
  9556. ** iColumn-th field of the iTable-th table. */
  9557. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  9558. int iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  9559. int iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  9560. Select *pSelect; /* When the expression is a sub-select. Also the
  9561. ** right side of "<expr> IN (<select>)" */
  9562. Table *pTab; /* Table for TK_COLUMN expressions. */
  9563. #if SQLITE_MAX_EXPR_DEPTH>0
  9564. int nHeight; /* Height of the tree headed by this node */
  9565. #endif
  9566. };
  9567. /*
  9568. ** The following are the meanings of bits in the Expr.flags field.
  9569. */
  9570. #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
  9571. #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
  9572. #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
  9573. #define EP_Error 0x0008 /* Expression contains one or more errors */
  9574. #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
  9575. #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
  9576. #define EP_Dequoted 0x0040 /* True if the string has been dequoted */
  9577. #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
  9578. #define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
  9579. #define EP_AnyAff 0x0200 /* Can take a cached column of any affinity */
  9580. #define EP_FixedDest 0x0400 /* Result needed in a specific register */
  9581. #define EP_IntValue 0x0800 /* Integer value contained in iTable */
  9582. /*
  9583. ** These macros can be used to test, set, or clear bits in the
  9584. ** Expr.flags field.
  9585. */
  9586. #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
  9587. #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
  9588. #define ExprSetProperty(E,P) (E)->flags|=(P)
  9589. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  9590. /*
  9591. ** A list of expressions. Each expression may optionally have a
  9592. ** name. An expr/name combination can be used in several ways, such
  9593. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  9594. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  9595. ** also be used as the argument to a function, in which case the a.zName
  9596. ** field is not used.
  9597. */
  9598. struct ExprList {
  9599. int nExpr; /* Number of expressions on the list */
  9600. int nAlloc; /* Number of entries allocated below */
  9601. int iECursor; /* VDBE Cursor associated with this ExprList */
  9602. struct ExprList_item {
  9603. Expr *pExpr; /* The list of expressions */
  9604. char *zName; /* Token associated with this expression */
  9605. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  9606. u8 done; /* A flag to indicate when processing is finished */
  9607. u16 iCol; /* For ORDER BY, column number in result set */
  9608. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  9609. } *a; /* One entry for each expression */
  9610. };
  9611. /*
  9612. ** An instance of this structure can hold a simple list of identifiers,
  9613. ** such as the list "a,b,c" in the following statements:
  9614. **
  9615. ** INSERT INTO t(a,b,c) VALUES ...;
  9616. ** CREATE INDEX idx ON t(a,b,c);
  9617. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  9618. **
  9619. ** The IdList.a.idx field is used when the IdList represents the list of
  9620. ** column names after a table name in an INSERT statement. In the statement
  9621. **
  9622. ** INSERT INTO t(a,b,c) ...
  9623. **
  9624. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  9625. */
  9626. struct IdList {
  9627. struct IdList_item {
  9628. char *zName; /* Name of the identifier */
  9629. int idx; /* Index in some Table.aCol[] of a column named zName */
  9630. } *a;
  9631. int nId; /* Number of identifiers on the list */
  9632. int nAlloc; /* Number of entries allocated for a[] below */
  9633. };
  9634. /*
  9635. ** The bitmask datatype defined below is used for various optimizations.
  9636. **
  9637. ** Changing this from a 64-bit to a 32-bit type limits the number of
  9638. ** tables in a join to 32 instead of 64. But it also reduces the size
  9639. ** of the library by 738 bytes on ix86.
  9640. */
  9641. typedef u64 Bitmask;
  9642. /*
  9643. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  9644. */
  9645. #define BMS ((int)(sizeof(Bitmask)*8))
  9646. /*
  9647. ** The following structure describes the FROM clause of a SELECT statement.
  9648. ** Each table or subquery in the FROM clause is a separate element of
  9649. ** the SrcList.a[] array.
  9650. **
  9651. ** With the addition of multiple database support, the following structure
  9652. ** can also be used to describe a particular table such as the table that
  9653. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  9654. ** such a table must be a simple name: ID. But in SQLite, the table can
  9655. ** now be identified by a database name, a dot, then the table name: ID.ID.
  9656. **
  9657. ** The jointype starts out showing the join type between the current table
  9658. ** and the next table on the list. The parser builds the list this way.
  9659. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  9660. ** jointype expresses the join between the table and the previous table.
  9661. */
  9662. struct SrcList {
  9663. i16 nSrc; /* Number of tables or subqueries in the FROM clause */
  9664. i16 nAlloc; /* Number of entries allocated in a[] below */
  9665. struct SrcList_item {
  9666. char *zDatabase; /* Name of database holding this table */
  9667. char *zName; /* Name of the table */
  9668. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  9669. Table *pTab; /* An SQL table corresponding to zName */
  9670. Select *pSelect; /* A SELECT statement used in place of a table name */
  9671. u8 isPopulated; /* Temporary table associated with SELECT is populated */
  9672. u8 jointype; /* Type of join between this able and the previous */
  9673. u8 notIndexed; /* True if there is a NOT INDEXED clause */
  9674. int iCursor; /* The VDBE cursor number used to access this table */
  9675. Expr *pOn; /* The ON clause of a join */
  9676. IdList *pUsing; /* The USING clause of a join */
  9677. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  9678. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  9679. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  9680. } a[1]; /* One entry for each identifier on the list */
  9681. };
  9682. /*
  9683. ** Permitted values of the SrcList.a.jointype field
  9684. */
  9685. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  9686. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  9687. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  9688. #define JT_LEFT 0x0008 /* Left outer join */
  9689. #define JT_RIGHT 0x0010 /* Right outer join */
  9690. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  9691. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  9692. /*
  9693. ** A WherePlan object holds information that describes a lookup
  9694. ** strategy.
  9695. **
  9696. ** This object is intended to be opaque outside of the where.c module.
  9697. ** It is included here only so that that compiler will know how big it
  9698. ** is. None of the fields in this object should be used outside of
  9699. ** the where.c module.
  9700. **
  9701. ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
  9702. ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
  9703. ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
  9704. ** case that more than one of these conditions is true.
  9705. */
  9706. struct WherePlan {
  9707. u32 wsFlags; /* WHERE_* flags that describe the strategy */
  9708. u32 nEq; /* Number of == constraints */
  9709. union {
  9710. Index *pIdx; /* Index when WHERE_INDEXED is true */
  9711. struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
  9712. sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
  9713. } u;
  9714. };
  9715. /*
  9716. ** For each nested loop in a WHERE clause implementation, the WhereInfo
  9717. ** structure contains a single instance of this structure. This structure
  9718. ** is intended to be private the the where.c module and should not be
  9719. ** access or modified by other modules.
  9720. **
  9721. ** The pIdxInfo field is used to help pick the best index on a
  9722. ** virtual table. The pIdxInfo pointer contains indexing
  9723. ** information for the i-th table in the FROM clause before reordering.
  9724. ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
  9725. ** All other information in the i-th WhereLevel object for the i-th table
  9726. ** after FROM clause ordering.
  9727. */
  9728. struct WhereLevel {
  9729. WherePlan plan; /* query plan for this element of the FROM clause */
  9730. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  9731. int iTabCur; /* The VDBE cursor used to access the table */
  9732. int iIdxCur; /* The VDBE cursor used to access pIdx */
  9733. int addrBrk; /* Jump here to break out of the loop */
  9734. int addrNxt; /* Jump here to start the next IN combination */
  9735. int addrCont; /* Jump here to continue with the next loop cycle */
  9736. int addrFirst; /* First instruction of interior of the loop */
  9737. u8 iFrom; /* Which entry in the FROM clause */
  9738. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  9739. int p1, p2; /* Operands of the opcode used to ends the loop */
  9740. union { /* Information that depends on plan.wsFlags */
  9741. struct {
  9742. int nIn; /* Number of entries in aInLoop[] */
  9743. struct InLoop {
  9744. int iCur; /* The VDBE cursor used by this IN operator */
  9745. int addrInTop; /* Top of the IN loop */
  9746. } *aInLoop; /* Information about each nested IN operator */
  9747. } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
  9748. struct {
  9749. WherePlan *aPlan; /* Plans for each term of the WHERE clause */
  9750. } or; /* Used when plan.wsFlags&WHERE_MULTI_OR */
  9751. } u;
  9752. /* The following field is really not part of the current level. But
  9753. ** we need a place to cache virtual table index information for each
  9754. ** virtual table in the FROM clause and the WhereLevel structure is
  9755. ** a convenient place since there is one WhereLevel for each FROM clause
  9756. ** element.
  9757. */
  9758. sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
  9759. };
  9760. /*
  9761. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin().
  9762. */
  9763. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  9764. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  9765. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  9766. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  9767. #define WHERE_FILL_ROWSET 0x0008 /* Save results in a RowSet object */
  9768. #define WHERE_OMIT_OPEN 0x0010 /* Table cursor are already open */
  9769. #define WHERE_OMIT_CLOSE 0x0020 /* Omit close of table & index cursors */
  9770. /*
  9771. ** The WHERE clause processing routine has two halves. The
  9772. ** first part does the start of the WHERE loop and the second
  9773. ** half does the tail of the WHERE loop. An instance of
  9774. ** this structure is returned by the first half and passed
  9775. ** into the second half to give some continuity.
  9776. */
  9777. struct WhereInfo {
  9778. Parse *pParse; /* Parsing and code generating context */
  9779. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  9780. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
  9781. int regRowSet; /* Store rowids in this rowset if >=0 */
  9782. SrcList *pTabList; /* List of tables in the join */
  9783. int iTop; /* The very beginning of the WHERE loop */
  9784. int iContinue; /* Jump here to continue with next record */
  9785. int iBreak; /* Jump here to break out of the loop */
  9786. int nLevel; /* Number of nested loop */
  9787. struct WhereClause *pWC; /* Decomposition of the WHERE clause */
  9788. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  9789. };
  9790. /*
  9791. ** A NameContext defines a context in which to resolve table and column
  9792. ** names. The context consists of a list of tables (the pSrcList) field and
  9793. ** a list of named expression (pEList). The named expression list may
  9794. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  9795. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  9796. ** pEList corresponds to the result set of a SELECT and is NULL for
  9797. ** other statements.
  9798. **
  9799. ** NameContexts can be nested. When resolving names, the inner-most
  9800. ** context is searched first. If no match is found, the next outer
  9801. ** context is checked. If there is still no match, the next context
  9802. ** is checked. This process continues until either a match is found
  9803. ** or all contexts are check. When a match is found, the nRef member of
  9804. ** the context containing the match is incremented.
  9805. **
  9806. ** Each subquery gets a new NameContext. The pNext field points to the
  9807. ** NameContext in the parent query. Thus the process of scanning the
  9808. ** NameContext list corresponds to searching through successively outer
  9809. ** subqueries looking for a match.
  9810. */
  9811. struct NameContext {
  9812. Parse *pParse; /* The parser */
  9813. SrcList *pSrcList; /* One or more tables used to resolve names */
  9814. ExprList *pEList; /* Optional list of named expressions */
  9815. int nRef; /* Number of names resolved by this context */
  9816. int nErr; /* Number of errors encountered while resolving names */
  9817. u8 allowAgg; /* Aggregate functions allowed here */
  9818. u8 hasAgg; /* True if aggregates are seen */
  9819. u8 isCheck; /* True if resolving names in a CHECK constraint */
  9820. int nDepth; /* Depth of subquery recursion. 1 for no recursion */
  9821. AggInfo *pAggInfo; /* Information about aggregates at this level */
  9822. NameContext *pNext; /* Next outer name context. NULL for outermost */
  9823. };
  9824. /*
  9825. ** An instance of the following structure contains all information
  9826. ** needed to generate code for a single SELECT statement.
  9827. **
  9828. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  9829. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  9830. ** limit and nOffset to the value of the offset (or 0 if there is not
  9831. ** offset). But later on, nLimit and nOffset become the memory locations
  9832. ** in the VDBE that record the limit and offset counters.
  9833. **
  9834. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  9835. ** These addresses must be stored so that we can go back and fill in
  9836. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  9837. ** the number of columns in P2 can be computed at the same time
  9838. ** as the OP_OpenEphm instruction is coded because not
  9839. ** enough information about the compound query is known at that point.
  9840. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  9841. ** for the result set. The KeyInfo for addrOpenTran[2] contains collating
  9842. ** sequences for the ORDER BY clause.
  9843. */
  9844. struct Select {
  9845. ExprList *pEList; /* The fields of the result */
  9846. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  9847. char affinity; /* MakeRecord with this affinity for SRT_Set */
  9848. u16 selFlags; /* Various SF_* values */
  9849. SrcList *pSrc; /* The FROM clause */
  9850. Expr *pWhere; /* The WHERE clause */
  9851. ExprList *pGroupBy; /* The GROUP BY clause */
  9852. Expr *pHaving; /* The HAVING clause */
  9853. ExprList *pOrderBy; /* The ORDER BY clause */
  9854. Select *pPrior; /* Prior select in a compound select statement */
  9855. Select *pNext; /* Next select to the left in a compound */
  9856. Select *pRightmost; /* Right-most select in a compound select statement */
  9857. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  9858. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  9859. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  9860. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  9861. };
  9862. /*
  9863. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  9864. ** "Select Flag".
  9865. */
  9866. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  9867. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  9868. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  9869. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  9870. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  9871. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  9872. /*
  9873. ** The results of a select can be distributed in several ways. The
  9874. ** "SRT" prefix means "SELECT Result Type".
  9875. */
  9876. #define SRT_Union 1 /* Store result as keys in an index */
  9877. #define SRT_Except 2 /* Remove result from a UNION index */
  9878. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  9879. #define SRT_Discard 4 /* Do not save the results anywhere */
  9880. /* The ORDER BY clause is ignored for all of the above */
  9881. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  9882. #define SRT_Output 5 /* Output each row of result */
  9883. #define SRT_Mem 6 /* Store result in a memory cell */
  9884. #define SRT_Set 7 /* Store results as keys in an index */
  9885. #define SRT_Table 8 /* Store result as data with an automatic rowid */
  9886. #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
  9887. #define SRT_Coroutine 10 /* Generate a single row of result */
  9888. /*
  9889. ** A structure used to customize the behavior of sqlite3Select(). See
  9890. ** comments above sqlite3Select() for details.
  9891. */
  9892. typedef struct SelectDest SelectDest;
  9893. struct SelectDest {
  9894. u8 eDest; /* How to dispose of the results */
  9895. u8 affinity; /* Affinity used when eDest==SRT_Set */
  9896. int iParm; /* A parameter used by the eDest disposal method */
  9897. int iMem; /* Base register where results are written */
  9898. int nMem; /* Number of registers allocated */
  9899. };
  9900. /*
  9901. ** An SQL parser context. A copy of this structure is passed through
  9902. ** the parser and down into all the parser action routine in order to
  9903. ** carry around information that is global to the entire parse.
  9904. **
  9905. ** The structure is divided into two parts. When the parser and code
  9906. ** generate call themselves recursively, the first part of the structure
  9907. ** is constant but the second part is reset at the beginning and end of
  9908. ** each recursion.
  9909. **
  9910. ** The nTableLock and aTableLock variables are only used if the shared-cache
  9911. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  9912. ** used to store the set of table-locks required by the statement being
  9913. ** compiled. Function sqlite3TableLock() is used to add entries to the
  9914. ** list.
  9915. */
  9916. struct Parse {
  9917. sqlite3 *db; /* The main database structure */
  9918. int rc; /* Return code from execution */
  9919. char *zErrMsg; /* An error message */
  9920. Vdbe *pVdbe; /* An engine for executing database bytecode */
  9921. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  9922. u8 nameClash; /* A permanent table name clashes with temp table name */
  9923. u8 checkSchema; /* Causes schema cookie check after an error */
  9924. u8 nested; /* Number of nested calls to the parser/code generator */
  9925. u8 parseError; /* True after a parsing error. Ticket #1794 */
  9926. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  9927. u8 nTempInUse; /* Number of aTempReg[] currently checked out */
  9928. int aTempReg[8]; /* Holding area for temporary registers */
  9929. int nRangeReg; /* Size of the temporary register block */
  9930. int iRangeReg; /* First register in temporary register block */
  9931. int nErr; /* Number of errors seen */
  9932. int nTab; /* Number of previously allocated VDBE cursors */
  9933. int nMem; /* Number of memory cells used so far */
  9934. int nSet; /* Number of sets used so far */
  9935. int ckBase; /* Base register of data during check constraints */
  9936. int disableColCache; /* True to disable adding to column cache */
  9937. int nColCache; /* Number of entries in the column cache */
  9938. int iColCache; /* Next entry of the cache to replace */
  9939. struct yColCache {
  9940. int iTable; /* Table cursor number */
  9941. int iColumn; /* Table column number */
  9942. char affChange; /* True if this register has had an affinity change */
  9943. int iReg; /* Register holding value of this column */
  9944. } aColCache[10]; /* One for each valid column cache entry */
  9945. u32 writeMask; /* Start a write transaction on these databases */
  9946. u32 cookieMask; /* Bitmask of schema verified databases */
  9947. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  9948. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  9949. #ifndef SQLITE_OMIT_SHARED_CACHE
  9950. int nTableLock; /* Number of locks in aTableLock */
  9951. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  9952. #endif
  9953. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  9954. int regRoot; /* Register holding root page number for new objects */
  9955. /* Above is constant between recursions. Below is reset before and after
  9956. ** each recursion */
  9957. int nVar; /* Number of '?' variables seen in the SQL so far */
  9958. int nVarExpr; /* Number of used slots in apVarExpr[] */
  9959. int nVarExprAlloc; /* Number of allocated slots in apVarExpr[] */
  9960. Expr **apVarExpr; /* Pointers to :aaa and $aaaa wildcard expressions */
  9961. int nAlias; /* Number of aliased result set columns */
  9962. int nAliasAlloc; /* Number of allocated slots for aAlias[] */
  9963. int *aAlias; /* Register used to hold aliased result */
  9964. u8 explain; /* True if the EXPLAIN flag is found on the query */
  9965. Token sErrToken; /* The token at which the error occurred */
  9966. Token sNameToken; /* Token with unqualified schema object name */
  9967. Token sLastToken; /* The last token parsed */
  9968. const char *zSql; /* All SQL text */
  9969. const char *zTail; /* All SQL text past the last semicolon parsed */
  9970. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  9971. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  9972. TriggerStack *trigStack; /* Trigger actions being coded */
  9973. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  9974. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9975. Token sArg; /* Complete text of a module argument */
  9976. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  9977. int nVtabLock; /* Number of virtual tables to lock */
  9978. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  9979. #endif
  9980. int nHeight; /* Expression tree height of current sub-select */
  9981. Table *pZombieTab; /* List of Table objects to delete after code gen */
  9982. };
  9983. #ifdef SQLITE_OMIT_VIRTUALTABLE
  9984. #define IN_DECLARE_VTAB 0
  9985. #else
  9986. #define IN_DECLARE_VTAB (pParse->declareVtab)
  9987. #endif
  9988. /*
  9989. ** An instance of the following structure can be declared on a stack and used
  9990. ** to save the Parse.zAuthContext value so that it can be restored later.
  9991. */
  9992. struct AuthContext {
  9993. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  9994. Parse *pParse; /* The Parse structure */
  9995. };
  9996. /*
  9997. ** Bitfield flags for P2 value in OP_Insert and OP_Delete
  9998. */
  9999. #define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
  10000. #define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
  10001. #define OPFLAG_ISUPDATE 4 /* This OP_Insert is an sql UPDATE */
  10002. #define OPFLAG_APPEND 8 /* This is likely to be an append */
  10003. /*
  10004. * Each trigger present in the database schema is stored as an instance of
  10005. * struct Trigger.
  10006. *
  10007. * Pointers to instances of struct Trigger are stored in two ways.
  10008. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  10009. * database). This allows Trigger structures to be retrieved by name.
  10010. * 2. All triggers associated with a single table form a linked list, using the
  10011. * pNext member of struct Trigger. A pointer to the first element of the
  10012. * linked list is stored as the "pTrigger" member of the associated
  10013. * struct Table.
  10014. *
  10015. * The "step_list" member points to the first element of a linked list
  10016. * containing the SQL statements specified as the trigger program.
  10017. */
  10018. struct Trigger {
  10019. char *name; /* The name of the trigger */
  10020. char *table; /* The table or view to which the trigger applies */
  10021. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  10022. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  10023. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  10024. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  10025. the <column-list> is stored here */
  10026. Token nameToken; /* Token containing zName. Use during parsing only */
  10027. Schema *pSchema; /* Schema containing the trigger */
  10028. Schema *pTabSchema; /* Schema containing the table */
  10029. TriggerStep *step_list; /* Link list of trigger program steps */
  10030. Trigger *pNext; /* Next trigger associated with the table */
  10031. };
  10032. /*
  10033. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  10034. ** determine which.
  10035. **
  10036. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  10037. ** In that cases, the constants below can be ORed together.
  10038. */
  10039. #define TRIGGER_BEFORE 1
  10040. #define TRIGGER_AFTER 2
  10041. /*
  10042. * An instance of struct TriggerStep is used to store a single SQL statement
  10043. * that is a part of a trigger-program.
  10044. *
  10045. * Instances of struct TriggerStep are stored in a singly linked list (linked
  10046. * using the "pNext" member) referenced by the "step_list" member of the
  10047. * associated struct Trigger instance. The first element of the linked list is
  10048. * the first step of the trigger-program.
  10049. *
  10050. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  10051. * "SELECT" statement. The meanings of the other members is determined by the
  10052. * value of "op" as follows:
  10053. *
  10054. * (op == TK_INSERT)
  10055. * orconf -> stores the ON CONFLICT algorithm
  10056. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  10057. * this stores a pointer to the SELECT statement. Otherwise NULL.
  10058. * target -> A token holding the name of the table to insert into.
  10059. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  10060. * this stores values to be inserted. Otherwise NULL.
  10061. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  10062. * statement, then this stores the column-names to be
  10063. * inserted into.
  10064. *
  10065. * (op == TK_DELETE)
  10066. * target -> A token holding the name of the table to delete from.
  10067. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  10068. * Otherwise NULL.
  10069. *
  10070. * (op == TK_UPDATE)
  10071. * target -> A token holding the name of the table to update rows of.
  10072. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  10073. * Otherwise NULL.
  10074. * pExprList -> A list of the columns to update and the expressions to update
  10075. * them to. See sqlite3Update() documentation of "pChanges"
  10076. * argument.
  10077. *
  10078. */
  10079. struct TriggerStep {
  10080. int op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  10081. int orconf; /* OE_Rollback etc. */
  10082. Trigger *pTrig; /* The trigger that this step is a part of */
  10083. Select *pSelect; /* Valid for SELECT and sometimes
  10084. INSERT steps (when pExprList == 0) */
  10085. Token target; /* Valid for DELETE, UPDATE, INSERT steps */
  10086. Expr *pWhere; /* Valid for DELETE, UPDATE steps */
  10087. ExprList *pExprList; /* Valid for UPDATE statements and sometimes
  10088. INSERT steps (when pSelect == 0) */
  10089. IdList *pIdList; /* Valid for INSERT statements only */
  10090. TriggerStep *pNext; /* Next in the link-list */
  10091. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  10092. };
  10093. /*
  10094. * An instance of struct TriggerStack stores information required during code
  10095. * generation of a single trigger program. While the trigger program is being
  10096. * coded, its associated TriggerStack instance is pointed to by the
  10097. * "pTriggerStack" member of the Parse structure.
  10098. *
  10099. * The pTab member points to the table that triggers are being coded on. The
  10100. * newIdx member contains the index of the vdbe cursor that points at the temp
  10101. * table that stores the new.* references. If new.* references are not valid
  10102. * for the trigger being coded (for example an ON DELETE trigger), then newIdx
  10103. * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
  10104. *
  10105. * The ON CONFLICT policy to be used for the trigger program steps is stored
  10106. * as the orconf member. If this is OE_Default, then the ON CONFLICT clause
  10107. * specified for individual triggers steps is used.
  10108. *
  10109. * struct TriggerStack has a "pNext" member, to allow linked lists to be
  10110. * constructed. When coding nested triggers (triggers fired by other triggers)
  10111. * each nested trigger stores its parent trigger's TriggerStack as the "pNext"
  10112. * pointer. Once the nested trigger has been coded, the pNext value is restored
  10113. * to the pTriggerStack member of the Parse stucture and coding of the parent
  10114. * trigger continues.
  10115. *
  10116. * Before a nested trigger is coded, the linked list pointed to by the
  10117. * pTriggerStack is scanned to ensure that the trigger is not about to be coded
  10118. * recursively. If this condition is detected, the nested trigger is not coded.
  10119. */
  10120. struct TriggerStack {
  10121. Table *pTab; /* Table that triggers are currently being coded on */
  10122. int newIdx; /* Index of vdbe cursor to "new" temp table */
  10123. int oldIdx; /* Index of vdbe cursor to "old" temp table */
  10124. u32 newColMask;
  10125. u32 oldColMask;
  10126. int orconf; /* Current orconf policy */
  10127. int ignoreJump; /* where to jump to for a RAISE(IGNORE) */
  10128. Trigger *pTrigger; /* The trigger currently being coded */
  10129. TriggerStack *pNext; /* Next trigger down on the trigger stack */
  10130. };
  10131. /*
  10132. ** The following structure contains information used by the sqliteFix...
  10133. ** routines as they walk the parse tree to make database references
  10134. ** explicit.
  10135. */
  10136. typedef struct DbFixer DbFixer;
  10137. struct DbFixer {
  10138. Parse *pParse; /* The parsing context. Error messages written here */
  10139. const char *zDb; /* Make sure all objects are contained in this database */
  10140. const char *zType; /* Type of the container - used for error messages */
  10141. const Token *pName; /* Name of the container - used for error messages */
  10142. };
  10143. /*
  10144. ** An objected used to accumulate the text of a string where we
  10145. ** do not necessarily know how big the string will be in the end.
  10146. */
  10147. struct StrAccum {
  10148. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  10149. char *zBase; /* A base allocation. Not from malloc. */
  10150. char *zText; /* The string collected so far */
  10151. int nChar; /* Length of the string so far */
  10152. int nAlloc; /* Amount of space allocated in zText */
  10153. int mxAlloc; /* Maximum allowed string length */
  10154. u8 mallocFailed; /* Becomes true if any memory allocation fails */
  10155. u8 useMalloc; /* True if zText is enlargeable using realloc */
  10156. u8 tooBig; /* Becomes true if string size exceeds limits */
  10157. };
  10158. /*
  10159. ** A pointer to this structure is used to communicate information
  10160. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  10161. */
  10162. typedef struct {
  10163. sqlite3 *db; /* The database being initialized */
  10164. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  10165. char **pzErrMsg; /* Error message stored here */
  10166. int rc; /* Result code stored here */
  10167. } InitData;
  10168. /*
  10169. ** Structure containing global configuration data for the SQLite library.
  10170. **
  10171. ** This structure also contains some state information.
  10172. */
  10173. struct Sqlite3Config {
  10174. int bMemstat; /* True to enable memory status */
  10175. int bCoreMutex; /* True to enable core mutexing */
  10176. int bFullMutex; /* True to enable full mutexing */
  10177. int mxStrlen; /* Maximum string length */
  10178. int szLookaside; /* Default lookaside buffer size */
  10179. int nLookaside; /* Default lookaside buffer count */
  10180. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  10181. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  10182. sqlite3_pcache_methods pcache; /* Low-level page-cache interface */
  10183. void *pHeap; /* Heap storage space */
  10184. int nHeap; /* Size of pHeap[] */
  10185. int mnReq, mxReq; /* Min and max heap requests sizes */
  10186. void *pScratch; /* Scratch memory */
  10187. int szScratch; /* Size of each scratch buffer */
  10188. int nScratch; /* Number of scratch buffers */
  10189. void *pPage; /* Page cache memory */
  10190. int szPage; /* Size of each page in pPage[] */
  10191. int nPage; /* Number of pages in pPage[] */
  10192. int mxParserStack; /* maximum depth of the parser stack */
  10193. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  10194. /* The above might be initialized to non-zero. The following need to always
  10195. ** initially be zero, however. */
  10196. int isInit; /* True after initialization has finished */
  10197. int inProgress; /* True while initialization in progress */
  10198. int isMallocInit; /* True after malloc is initialized */
  10199. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  10200. int nRefInitMutex; /* Number of users of pInitMutex */
  10201. };
  10202. /*
  10203. ** Context pointer passed down through the tree-walk.
  10204. */
  10205. struct Walker {
  10206. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  10207. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  10208. Parse *pParse; /* Parser context. */
  10209. union { /* Extra data for callback */
  10210. NameContext *pNC; /* Naming context */
  10211. int i; /* Integer value */
  10212. } u;
  10213. };
  10214. /* Forward declarations */
  10215. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  10216. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  10217. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  10218. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  10219. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  10220. /*
  10221. ** Return code from the parse-tree walking primitives and their
  10222. ** callbacks.
  10223. */
  10224. #define WRC_Continue 0 /* Continue down into children */
  10225. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  10226. #define WRC_Abort 2 /* Abandon the tree walk */
  10227. /*
  10228. ** Assuming zIn points to the first byte of a UTF-8 character,
  10229. ** advance zIn to point to the first byte of the next UTF-8 character.
  10230. */
  10231. #define SQLITE_SKIP_UTF8(zIn) { \
  10232. if( (*(zIn++))>=0xc0 ){ \
  10233. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  10234. } \
  10235. }
  10236. /*
  10237. ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
  10238. ** builds) or a function call (for debugging). If it is a function call,
  10239. ** it allows the operator to set a breakpoint at the spot where database
  10240. ** corruption is first detected.
  10241. */
  10242. #ifdef SQLITE_DEBUG
  10243. SQLITE_PRIVATE int sqlite3Corrupt(void);
  10244. # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
  10245. #else
  10246. # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
  10247. #endif
  10248. /*
  10249. ** Internal function prototypes
  10250. */
  10251. SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
  10252. SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
  10253. SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
  10254. SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);
  10255. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  10256. SQLITE_PRIVATE int sqlite3MallocInit(void);
  10257. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  10258. SQLITE_PRIVATE void *sqlite3Malloc(int);
  10259. SQLITE_PRIVATE void *sqlite3MallocZero(int);
  10260. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
  10261. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
  10262. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  10263. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  10264. SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
  10265. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  10266. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
  10267. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  10268. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  10269. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  10270. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  10271. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  10272. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  10273. SQLITE_PRIVATE void sqlite3PageFree(void*);
  10274. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  10275. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  10276. SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
  10277. #ifdef SQLITE_ENABLE_MEMSYS3
  10278. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  10279. #endif
  10280. #ifdef SQLITE_ENABLE_MEMSYS5
  10281. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  10282. #endif
  10283. #ifndef SQLITE_MUTEX_OMIT
  10284. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void);
  10285. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  10286. SQLITE_PRIVATE int sqlite3MutexInit(void);
  10287. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  10288. #endif
  10289. SQLITE_PRIVATE int sqlite3StatusValue(int);
  10290. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  10291. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  10292. SQLITE_PRIVATE int sqlite3IsNaN(double);
  10293. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  10294. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  10295. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  10296. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  10297. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  10298. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  10299. #endif
  10300. #if defined(SQLITE_TEST)
  10301. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  10302. #endif
  10303. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  10304. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  10305. SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
  10306. SQLITE_PRIVATE void sqlite3Dequote(char*);
  10307. SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3*, Expr*);
  10308. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  10309. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  10310. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  10311. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  10312. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  10313. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  10314. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  10315. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
  10316. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  10317. SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
  10318. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  10319. SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
  10320. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  10321. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  10322. SQLITE_PRIVATE void sqlite3ExprClear(sqlite3*, Expr*);
  10323. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  10324. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
  10325. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  10326. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  10327. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  10328. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  10329. SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
  10330. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  10331. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  10332. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  10333. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  10334. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  10335. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  10336. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  10337. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  10338. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  10339. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  10340. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
  10341. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  10342. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  10343. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  10344. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  10345. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  10346. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
  10347. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  10348. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  10349. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  10350. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  10351. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  10352. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  10353. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  10354. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  10355. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  10356. #else
  10357. # define sqlite3ViewGetColumnNames(A,B) 0
  10358. #endif
  10359. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  10360. SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
  10361. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  10362. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
  10363. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  10364. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  10365. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  10366. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  10367. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  10368. Token*, Select*, Expr*, IdList*);
  10369. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  10370. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  10371. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  10372. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  10373. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  10374. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  10375. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  10376. Token*, int, int);
  10377. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  10378. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  10379. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  10380. Expr*,ExprList*,int,Expr*,Expr*);
  10381. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  10382. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  10383. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  10384. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  10385. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  10386. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
  10387. #endif
  10388. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  10389. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  10390. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8, int);
  10391. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  10392. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
  10393. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  10394. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
  10395. SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse*, int);
  10396. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  10397. SQLITE_PRIVATE void sqlite3ExprWritableRegister(Parse*,int);
  10398. SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
  10399. SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
  10400. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  10401. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  10402. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  10403. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
  10404. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  10405. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  10406. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  10407. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  10408. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  10409. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  10410. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  10411. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  10412. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  10413. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  10414. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  10415. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
  10416. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  10417. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  10418. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  10419. SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*);
  10420. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  10421. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  10422. SQLITE_PRIVATE void sqlite3PrngResetState(void);
  10423. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
  10424. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  10425. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  10426. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  10427. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  10428. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  10429. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  10430. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  10431. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  10432. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
  10433. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  10434. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  10435. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
  10436. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  10437. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
  10438. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  10439. int*,int,int,int,int);
  10440. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  10441. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  10442. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  10443. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*);
  10444. SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*, Token*);
  10445. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
  10446. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
  10447. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  10448. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*);
  10449. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  10450. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
  10451. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  10452. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  10453. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  10454. #ifdef SQLITE_DEBUG
  10455. SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3*);
  10456. SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3*);
  10457. #else
  10458. # define sqlite3SafetyOn(A) 0
  10459. # define sqlite3SafetyOff(A) 0
  10460. #endif
  10461. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  10462. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  10463. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  10464. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  10465. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  10466. #endif
  10467. #ifndef SQLITE_OMIT_TRIGGER
  10468. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  10469. Expr*,int, int);
  10470. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  10471. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  10472. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  10473. SQLITE_PRIVATE int sqlite3TriggersExist(Table*, int, ExprList*);
  10474. SQLITE_PRIVATE int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int,
  10475. int, int, u32*, u32*);
  10476. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  10477. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  10478. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  10479. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  10480. ExprList*,Select*,int);
  10481. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
  10482. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  10483. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  10484. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  10485. #else
  10486. # define sqlite3TriggersExist(B,C,D,E,F) 0
  10487. # define sqlite3DeleteTrigger(A,B)
  10488. # define sqlite3DropTriggerPtr(A,B)
  10489. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  10490. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0
  10491. #endif
  10492. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  10493. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  10494. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  10495. #ifndef SQLITE_OMIT_AUTHORIZATION
  10496. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  10497. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  10498. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  10499. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  10500. #else
  10501. # define sqlite3AuthRead(a,b,c,d)
  10502. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  10503. # define sqlite3AuthContextPush(a,b,c)
  10504. # define sqlite3AuthContextPop(a) ((void)(a))
  10505. #endif
  10506. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  10507. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  10508. SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
  10509. int omitJournal, int nCache, int flags, Btree **ppBtree);
  10510. SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  10511. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  10512. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  10513. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  10514. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  10515. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  10516. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
  10517. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  10518. SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
  10519. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  10520. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  10521. SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8*, const u8**);
  10522. /*
  10523. ** Routines to read and write variable-length integers. These used to
  10524. ** be defined locally, but now we use the varint routines in the util.c
  10525. ** file. Code should use the MACRO forms below, as the Varint32 versions
  10526. ** are coded to assume the single byte case is already handled (which
  10527. ** the MACRO form does).
  10528. */
  10529. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  10530. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
  10531. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  10532. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  10533. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  10534. /*
  10535. ** The header of a record consists of a sequence variable-length integers.
  10536. ** These integers are almost always small and are encoded as a single byte.
  10537. ** The following macros take advantage this fact to provide a fast encode
  10538. ** and decode of the integers in a record header. It is faster for the common
  10539. ** case where the integer is a single byte. It is a little slower when the
  10540. ** integer is two or more bytes. But overall it is faster.
  10541. **
  10542. ** The following expressions are equivalent:
  10543. **
  10544. ** x = sqlite3GetVarint32( A, &B );
  10545. ** x = sqlite3PutVarint32( A, B );
  10546. **
  10547. ** x = getVarint32( A, B );
  10548. ** x = putVarint32( A, B );
  10549. **
  10550. */
  10551. #define getVarint32(A,B) (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
  10552. #define putVarint32(A,B) (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
  10553. #define getVarint sqlite3GetVarint
  10554. #define putVarint sqlite3PutVarint
  10555. SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
  10556. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
  10557. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  10558. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  10559. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  10560. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
  10561. SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
  10562. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  10563. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  10564. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  10565. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  10566. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
  10567. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
  10568. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  10569. SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
  10570. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  10571. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  10572. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  10573. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  10574. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  10575. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  10576. void(*)(void*));
  10577. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  10578. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  10579. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
  10580. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  10581. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  10582. #ifndef SQLITE_AMALGAMATION
  10583. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  10584. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  10585. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  10586. #endif
  10587. SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
  10588. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  10589. SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
  10590. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  10591. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  10592. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  10593. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  10594. SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *, int, int);
  10595. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  10596. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  10597. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  10598. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  10599. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
  10600. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  10601. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  10602. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
  10603. SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
  10604. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  10605. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  10606. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  10607. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  10608. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  10609. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  10610. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  10611. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  10612. SQLITE_PRIVATE void sqlite3SchemaFree(void *);
  10613. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  10614. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  10615. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  10616. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  10617. void (*)(sqlite3_context*,int,sqlite3_value **),
  10618. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
  10619. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  10620. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  10621. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  10622. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  10623. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  10624. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  10625. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  10626. /*
  10627. ** The interface to the LEMON-generated parser
  10628. */
  10629. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
  10630. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  10631. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  10632. #ifdef YYTRACKMAXSTACKDEPTH
  10633. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  10634. #endif
  10635. SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3*);
  10636. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  10637. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  10638. #else
  10639. # define sqlite3CloseExtensions(X)
  10640. #endif
  10641. #ifndef SQLITE_OMIT_SHARED_CACHE
  10642. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  10643. #else
  10644. #define sqlite3TableLock(v,w,x,y,z)
  10645. #endif
  10646. #ifdef SQLITE_TEST
  10647. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  10648. #endif
  10649. #ifdef SQLITE_OMIT_VIRTUALTABLE
  10650. # define sqlite3VtabClear(X)
  10651. # define sqlite3VtabSync(X,Y) SQLITE_OK
  10652. # define sqlite3VtabRollback(X)
  10653. # define sqlite3VtabCommit(X)
  10654. # define sqlite3VtabInSync(db) 0
  10655. #else
  10656. SQLITE_PRIVATE void sqlite3VtabClear(Table*);
  10657. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **);
  10658. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  10659. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  10660. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  10661. #endif
  10662. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  10663. SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
  10664. SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
  10665. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
  10666. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  10667. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  10668. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  10669. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  10670. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  10671. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  10672. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
  10673. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  10674. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  10675. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  10676. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  10677. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  10678. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  10679. /*
  10680. ** Available fault injectors. Should be numbered beginning with 0.
  10681. */
  10682. #define SQLITE_FAULTINJECTOR_MALLOC 0
  10683. #define SQLITE_FAULTINJECTOR_COUNT 1
  10684. /*
  10685. ** The interface to the code in fault.c used for identifying "benign"
  10686. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  10687. ** is not defined.
  10688. */
  10689. #ifndef SQLITE_OMIT_BUILTIN_TEST
  10690. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  10691. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  10692. #else
  10693. #define sqlite3BeginBenignMalloc()
  10694. #define sqlite3EndBenignMalloc()
  10695. #endif
  10696. #define IN_INDEX_ROWID 1
  10697. #define IN_INDEX_EPH 2
  10698. #define IN_INDEX_INDEX 3
  10699. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
  10700. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  10701. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  10702. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  10703. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  10704. #else
  10705. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  10706. #endif
  10707. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  10708. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  10709. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  10710. #if SQLITE_MAX_EXPR_DEPTH>0
  10711. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  10712. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  10713. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  10714. #else
  10715. #define sqlite3ExprSetHeight(x,y)
  10716. #define sqlite3SelectExprHeight(x) 0
  10717. #define sqlite3ExprCheckHeight(x,y)
  10718. #endif
  10719. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  10720. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  10721. #ifdef SQLITE_SSE
  10722. #include "sseInt.h"
  10723. #endif
  10724. #ifdef SQLITE_DEBUG
  10725. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  10726. #endif
  10727. /*
  10728. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  10729. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  10730. ** print I/O tracing messages.
  10731. */
  10732. #ifdef SQLITE_ENABLE_IOTRACE
  10733. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  10734. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  10735. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  10736. #else
  10737. # define IOTRACE(A)
  10738. # define sqlite3VdbeIOTraceSql(X)
  10739. #endif
  10740. #endif
  10741. /************** End of sqliteInt.h *******************************************/
  10742. /************** Begin file global.c ******************************************/
  10743. /*
  10744. ** 2008 June 13
  10745. **
  10746. ** The author disclaims copyright to this source code. In place of
  10747. ** a legal notice, here is a blessing:
  10748. **
  10749. ** May you do good and not evil.
  10750. ** May you find forgiveness for yourself and forgive others.
  10751. ** May you share freely, never taking more than you give.
  10752. **
  10753. *************************************************************************
  10754. **
  10755. ** This file contains definitions of global variables and contants.
  10756. **
  10757. ** $Id: global.c,v 1.9 2008/12/08 18:19:18 drh Exp $
  10758. */
  10759. /* An array to map all upper-case characters into their corresponding
  10760. ** lower-case character.
  10761. **
  10762. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  10763. ** handle case conversions for the UTF character set since the tables
  10764. ** involved are nearly as big or bigger than SQLite itself.
  10765. */
  10766. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  10767. #ifdef SQLITE_ASCII
  10768. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  10769. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  10770. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  10771. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  10772. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  10773. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  10774. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  10775. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  10776. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  10777. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  10778. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  10779. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  10780. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  10781. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  10782. 252,253,254,255
  10783. #endif
  10784. #ifdef SQLITE_EBCDIC
  10785. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  10786. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  10787. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  10788. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  10789. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  10790. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  10791. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  10792. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  10793. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  10794. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  10795. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  10796. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  10797. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  10798. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  10799. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  10800. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  10801. #endif
  10802. };
  10803. /*
  10804. ** The following singleton contains the global configuration for
  10805. ** the SQLite library.
  10806. */
  10807. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  10808. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  10809. 1, /* bCoreMutex */
  10810. SQLITE_THREADSAFE==1, /* bFullMutex */
  10811. 0x7ffffffe, /* mxStrlen */
  10812. 100, /* szLookaside */
  10813. 500, /* nLookaside */
  10814. {0,0,0,0,0,0,0,0}, /* m */
  10815. {0,0,0,0,0,0,0,0,0}, /* mutex */
  10816. {0,0,0,0,0,0,0,0,0,0,0}, /* pcache */
  10817. (void*)0, /* pHeap */
  10818. 0, /* nHeap */
  10819. 0, 0, /* mnHeap, mxHeap */
  10820. (void*)0, /* pScratch */
  10821. 0, /* szScratch */
  10822. 0, /* nScratch */
  10823. (void*)0, /* pPage */
  10824. 0, /* szPage */
  10825. 0, /* nPage */
  10826. 0, /* mxParserStack */
  10827. 0, /* sharedCacheEnabled */
  10828. /* All the rest need to always be zero */
  10829. 0, /* isInit */
  10830. 0, /* inProgress */
  10831. 0, /* isMallocInit */
  10832. 0, /* pInitMutex */
  10833. 0, /* nRefInitMutex */
  10834. };
  10835. /*
  10836. ** Hash table for global functions - functions common to all
  10837. ** database connections. After initialization, this table is
  10838. ** read-only.
  10839. */
  10840. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  10841. /************** End of global.c **********************************************/
  10842. /************** Begin file status.c ******************************************/
  10843. /*
  10844. ** 2008 June 18
  10845. **
  10846. ** The author disclaims copyright to this source code. In place of
  10847. ** a legal notice, here is a blessing:
  10848. **
  10849. ** May you do good and not evil.
  10850. ** May you find forgiveness for yourself and forgive others.
  10851. ** May you share freely, never taking more than you give.
  10852. **
  10853. *************************************************************************
  10854. **
  10855. ** This module implements the sqlite3_status() interface and related
  10856. ** functionality.
  10857. **
  10858. ** $Id: status.c,v 1.9 2008/09/02 00:52:52 drh Exp $
  10859. */
  10860. /*
  10861. ** Variables in which to record status information.
  10862. */
  10863. typedef struct sqlite3StatType sqlite3StatType;
  10864. static SQLITE_WSD struct sqlite3StatType {
  10865. int nowValue[9]; /* Current value */
  10866. int mxValue[9]; /* Maximum value */
  10867. } sqlite3Stat = { {0,}, {0,} };
  10868. /* The "wsdStat" macro will resolve to the status information
  10869. ** state vector. If writable static data is unsupported on the target,
  10870. ** we have to locate the state vector at run-time. In the more common
  10871. ** case where writable static data is supported, wsdStat can refer directly
  10872. ** to the "sqlite3Stat" state vector declared above.
  10873. */
  10874. #ifdef SQLITE_OMIT_WSD
  10875. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  10876. # define wsdStat x[0]
  10877. #else
  10878. # define wsdStatInit
  10879. # define wsdStat sqlite3Stat
  10880. #endif
  10881. /*
  10882. ** Return the current value of a status parameter.
  10883. */
  10884. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  10885. wsdStatInit;
  10886. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  10887. return wsdStat.nowValue[op];
  10888. }
  10889. /*
  10890. ** Add N to the value of a status record. It is assumed that the
  10891. ** caller holds appropriate locks.
  10892. */
  10893. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  10894. wsdStatInit;
  10895. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  10896. wsdStat.nowValue[op] += N;
  10897. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  10898. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  10899. }
  10900. }
  10901. /*
  10902. ** Set the value of a status to X.
  10903. */
  10904. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  10905. wsdStatInit;
  10906. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  10907. wsdStat.nowValue[op] = X;
  10908. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  10909. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  10910. }
  10911. }
  10912. /*
  10913. ** Query status information.
  10914. **
  10915. ** This implementation assumes that reading or writing an aligned
  10916. ** 32-bit integer is an atomic operation. If that assumption is not true,
  10917. ** then this routine is not threadsafe.
  10918. */
  10919. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  10920. wsdStatInit;
  10921. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  10922. return SQLITE_MISUSE;
  10923. }
  10924. *pCurrent = wsdStat.nowValue[op];
  10925. *pHighwater = wsdStat.mxValue[op];
  10926. if( resetFlag ){
  10927. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  10928. }
  10929. return SQLITE_OK;
  10930. }
  10931. /*
  10932. ** Query status information for a single database connection
  10933. */
  10934. SQLITE_API int sqlite3_db_status(
  10935. sqlite3 *db, /* The database connection whose status is desired */
  10936. int op, /* Status verb */
  10937. int *pCurrent, /* Write current value here */
  10938. int *pHighwater, /* Write high-water mark here */
  10939. int resetFlag /* Reset high-water mark if true */
  10940. ){
  10941. switch( op ){
  10942. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  10943. *pCurrent = db->lookaside.nOut;
  10944. *pHighwater = db->lookaside.mxOut;
  10945. if( resetFlag ){
  10946. db->lookaside.mxOut = db->lookaside.nOut;
  10947. }
  10948. break;
  10949. }
  10950. default: {
  10951. return SQLITE_ERROR;
  10952. }
  10953. }
  10954. return SQLITE_OK;
  10955. }
  10956. /************** End of status.c **********************************************/
  10957. /************** Begin file date.c ********************************************/
  10958. /*
  10959. ** 2003 October 31
  10960. **
  10961. ** The author disclaims copyright to this source code. In place of
  10962. ** a legal notice, here is a blessing:
  10963. **
  10964. ** May you do good and not evil.
  10965. ** May you find forgiveness for yourself and forgive others.
  10966. ** May you share freely, never taking more than you give.
  10967. **
  10968. *************************************************************************
  10969. ** This file contains the C functions that implement date and time
  10970. ** functions for SQLite.
  10971. **
  10972. ** There is only one exported symbol in this file - the function
  10973. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  10974. ** All other code has file scope.
  10975. **
  10976. ** $Id: date.c,v 1.99 2008/12/20 13:18:50 drh Exp $
  10977. **
  10978. ** SQLite processes all times and dates as Julian Day numbers. The
  10979. ** dates and times are stored as the number of days since noon
  10980. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  10981. ** calendar system.
  10982. **
  10983. ** 1970-01-01 00:00:00 is JD 2440587.5
  10984. ** 2000-01-01 00:00:00 is JD 2451544.5
  10985. **
  10986. ** This implemention requires years to be expressed as a 4-digit number
  10987. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  10988. ** be represented, even though julian day numbers allow a much wider
  10989. ** range of dates.
  10990. **
  10991. ** The Gregorian calendar system is used for all dates and times,
  10992. ** even those that predate the Gregorian calendar. Historians usually
  10993. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  10994. ** dates afterwards, depending on locale. Beware of this difference.
  10995. **
  10996. ** The conversion algorithms are implemented based on descriptions
  10997. ** in the following text:
  10998. **
  10999. ** Jean Meeus
  11000. ** Astronomical Algorithms, 2nd Edition, 1998
  11001. ** ISBM 0-943396-61-1
  11002. ** Willmann-Bell, Inc
  11003. ** Richmond, Virginia (USA)
  11004. */
  11005. #include <ctype.h>
  11006. #include <time.h>
  11007. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  11008. /*
  11009. ** On recent Windows platforms, the localtime_s() function is available
  11010. ** as part of the "Secure CRT". It is essentially equivalent to
  11011. ** localtime_r() available under most POSIX platforms, except that the
  11012. ** order of the parameters is reversed.
  11013. **
  11014. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  11015. **
  11016. ** If the user has not indicated to use localtime_r() or localtime_s()
  11017. ** already, check for an MSVC build environment that provides
  11018. ** localtime_s().
  11019. */
  11020. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  11021. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  11022. #define HAVE_LOCALTIME_S 1
  11023. #endif
  11024. /*
  11025. ** A structure for holding a single date and time.
  11026. */
  11027. typedef struct DateTime DateTime;
  11028. struct DateTime {
  11029. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  11030. int Y, M, D; /* Year, month, and day */
  11031. int h, m; /* Hour and minutes */
  11032. int tz; /* Timezone offset in minutes */
  11033. double s; /* Seconds */
  11034. char validYMD; /* True (1) if Y,M,D are valid */
  11035. char validHMS; /* True (1) if h,m,s are valid */
  11036. char validJD; /* True (1) if iJD is valid */
  11037. char validTZ; /* True (1) if tz is valid */
  11038. };
  11039. /*
  11040. ** Convert zDate into one or more integers. Additional arguments
  11041. ** come in groups of 5 as follows:
  11042. **
  11043. ** N number of digits in the integer
  11044. ** min minimum allowed value of the integer
  11045. ** max maximum allowed value of the integer
  11046. ** nextC first character after the integer
  11047. ** pVal where to write the integers value.
  11048. **
  11049. ** Conversions continue until one with nextC==0 is encountered.
  11050. ** The function returns the number of successful conversions.
  11051. */
  11052. static int getDigits(const char *zDate, ...){
  11053. va_list ap;
  11054. int val;
  11055. int N;
  11056. int min;
  11057. int max;
  11058. int nextC;
  11059. int *pVal;
  11060. int cnt = 0;
  11061. va_start(ap, zDate);
  11062. do{
  11063. N = va_arg(ap, int);
  11064. min = va_arg(ap, int);
  11065. max = va_arg(ap, int);
  11066. nextC = va_arg(ap, int);
  11067. pVal = va_arg(ap, int*);
  11068. val = 0;
  11069. while( N-- ){
  11070. if( !isdigit(*(u8*)zDate) ){
  11071. goto end_getDigits;
  11072. }
  11073. val = val*10 + *zDate - '0';
  11074. zDate++;
  11075. }
  11076. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  11077. goto end_getDigits;
  11078. }
  11079. *pVal = val;
  11080. zDate++;
  11081. cnt++;
  11082. }while( nextC );
  11083. end_getDigits:
  11084. va_end(ap);
  11085. return cnt;
  11086. }
  11087. /*
  11088. ** Read text from z[] and convert into a floating point number. Return
  11089. ** the number of digits converted.
  11090. */
  11091. #define getValue sqlite3AtoF
  11092. /*
  11093. ** Parse a timezone extension on the end of a date-time.
  11094. ** The extension is of the form:
  11095. **
  11096. ** (+/-)HH:MM
  11097. **
  11098. ** Or the "zulu" notation:
  11099. **
  11100. ** Z
  11101. **
  11102. ** If the parse is successful, write the number of minutes
  11103. ** of change in p->tz and return 0. If a parser error occurs,
  11104. ** return non-zero.
  11105. **
  11106. ** A missing specifier is not considered an error.
  11107. */
  11108. static int parseTimezone(const char *zDate, DateTime *p){
  11109. int sgn = 0;
  11110. int nHr, nMn;
  11111. int c;
  11112. while( isspace(*(u8*)zDate) ){ zDate++; }
  11113. p->tz = 0;
  11114. c = *zDate;
  11115. if( c=='-' ){
  11116. sgn = -1;
  11117. }else if( c=='+' ){
  11118. sgn = +1;
  11119. }else if( c=='Z' || c=='z' ){
  11120. zDate++;
  11121. goto zulu_time;
  11122. }else{
  11123. return c!=0;
  11124. }
  11125. zDate++;
  11126. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  11127. return 1;
  11128. }
  11129. zDate += 5;
  11130. p->tz = sgn*(nMn + nHr*60);
  11131. zulu_time:
  11132. while( isspace(*(u8*)zDate) ){ zDate++; }
  11133. return *zDate!=0;
  11134. }
  11135. /*
  11136. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  11137. ** The HH, MM, and SS must each be exactly 2 digits. The
  11138. ** fractional seconds FFFF can be one or more digits.
  11139. **
  11140. ** Return 1 if there is a parsing error and 0 on success.
  11141. */
  11142. static int parseHhMmSs(const char *zDate, DateTime *p){
  11143. int h, m, s;
  11144. double ms = 0.0;
  11145. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  11146. return 1;
  11147. }
  11148. zDate += 5;
  11149. if( *zDate==':' ){
  11150. zDate++;
  11151. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  11152. return 1;
  11153. }
  11154. zDate += 2;
  11155. if( *zDate=='.' && isdigit((u8)zDate[1]) ){
  11156. double rScale = 1.0;
  11157. zDate++;
  11158. while( isdigit(*(u8*)zDate) ){
  11159. ms = ms*10.0 + *zDate - '0';
  11160. rScale *= 10.0;
  11161. zDate++;
  11162. }
  11163. ms /= rScale;
  11164. }
  11165. }else{
  11166. s = 0;
  11167. }
  11168. p->validJD = 0;
  11169. p->validHMS = 1;
  11170. p->h = h;
  11171. p->m = m;
  11172. p->s = s + ms;
  11173. if( parseTimezone(zDate, p) ) return 1;
  11174. p->validTZ = (p->tz!=0)?1:0;
  11175. return 0;
  11176. }
  11177. /*
  11178. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  11179. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  11180. **
  11181. ** Reference: Meeus page 61
  11182. */
  11183. static void computeJD(DateTime *p){
  11184. int Y, M, D, A, B, X1, X2;
  11185. if( p->validJD ) return;
  11186. if( p->validYMD ){
  11187. Y = p->Y;
  11188. M = p->M;
  11189. D = p->D;
  11190. }else{
  11191. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  11192. M = 1;
  11193. D = 1;
  11194. }
  11195. if( M<=2 ){
  11196. Y--;
  11197. M += 12;
  11198. }
  11199. A = Y/100;
  11200. B = 2 - A + (A/4);
  11201. X1 = 36525*(Y+4716)/100;
  11202. X2 = 306001*(M+1)/10000;
  11203. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  11204. p->validJD = 1;
  11205. if( p->validHMS ){
  11206. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  11207. if( p->validTZ ){
  11208. p->iJD -= p->tz*60000;
  11209. p->validYMD = 0;
  11210. p->validHMS = 0;
  11211. p->validTZ = 0;
  11212. }
  11213. }
  11214. }
  11215. /*
  11216. ** Parse dates of the form
  11217. **
  11218. ** YYYY-MM-DD HH:MM:SS.FFF
  11219. ** YYYY-MM-DD HH:MM:SS
  11220. ** YYYY-MM-DD HH:MM
  11221. ** YYYY-MM-DD
  11222. **
  11223. ** Write the result into the DateTime structure and return 0
  11224. ** on success and 1 if the input string is not a well-formed
  11225. ** date.
  11226. */
  11227. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  11228. int Y, M, D, neg;
  11229. if( zDate[0]=='-' ){
  11230. zDate++;
  11231. neg = 1;
  11232. }else{
  11233. neg = 0;
  11234. }
  11235. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  11236. return 1;
  11237. }
  11238. zDate += 10;
  11239. while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  11240. if( parseHhMmSs(zDate, p)==0 ){
  11241. /* We got the time */
  11242. }else if( *zDate==0 ){
  11243. p->validHMS = 0;
  11244. }else{
  11245. return 1;
  11246. }
  11247. p->validJD = 0;
  11248. p->validYMD = 1;
  11249. p->Y = neg ? -Y : Y;
  11250. p->M = M;
  11251. p->D = D;
  11252. if( p->validTZ ){
  11253. computeJD(p);
  11254. }
  11255. return 0;
  11256. }
  11257. /*
  11258. ** Set the time to the current time reported by the VFS
  11259. */
  11260. static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  11261. double r;
  11262. sqlite3 *db = sqlite3_context_db_handle(context);
  11263. sqlite3OsCurrentTime(db->pVfs, &r);
  11264. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  11265. p->validJD = 1;
  11266. }
  11267. /*
  11268. ** Attempt to parse the given string into a Julian Day Number. Return
  11269. ** the number of errors.
  11270. **
  11271. ** The following are acceptable forms for the input string:
  11272. **
  11273. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  11274. ** DDDD.DD
  11275. ** now
  11276. **
  11277. ** In the first form, the +/-HH:MM is always optional. The fractional
  11278. ** seconds extension (the ".FFF") is optional. The seconds portion
  11279. ** (":SS.FFF") is option. The year and date can be omitted as long
  11280. ** as there is a time string. The time string can be omitted as long
  11281. ** as there is a year and date.
  11282. */
  11283. static int parseDateOrTime(
  11284. sqlite3_context *context,
  11285. const char *zDate,
  11286. DateTime *p
  11287. ){
  11288. if( parseYyyyMmDd(zDate,p)==0 ){
  11289. return 0;
  11290. }else if( parseHhMmSs(zDate, p)==0 ){
  11291. return 0;
  11292. }else if( sqlite3StrICmp(zDate,"now")==0){
  11293. setDateTimeToCurrent(context, p);
  11294. return 0;
  11295. }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
  11296. double r;
  11297. getValue(zDate, &r);
  11298. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  11299. p->validJD = 1;
  11300. return 0;
  11301. }
  11302. return 1;
  11303. }
  11304. /*
  11305. ** Compute the Year, Month, and Day from the julian day number.
  11306. */
  11307. static void computeYMD(DateTime *p){
  11308. int Z, A, B, C, D, E, X1;
  11309. if( p->validYMD ) return;
  11310. if( !p->validJD ){
  11311. p->Y = 2000;
  11312. p->M = 1;
  11313. p->D = 1;
  11314. }else{
  11315. Z = (int)((p->iJD + 43200000)/86400000);
  11316. A = (int)((Z - 1867216.25)/36524.25);
  11317. A = Z + 1 + A - (A/4);
  11318. B = A + 1524;
  11319. C = (int)((B - 122.1)/365.25);
  11320. D = (36525*C)/100;
  11321. E = (int)((B-D)/30.6001);
  11322. X1 = (int)(30.6001*E);
  11323. p->D = B - D - X1;
  11324. p->M = E<14 ? E-1 : E-13;
  11325. p->Y = p->M>2 ? C - 4716 : C - 4715;
  11326. }
  11327. p->validYMD = 1;
  11328. }
  11329. /*
  11330. ** Compute the Hour, Minute, and Seconds from the julian day number.
  11331. */
  11332. static void computeHMS(DateTime *p){
  11333. int s;
  11334. if( p->validHMS ) return;
  11335. computeJD(p);
  11336. s = (int)((p->iJD + 43200000) % 86400000);
  11337. p->s = s/1000.0;
  11338. s = (int)p->s;
  11339. p->s -= s;
  11340. p->h = s/3600;
  11341. s -= p->h*3600;
  11342. p->m = s/60;
  11343. p->s += s - p->m*60;
  11344. p->validHMS = 1;
  11345. }
  11346. /*
  11347. ** Compute both YMD and HMS
  11348. */
  11349. static void computeYMD_HMS(DateTime *p){
  11350. computeYMD(p);
  11351. computeHMS(p);
  11352. }
  11353. /*
  11354. ** Clear the YMD and HMS and the TZ
  11355. */
  11356. static void clearYMD_HMS_TZ(DateTime *p){
  11357. p->validYMD = 0;
  11358. p->validHMS = 0;
  11359. p->validTZ = 0;
  11360. }
  11361. #ifndef SQLITE_OMIT_LOCALTIME
  11362. /*
  11363. ** Compute the difference (in milliseconds)
  11364. ** between localtime and UTC (a.k.a. GMT)
  11365. ** for the time value p where p is in UTC.
  11366. */
  11367. static sqlite3_int64 localtimeOffset(DateTime *p){
  11368. DateTime x, y;
  11369. time_t t;
  11370. x = *p;
  11371. computeYMD_HMS(&x);
  11372. if( x.Y<1971 || x.Y>=2038 ){
  11373. x.Y = 2000;
  11374. x.M = 1;
  11375. x.D = 1;
  11376. x.h = 0;
  11377. x.m = 0;
  11378. x.s = 0.0;
  11379. } else {
  11380. int s = (int)(x.s + 0.5);
  11381. x.s = s;
  11382. }
  11383. x.tz = 0;
  11384. x.validJD = 0;
  11385. computeJD(&x);
  11386. t = x.iJD/1000 - 21086676*(i64)10000;
  11387. #ifdef HAVE_LOCALTIME_R
  11388. {
  11389. struct tm sLocal;
  11390. localtime_r(&t, &sLocal);
  11391. y.Y = sLocal.tm_year + 1900;
  11392. y.M = sLocal.tm_mon + 1;
  11393. y.D = sLocal.tm_mday;
  11394. y.h = sLocal.tm_hour;
  11395. y.m = sLocal.tm_min;
  11396. y.s = sLocal.tm_sec;
  11397. }
  11398. #elif defined(HAVE_LOCALTIME_S)
  11399. {
  11400. struct tm sLocal;
  11401. localtime_s(&sLocal, &t);
  11402. y.Y = sLocal.tm_year + 1900;
  11403. y.M = sLocal.tm_mon + 1;
  11404. y.D = sLocal.tm_mday;
  11405. y.h = sLocal.tm_hour;
  11406. y.m = sLocal.tm_min;
  11407. y.s = sLocal.tm_sec;
  11408. }
  11409. #else
  11410. {
  11411. struct tm *pTm;
  11412. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  11413. pTm = localtime(&t);
  11414. y.Y = pTm->tm_year + 1900;
  11415. y.M = pTm->tm_mon + 1;
  11416. y.D = pTm->tm_mday;
  11417. y.h = pTm->tm_hour;
  11418. y.m = pTm->tm_min;
  11419. y.s = pTm->tm_sec;
  11420. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  11421. }
  11422. #endif
  11423. y.validYMD = 1;
  11424. y.validHMS = 1;
  11425. y.validJD = 0;
  11426. y.validTZ = 0;
  11427. computeJD(&y);
  11428. return y.iJD - x.iJD;
  11429. }
  11430. #endif /* SQLITE_OMIT_LOCALTIME */
  11431. /*
  11432. ** Process a modifier to a date-time stamp. The modifiers are
  11433. ** as follows:
  11434. **
  11435. ** NNN days
  11436. ** NNN hours
  11437. ** NNN minutes
  11438. ** NNN.NNNN seconds
  11439. ** NNN months
  11440. ** NNN years
  11441. ** start of month
  11442. ** start of year
  11443. ** start of week
  11444. ** start of day
  11445. ** weekday N
  11446. ** unixepoch
  11447. ** localtime
  11448. ** utc
  11449. **
  11450. ** Return 0 on success and 1 if there is any kind of error.
  11451. */
  11452. static int parseModifier(const char *zMod, DateTime *p){
  11453. int rc = 1;
  11454. int n;
  11455. double r;
  11456. char *z, zBuf[30];
  11457. z = zBuf;
  11458. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  11459. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  11460. }
  11461. z[n] = 0;
  11462. switch( z[0] ){
  11463. #ifndef SQLITE_OMIT_LOCALTIME
  11464. case 'l': {
  11465. /* localtime
  11466. **
  11467. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  11468. ** show local time.
  11469. */
  11470. if( strcmp(z, "localtime")==0 ){
  11471. computeJD(p);
  11472. p->iJD += localtimeOffset(p);
  11473. clearYMD_HMS_TZ(p);
  11474. rc = 0;
  11475. }
  11476. break;
  11477. }
  11478. #endif
  11479. case 'u': {
  11480. /*
  11481. ** unixepoch
  11482. **
  11483. ** Treat the current value of p->iJD as the number of
  11484. ** seconds since 1970. Convert to a real julian day number.
  11485. */
  11486. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  11487. p->iJD = p->iJD/86400 + 21086676*(i64)10000000;
  11488. clearYMD_HMS_TZ(p);
  11489. rc = 0;
  11490. }
  11491. #ifndef SQLITE_OMIT_LOCALTIME
  11492. else if( strcmp(z, "utc")==0 ){
  11493. sqlite3_int64 c1;
  11494. computeJD(p);
  11495. c1 = localtimeOffset(p);
  11496. p->iJD -= c1;
  11497. clearYMD_HMS_TZ(p);
  11498. p->iJD += c1 - localtimeOffset(p);
  11499. rc = 0;
  11500. }
  11501. #endif
  11502. break;
  11503. }
  11504. case 'w': {
  11505. /*
  11506. ** weekday N
  11507. **
  11508. ** Move the date to the same time on the next occurrence of
  11509. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  11510. ** date is already on the appropriate weekday, this is a no-op.
  11511. */
  11512. if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
  11513. && (n=(int)r)==r && n>=0 && r<7 ){
  11514. sqlite3_int64 Z;
  11515. computeYMD_HMS(p);
  11516. p->validTZ = 0;
  11517. p->validJD = 0;
  11518. computeJD(p);
  11519. Z = ((p->iJD + 129600000)/86400000) % 7;
  11520. if( Z>n ) Z -= 7;
  11521. p->iJD += (n - Z)*86400000;
  11522. clearYMD_HMS_TZ(p);
  11523. rc = 0;
  11524. }
  11525. break;
  11526. }
  11527. case 's': {
  11528. /*
  11529. ** start of TTTTT
  11530. **
  11531. ** Move the date backwards to the beginning of the current day,
  11532. ** or month or year.
  11533. */
  11534. if( strncmp(z, "start of ", 9)!=0 ) break;
  11535. z += 9;
  11536. computeYMD(p);
  11537. p->validHMS = 1;
  11538. p->h = p->m = 0;
  11539. p->s = 0.0;
  11540. p->validTZ = 0;
  11541. p->validJD = 0;
  11542. if( strcmp(z,"month")==0 ){
  11543. p->D = 1;
  11544. rc = 0;
  11545. }else if( strcmp(z,"year")==0 ){
  11546. computeYMD(p);
  11547. p->M = 1;
  11548. p->D = 1;
  11549. rc = 0;
  11550. }else if( strcmp(z,"day")==0 ){
  11551. rc = 0;
  11552. }
  11553. break;
  11554. }
  11555. case '+':
  11556. case '-':
  11557. case '0':
  11558. case '1':
  11559. case '2':
  11560. case '3':
  11561. case '4':
  11562. case '5':
  11563. case '6':
  11564. case '7':
  11565. case '8':
  11566. case '9': {
  11567. n = getValue(z, &r);
  11568. assert( n>=1 );
  11569. if( z[n]==':' ){
  11570. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  11571. ** specified number of hours, minutes, seconds, and fractional seconds
  11572. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  11573. ** omitted.
  11574. */
  11575. const char *z2 = z;
  11576. DateTime tx;
  11577. sqlite3_int64 day;
  11578. if( !isdigit(*(u8*)z2) ) z2++;
  11579. memset(&tx, 0, sizeof(tx));
  11580. if( parseHhMmSs(z2, &tx) ) break;
  11581. computeJD(&tx);
  11582. tx.iJD -= 43200000;
  11583. day = tx.iJD/86400000;
  11584. tx.iJD -= day*86400000;
  11585. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  11586. computeJD(p);
  11587. clearYMD_HMS_TZ(p);
  11588. p->iJD += tx.iJD;
  11589. rc = 0;
  11590. break;
  11591. }
  11592. z += n;
  11593. while( isspace(*(u8*)z) ) z++;
  11594. n = sqlite3Strlen30(z);
  11595. if( n>10 || n<3 ) break;
  11596. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  11597. computeJD(p);
  11598. rc = 0;
  11599. if( n==3 && strcmp(z,"day")==0 ){
  11600. p->iJD += (sqlite3_int64)(r*86400000.0 + 0.5);
  11601. }else if( n==4 && strcmp(z,"hour")==0 ){
  11602. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + 0.5);
  11603. }else if( n==6 && strcmp(z,"minute")==0 ){
  11604. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + 0.5);
  11605. }else if( n==6 && strcmp(z,"second")==0 ){
  11606. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + 0.5);
  11607. }else if( n==5 && strcmp(z,"month")==0 ){
  11608. int x, y;
  11609. computeYMD_HMS(p);
  11610. p->M += (int)r;
  11611. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  11612. p->Y += x;
  11613. p->M -= x*12;
  11614. p->validJD = 0;
  11615. computeJD(p);
  11616. y = (int)r;
  11617. if( y!=r ){
  11618. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + 0.5);
  11619. }
  11620. }else if( n==4 && strcmp(z,"year")==0 ){
  11621. computeYMD_HMS(p);
  11622. p->Y += (int)r;
  11623. p->validJD = 0;
  11624. computeJD(p);
  11625. }else{
  11626. rc = 1;
  11627. }
  11628. clearYMD_HMS_TZ(p);
  11629. break;
  11630. }
  11631. default: {
  11632. break;
  11633. }
  11634. }
  11635. return rc;
  11636. }
  11637. /*
  11638. ** Process time function arguments. argv[0] is a date-time stamp.
  11639. ** argv[1] and following are modifiers. Parse them all and write
  11640. ** the resulting time into the DateTime structure p. Return 0
  11641. ** on success and 1 if there are any errors.
  11642. **
  11643. ** If there are zero parameters (if even argv[0] is undefined)
  11644. ** then assume a default value of "now" for argv[0].
  11645. */
  11646. static int isDate(
  11647. sqlite3_context *context,
  11648. int argc,
  11649. sqlite3_value **argv,
  11650. DateTime *p
  11651. ){
  11652. int i;
  11653. const unsigned char *z;
  11654. int eType;
  11655. memset(p, 0, sizeof(*p));
  11656. if( argc==0 ){
  11657. setDateTimeToCurrent(context, p);
  11658. }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  11659. || eType==SQLITE_INTEGER ){
  11660. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  11661. p->validJD = 1;
  11662. }else{
  11663. z = sqlite3_value_text(argv[0]);
  11664. if( !z || parseDateOrTime(context, (char*)z, p) ){
  11665. return 1;
  11666. }
  11667. }
  11668. for(i=1; i<argc; i++){
  11669. if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
  11670. return 1;
  11671. }
  11672. }
  11673. return 0;
  11674. }
  11675. /*
  11676. ** The following routines implement the various date and time functions
  11677. ** of SQLite.
  11678. */
  11679. /*
  11680. ** julianday( TIMESTRING, MOD, MOD, ...)
  11681. **
  11682. ** Return the julian day number of the date specified in the arguments
  11683. */
  11684. static void juliandayFunc(
  11685. sqlite3_context *context,
  11686. int argc,
  11687. sqlite3_value **argv
  11688. ){
  11689. DateTime x;
  11690. if( isDate(context, argc, argv, &x)==0 ){
  11691. computeJD(&x);
  11692. sqlite3_result_double(context, x.iJD/86400000.0);
  11693. }
  11694. }
  11695. /*
  11696. ** datetime( TIMESTRING, MOD, MOD, ...)
  11697. **
  11698. ** Return YYYY-MM-DD HH:MM:SS
  11699. */
  11700. static void datetimeFunc(
  11701. sqlite3_context *context,
  11702. int argc,
  11703. sqlite3_value **argv
  11704. ){
  11705. DateTime x;
  11706. if( isDate(context, argc, argv, &x)==0 ){
  11707. char zBuf[100];
  11708. computeYMD_HMS(&x);
  11709. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  11710. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  11711. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  11712. }
  11713. }
  11714. /*
  11715. ** time( TIMESTRING, MOD, MOD, ...)
  11716. **
  11717. ** Return HH:MM:SS
  11718. */
  11719. static void timeFunc(
  11720. sqlite3_context *context,
  11721. int argc,
  11722. sqlite3_value **argv
  11723. ){
  11724. DateTime x;
  11725. if( isDate(context, argc, argv, &x)==0 ){
  11726. char zBuf[100];
  11727. computeHMS(&x);
  11728. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  11729. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  11730. }
  11731. }
  11732. /*
  11733. ** date( TIMESTRING, MOD, MOD, ...)
  11734. **
  11735. ** Return YYYY-MM-DD
  11736. */
  11737. static void dateFunc(
  11738. sqlite3_context *context,
  11739. int argc,
  11740. sqlite3_value **argv
  11741. ){
  11742. DateTime x;
  11743. if( isDate(context, argc, argv, &x)==0 ){
  11744. char zBuf[100];
  11745. computeYMD(&x);
  11746. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  11747. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  11748. }
  11749. }
  11750. /*
  11751. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  11752. **
  11753. ** Return a string described by FORMAT. Conversions as follows:
  11754. **
  11755. ** %d day of month
  11756. ** %f ** fractional seconds SS.SSS
  11757. ** %H hour 00-24
  11758. ** %j day of year 000-366
  11759. ** %J ** Julian day number
  11760. ** %m month 01-12
  11761. ** %M minute 00-59
  11762. ** %s seconds since 1970-01-01
  11763. ** %S seconds 00-59
  11764. ** %w day of week 0-6 sunday==0
  11765. ** %W week of year 00-53
  11766. ** %Y year 0000-9999
  11767. ** %% %
  11768. */
  11769. static void strftimeFunc(
  11770. sqlite3_context *context,
  11771. int argc,
  11772. sqlite3_value **argv
  11773. ){
  11774. DateTime x;
  11775. u64 n;
  11776. size_t i,j;
  11777. char *z;
  11778. sqlite3 *db;
  11779. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  11780. char zBuf[100];
  11781. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  11782. db = sqlite3_context_db_handle(context);
  11783. for(i=0, n=1; zFmt[i]; i++, n++){
  11784. if( zFmt[i]=='%' ){
  11785. switch( zFmt[i+1] ){
  11786. case 'd':
  11787. case 'H':
  11788. case 'm':
  11789. case 'M':
  11790. case 'S':
  11791. case 'W':
  11792. n++;
  11793. /* fall thru */
  11794. case 'w':
  11795. case '%':
  11796. break;
  11797. case 'f':
  11798. n += 8;
  11799. break;
  11800. case 'j':
  11801. n += 3;
  11802. break;
  11803. case 'Y':
  11804. n += 8;
  11805. break;
  11806. case 's':
  11807. case 'J':
  11808. n += 50;
  11809. break;
  11810. default:
  11811. return; /* ERROR. return a NULL */
  11812. }
  11813. i++;
  11814. }
  11815. }
  11816. if( n<sizeof(zBuf) ){
  11817. z = zBuf;
  11818. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  11819. sqlite3_result_error_toobig(context);
  11820. return;
  11821. }else{
  11822. z = sqlite3DbMallocRaw(db, (int)n);
  11823. if( z==0 ){
  11824. sqlite3_result_error_nomem(context);
  11825. return;
  11826. }
  11827. }
  11828. computeJD(&x);
  11829. computeYMD_HMS(&x);
  11830. for(i=j=0; zFmt[i]; i++){
  11831. if( zFmt[i]!='%' ){
  11832. z[j++] = zFmt[i];
  11833. }else{
  11834. i++;
  11835. switch( zFmt[i] ){
  11836. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  11837. case 'f': {
  11838. double s = x.s;
  11839. if( s>59.999 ) s = 59.999;
  11840. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  11841. j += sqlite3Strlen30(&z[j]);
  11842. break;
  11843. }
  11844. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  11845. case 'W': /* Fall thru */
  11846. case 'j': {
  11847. int nDay; /* Number of days since 1st day of year */
  11848. DateTime y = x;
  11849. y.validJD = 0;
  11850. y.M = 1;
  11851. y.D = 1;
  11852. computeJD(&y);
  11853. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  11854. if( zFmt[i]=='W' ){
  11855. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  11856. wd = (int)(((x.iJD+43200000)/86400000)%7);
  11857. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  11858. j += 2;
  11859. }else{
  11860. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  11861. j += 3;
  11862. }
  11863. break;
  11864. }
  11865. case 'J': {
  11866. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  11867. j+=sqlite3Strlen30(&z[j]);
  11868. break;
  11869. }
  11870. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  11871. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  11872. case 's': {
  11873. sqlite3_snprintf(30,&z[j],"%d",
  11874. (int)(x.iJD/1000.0 - 210866760000.0));
  11875. j += sqlite3Strlen30(&z[j]);
  11876. break;
  11877. }
  11878. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  11879. case 'w': {
  11880. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  11881. break;
  11882. }
  11883. case 'Y': {
  11884. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  11885. break;
  11886. }
  11887. default: z[j++] = '%'; break;
  11888. }
  11889. }
  11890. }
  11891. z[j] = 0;
  11892. sqlite3_result_text(context, z, -1,
  11893. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  11894. }
  11895. /*
  11896. ** current_time()
  11897. **
  11898. ** This function returns the same value as time('now').
  11899. */
  11900. static void ctimeFunc(
  11901. sqlite3_context *context,
  11902. int NotUsed,
  11903. sqlite3_value **NotUsed2
  11904. ){
  11905. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  11906. timeFunc(context, 0, 0);
  11907. }
  11908. /*
  11909. ** current_date()
  11910. **
  11911. ** This function returns the same value as date('now').
  11912. */
  11913. static void cdateFunc(
  11914. sqlite3_context *context,
  11915. int NotUsed,
  11916. sqlite3_value **NotUsed2
  11917. ){
  11918. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  11919. dateFunc(context, 0, 0);
  11920. }
  11921. /*
  11922. ** current_timestamp()
  11923. **
  11924. ** This function returns the same value as datetime('now').
  11925. */
  11926. static void ctimestampFunc(
  11927. sqlite3_context *context,
  11928. int NotUsed,
  11929. sqlite3_value **NotUsed2
  11930. ){
  11931. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  11932. datetimeFunc(context, 0, 0);
  11933. }
  11934. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  11935. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  11936. /*
  11937. ** If the library is compiled to omit the full-scale date and time
  11938. ** handling (to get a smaller binary), the following minimal version
  11939. ** of the functions current_time(), current_date() and current_timestamp()
  11940. ** are included instead. This is to support column declarations that
  11941. ** include "DEFAULT CURRENT_TIME" etc.
  11942. **
  11943. ** This function uses the C-library functions time(), gmtime()
  11944. ** and strftime(). The format string to pass to strftime() is supplied
  11945. ** as the user-data for the function.
  11946. */
  11947. static void currentTimeFunc(
  11948. sqlite3_context *context,
  11949. int argc,
  11950. sqlite3_value **argv
  11951. ){
  11952. time_t t;
  11953. char *zFormat = (char *)sqlite3_user_data(context);
  11954. sqlite3 *db;
  11955. double rT;
  11956. char zBuf[20];
  11957. db = sqlite3_context_db_handle(context);
  11958. sqlite3OsCurrentTime(db->pVfs, &rT);
  11959. t = 86400.0*(rT - 2440587.5) + 0.5;
  11960. #ifdef HAVE_GMTIME_R
  11961. {
  11962. struct tm sNow;
  11963. gmtime_r(&t, &sNow);
  11964. strftime(zBuf, 20, zFormat, &sNow);
  11965. }
  11966. #else
  11967. {
  11968. struct tm *pTm;
  11969. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  11970. pTm = gmtime(&t);
  11971. strftime(zBuf, 20, zFormat, pTm);
  11972. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  11973. }
  11974. #endif
  11975. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  11976. }
  11977. #endif
  11978. /*
  11979. ** This function registered all of the above C functions as SQL
  11980. ** functions. This should be the only routine in this file with
  11981. ** external linkage.
  11982. */
  11983. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  11984. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  11985. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  11986. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  11987. FUNCTION(date, -1, 0, 0, dateFunc ),
  11988. FUNCTION(time, -1, 0, 0, timeFunc ),
  11989. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  11990. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  11991. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  11992. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  11993. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  11994. #else
  11995. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  11996. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d", 0, currentTimeFunc),
  11997. STR_FUNCTION(current_date, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  11998. #endif
  11999. };
  12000. int i;
  12001. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  12002. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  12003. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  12004. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  12005. }
  12006. }
  12007. /************** End of date.c ************************************************/
  12008. /************** Begin file os.c **********************************************/
  12009. /*
  12010. ** 2005 November 29
  12011. **
  12012. ** The author disclaims copyright to this source code. In place of
  12013. ** a legal notice, here is a blessing:
  12014. **
  12015. ** May you do good and not evil.
  12016. ** May you find forgiveness for yourself and forgive others.
  12017. ** May you share freely, never taking more than you give.
  12018. **
  12019. ******************************************************************************
  12020. **
  12021. ** This file contains OS interface code that is common to all
  12022. ** architectures.
  12023. **
  12024. ** $Id: os.c,v 1.125 2008/12/08 18:19:18 drh Exp $
  12025. */
  12026. #define _SQLITE_OS_C_ 1
  12027. #undef _SQLITE_OS_C_
  12028. /*
  12029. ** The default SQLite sqlite3_vfs implementations do not allocate
  12030. ** memory (actually, os_unix.c allocates a small amount of memory
  12031. ** from within OsOpen()), but some third-party implementations may.
  12032. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  12033. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  12034. **
  12035. ** The following functions are instrumented for malloc() failure
  12036. ** testing:
  12037. **
  12038. ** sqlite3OsOpen()
  12039. ** sqlite3OsRead()
  12040. ** sqlite3OsWrite()
  12041. ** sqlite3OsSync()
  12042. ** sqlite3OsLock()
  12043. **
  12044. */
  12045. #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
  12046. #define DO_OS_MALLOC_TEST if (1) { \
  12047. void *pTstAlloc = sqlite3Malloc(10); \
  12048. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  12049. sqlite3_free(pTstAlloc); \
  12050. }
  12051. #else
  12052. #define DO_OS_MALLOC_TEST
  12053. #endif
  12054. /*
  12055. ** The following routines are convenience wrappers around methods
  12056. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  12057. ** of this would be completely automatic if SQLite were coded using
  12058. ** C++ instead of plain old C.
  12059. */
  12060. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  12061. int rc = SQLITE_OK;
  12062. if( pId->pMethods ){
  12063. rc = pId->pMethods->xClose(pId);
  12064. pId->pMethods = 0;
  12065. }
  12066. return rc;
  12067. }
  12068. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  12069. DO_OS_MALLOC_TEST;
  12070. return id->pMethods->xRead(id, pBuf, amt, offset);
  12071. }
  12072. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  12073. DO_OS_MALLOC_TEST;
  12074. return id->pMethods->xWrite(id, pBuf, amt, offset);
  12075. }
  12076. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  12077. return id->pMethods->xTruncate(id, size);
  12078. }
  12079. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  12080. DO_OS_MALLOC_TEST;
  12081. return id->pMethods->xSync(id, flags);
  12082. }
  12083. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  12084. DO_OS_MALLOC_TEST;
  12085. return id->pMethods->xFileSize(id, pSize);
  12086. }
  12087. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  12088. DO_OS_MALLOC_TEST;
  12089. return id->pMethods->xLock(id, lockType);
  12090. }
  12091. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  12092. return id->pMethods->xUnlock(id, lockType);
  12093. }
  12094. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  12095. DO_OS_MALLOC_TEST;
  12096. return id->pMethods->xCheckReservedLock(id, pResOut);
  12097. }
  12098. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  12099. return id->pMethods->xFileControl(id, op, pArg);
  12100. }
  12101. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  12102. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  12103. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  12104. }
  12105. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  12106. return id->pMethods->xDeviceCharacteristics(id);
  12107. }
  12108. /*
  12109. ** The next group of routines are convenience wrappers around the
  12110. ** VFS methods.
  12111. */
  12112. SQLITE_PRIVATE int sqlite3OsOpen(
  12113. sqlite3_vfs *pVfs,
  12114. const char *zPath,
  12115. sqlite3_file *pFile,
  12116. int flags,
  12117. int *pFlagsOut
  12118. ){
  12119. DO_OS_MALLOC_TEST;
  12120. return pVfs->xOpen(pVfs, zPath, pFile, flags, pFlagsOut);
  12121. }
  12122. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  12123. return pVfs->xDelete(pVfs, zPath, dirSync);
  12124. }
  12125. SQLITE_PRIVATE int sqlite3OsAccess(
  12126. sqlite3_vfs *pVfs,
  12127. const char *zPath,
  12128. int flags,
  12129. int *pResOut
  12130. ){
  12131. DO_OS_MALLOC_TEST;
  12132. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  12133. }
  12134. SQLITE_PRIVATE int sqlite3OsFullPathname(
  12135. sqlite3_vfs *pVfs,
  12136. const char *zPath,
  12137. int nPathOut,
  12138. char *zPathOut
  12139. ){
  12140. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  12141. }
  12142. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  12143. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  12144. return pVfs->xDlOpen(pVfs, zPath);
  12145. }
  12146. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  12147. pVfs->xDlError(pVfs, nByte, zBufOut);
  12148. }
  12149. void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  12150. return pVfs->xDlSym(pVfs, pHdle, zSym);
  12151. }
  12152. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  12153. pVfs->xDlClose(pVfs, pHandle);
  12154. }
  12155. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  12156. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  12157. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  12158. }
  12159. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  12160. return pVfs->xSleep(pVfs, nMicro);
  12161. }
  12162. SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  12163. return pVfs->xCurrentTime(pVfs, pTimeOut);
  12164. }
  12165. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  12166. sqlite3_vfs *pVfs,
  12167. const char *zFile,
  12168. sqlite3_file **ppFile,
  12169. int flags,
  12170. int *pOutFlags
  12171. ){
  12172. int rc = SQLITE_NOMEM;
  12173. sqlite3_file *pFile;
  12174. pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
  12175. if( pFile ){
  12176. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  12177. if( rc!=SQLITE_OK ){
  12178. sqlite3_free(pFile);
  12179. }else{
  12180. *ppFile = pFile;
  12181. }
  12182. }
  12183. return rc;
  12184. }
  12185. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  12186. int rc = SQLITE_OK;
  12187. assert( pFile );
  12188. rc = sqlite3OsClose(pFile);
  12189. sqlite3_free(pFile);
  12190. return rc;
  12191. }
  12192. /*
  12193. ** The list of all registered VFS implementations.
  12194. */
  12195. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  12196. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  12197. /*
  12198. ** Locate a VFS by name. If no name is given, simply return the
  12199. ** first VFS on the list.
  12200. */
  12201. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  12202. sqlite3_vfs *pVfs = 0;
  12203. #if SQLITE_THREADSAFE
  12204. sqlite3_mutex *mutex;
  12205. #endif
  12206. #ifndef SQLITE_OMIT_AUTOINIT
  12207. int rc = sqlite3_initialize();
  12208. if( rc ) return 0;
  12209. #endif
  12210. #if SQLITE_THREADSAFE
  12211. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  12212. #endif
  12213. sqlite3_mutex_enter(mutex);
  12214. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  12215. if( zVfs==0 ) break;
  12216. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  12217. }
  12218. sqlite3_mutex_leave(mutex);
  12219. return pVfs;
  12220. }
  12221. /*
  12222. ** Unlink a VFS from the linked list
  12223. */
  12224. static void vfsUnlink(sqlite3_vfs *pVfs){
  12225. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  12226. if( pVfs==0 ){
  12227. /* No-op */
  12228. }else if( vfsList==pVfs ){
  12229. vfsList = pVfs->pNext;
  12230. }else if( vfsList ){
  12231. sqlite3_vfs *p = vfsList;
  12232. while( p->pNext && p->pNext!=pVfs ){
  12233. p = p->pNext;
  12234. }
  12235. if( p->pNext==pVfs ){
  12236. p->pNext = pVfs->pNext;
  12237. }
  12238. }
  12239. }
  12240. /*
  12241. ** Register a VFS with the system. It is harmless to register the same
  12242. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  12243. ** true.
  12244. */
  12245. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  12246. sqlite3_mutex *mutex = 0;
  12247. #ifndef SQLITE_OMIT_AUTOINIT
  12248. int rc = sqlite3_initialize();
  12249. if( rc ) return rc;
  12250. #endif
  12251. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  12252. sqlite3_mutex_enter(mutex);
  12253. vfsUnlink(pVfs);
  12254. if( makeDflt || vfsList==0 ){
  12255. pVfs->pNext = vfsList;
  12256. vfsList = pVfs;
  12257. }else{
  12258. pVfs->pNext = vfsList->pNext;
  12259. vfsList->pNext = pVfs;
  12260. }
  12261. assert(vfsList);
  12262. sqlite3_mutex_leave(mutex);
  12263. return SQLITE_OK;
  12264. }
  12265. /*
  12266. ** Unregister a VFS so that it is no longer accessible.
  12267. */
  12268. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  12269. #if SQLITE_THREADSAFE
  12270. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  12271. #endif
  12272. sqlite3_mutex_enter(mutex);
  12273. vfsUnlink(pVfs);
  12274. sqlite3_mutex_leave(mutex);
  12275. return SQLITE_OK;
  12276. }
  12277. /************** End of os.c **************************************************/
  12278. /************** Begin file fault.c *******************************************/
  12279. /*
  12280. ** 2008 Jan 22
  12281. **
  12282. ** The author disclaims copyright to this source code. In place of
  12283. ** a legal notice, here is a blessing:
  12284. **
  12285. ** May you do good and not evil.
  12286. ** May you find forgiveness for yourself and forgive others.
  12287. ** May you share freely, never taking more than you give.
  12288. **
  12289. *************************************************************************
  12290. **
  12291. ** $Id: fault.c,v 1.11 2008/09/02 00:52:52 drh Exp $
  12292. */
  12293. /*
  12294. ** This file contains code to support the concept of "benign"
  12295. ** malloc failures (when the xMalloc() or xRealloc() method of the
  12296. ** sqlite3_mem_methods structure fails to allocate a block of memory
  12297. ** and returns 0).
  12298. **
  12299. ** Most malloc failures are non-benign. After they occur, SQLite
  12300. ** abandons the current operation and returns an error code (usually
  12301. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  12302. ** fatal. For example, if a malloc fails while resizing a hash table, this
  12303. ** is completely recoverable simply by not carrying out the resize. The
  12304. ** hash table will continue to function normally. So a malloc failure
  12305. ** during a hash table resize is a benign fault.
  12306. */
  12307. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12308. /*
  12309. ** Global variables.
  12310. */
  12311. typedef struct BenignMallocHooks BenignMallocHooks;
  12312. static SQLITE_WSD struct BenignMallocHooks {
  12313. void (*xBenignBegin)(void);
  12314. void (*xBenignEnd)(void);
  12315. } sqlite3Hooks = { 0, 0 };
  12316. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  12317. ** structure. If writable static data is unsupported on the target,
  12318. ** we have to locate the state vector at run-time. In the more common
  12319. ** case where writable static data is supported, wsdHooks can refer directly
  12320. ** to the "sqlite3Hooks" state vector declared above.
  12321. */
  12322. #ifdef SQLITE_OMIT_WSD
  12323. # define wsdHooksInit \
  12324. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  12325. # define wsdHooks x[0]
  12326. #else
  12327. # define wsdHooksInit
  12328. # define wsdHooks sqlite3Hooks
  12329. #endif
  12330. /*
  12331. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  12332. ** sqlite3EndBenignMalloc() are called, respectively.
  12333. */
  12334. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  12335. void (*xBenignBegin)(void),
  12336. void (*xBenignEnd)(void)
  12337. ){
  12338. wsdHooksInit;
  12339. wsdHooks.xBenignBegin = xBenignBegin;
  12340. wsdHooks.xBenignEnd = xBenignEnd;
  12341. }
  12342. /*
  12343. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  12344. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  12345. ** indicates that subsequent malloc failures are non-benign.
  12346. */
  12347. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  12348. wsdHooksInit;
  12349. if( wsdHooks.xBenignBegin ){
  12350. wsdHooks.xBenignBegin();
  12351. }
  12352. }
  12353. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  12354. wsdHooksInit;
  12355. if( wsdHooks.xBenignEnd ){
  12356. wsdHooks.xBenignEnd();
  12357. }
  12358. }
  12359. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  12360. /************** End of fault.c ***********************************************/
  12361. /************** Begin file mem0.c ********************************************/
  12362. /*
  12363. ** 2008 October 28
  12364. **
  12365. ** The author disclaims copyright to this source code. In place of
  12366. ** a legal notice, here is a blessing:
  12367. **
  12368. ** May you do good and not evil.
  12369. ** May you find forgiveness for yourself and forgive others.
  12370. ** May you share freely, never taking more than you give.
  12371. **
  12372. *************************************************************************
  12373. **
  12374. ** This file contains a no-op memory allocation drivers for use when
  12375. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  12376. ** here always fail. SQLite will not operate with these drivers. These
  12377. ** are merely placeholders. Real drivers must be substituted using
  12378. ** sqlite3_config() before SQLite will operate.
  12379. **
  12380. ** $Id: mem0.c,v 1.1 2008/10/28 18:58:20 drh Exp $
  12381. */
  12382. /*
  12383. ** This version of the memory allocator is the default. It is
  12384. ** used when no other memory allocator is specified using compile-time
  12385. ** macros.
  12386. */
  12387. #ifdef SQLITE_ZERO_MALLOC
  12388. /*
  12389. ** No-op versions of all memory allocation routines
  12390. */
  12391. static void *sqlite3MemMalloc(int nByte){ return 0; }
  12392. static void sqlite3MemFree(void *pPrior){ return; }
  12393. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  12394. static int sqlite3MemSize(void *pPrior){ return 0; }
  12395. static int sqlite3MemRoundup(int n){ return n; }
  12396. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  12397. static void sqlite3MemShutdown(void *NotUsed){ return; }
  12398. /*
  12399. ** This routine is the only routine in this file with external linkage.
  12400. **
  12401. ** Populate the low-level memory allocation function pointers in
  12402. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  12403. */
  12404. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  12405. static const sqlite3_mem_methods defaultMethods = {
  12406. sqlite3MemMalloc,
  12407. sqlite3MemFree,
  12408. sqlite3MemRealloc,
  12409. sqlite3MemSize,
  12410. sqlite3MemRoundup,
  12411. sqlite3MemInit,
  12412. sqlite3MemShutdown,
  12413. 0
  12414. };
  12415. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  12416. }
  12417. #endif /* SQLITE_ZERO_MALLOC */
  12418. /************** End of mem0.c ************************************************/
  12419. /************** Begin file mem1.c ********************************************/
  12420. /*
  12421. ** 2007 August 14
  12422. **
  12423. ** The author disclaims copyright to this source code. In place of
  12424. ** a legal notice, here is a blessing:
  12425. **
  12426. ** May you do good and not evil.
  12427. ** May you find forgiveness for yourself and forgive others.
  12428. ** May you share freely, never taking more than you give.
  12429. **
  12430. *************************************************************************
  12431. **
  12432. ** This file contains low-level memory allocation drivers for when
  12433. ** SQLite will use the standard C-library malloc/realloc/free interface
  12434. ** to obtain the memory it needs.
  12435. **
  12436. ** This file contains implementations of the low-level memory allocation
  12437. ** routines specified in the sqlite3_mem_methods object.
  12438. **
  12439. ** $Id: mem1.c,v 1.29 2008/12/10 21:19:57 drh Exp $
  12440. */
  12441. /*
  12442. ** This version of the memory allocator is the default. It is
  12443. ** used when no other memory allocator is specified using compile-time
  12444. ** macros.
  12445. */
  12446. #ifdef SQLITE_SYSTEM_MALLOC
  12447. /*
  12448. ** Like malloc(), but remember the size of the allocation
  12449. ** so that we can find it later using sqlite3MemSize().
  12450. **
  12451. ** For this low-level routine, we are guaranteed that nByte>0 because
  12452. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  12453. ** routines.
  12454. */
  12455. static void *sqlite3MemMalloc(int nByte){
  12456. sqlite3_int64 *p;
  12457. assert( nByte>0 );
  12458. nByte = (nByte+7)&~7;
  12459. p = malloc( nByte+8 );
  12460. if( p ){
  12461. p[0] = nByte;
  12462. p++;
  12463. }
  12464. return (void *)p;
  12465. }
  12466. /*
  12467. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  12468. ** or sqlite3MemRealloc().
  12469. **
  12470. ** For this low-level routine, we already know that pPrior!=0 since
  12471. ** cases where pPrior==0 will have been intecepted and dealt with
  12472. ** by higher-level routines.
  12473. */
  12474. static void sqlite3MemFree(void *pPrior){
  12475. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  12476. assert( pPrior!=0 );
  12477. p--;
  12478. free(p);
  12479. }
  12480. /*
  12481. ** Like realloc(). Resize an allocation previously obtained from
  12482. ** sqlite3MemMalloc().
  12483. **
  12484. ** For this low-level interface, we know that pPrior!=0. Cases where
  12485. ** pPrior==0 while have been intercepted by higher-level routine and
  12486. ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
  12487. ** cases where nByte<=0 will have been intercepted by higher-level
  12488. ** routines and redirected to xFree.
  12489. */
  12490. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  12491. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  12492. assert( pPrior!=0 && nByte>0 );
  12493. nByte = (nByte+7)&~7;
  12494. p = (sqlite3_int64*)pPrior;
  12495. p--;
  12496. p = realloc(p, nByte+8 );
  12497. if( p ){
  12498. p[0] = nByte;
  12499. p++;
  12500. }
  12501. return (void*)p;
  12502. }
  12503. /*
  12504. ** Report the allocated size of a prior return from xMalloc()
  12505. ** or xRealloc().
  12506. */
  12507. static int sqlite3MemSize(void *pPrior){
  12508. sqlite3_int64 *p;
  12509. if( pPrior==0 ) return 0;
  12510. p = (sqlite3_int64*)pPrior;
  12511. p--;
  12512. return (int)p[0];
  12513. }
  12514. /*
  12515. ** Round up a request size to the next valid allocation size.
  12516. */
  12517. static int sqlite3MemRoundup(int n){
  12518. return (n+7) & ~7;
  12519. }
  12520. /*
  12521. ** Initialize this module.
  12522. */
  12523. static int sqlite3MemInit(void *NotUsed){
  12524. UNUSED_PARAMETER(NotUsed);
  12525. return SQLITE_OK;
  12526. }
  12527. /*
  12528. ** Deinitialize this module.
  12529. */
  12530. static void sqlite3MemShutdown(void *NotUsed){
  12531. UNUSED_PARAMETER(NotUsed);
  12532. return;
  12533. }
  12534. /*
  12535. ** This routine is the only routine in this file with external linkage.
  12536. **
  12537. ** Populate the low-level memory allocation function pointers in
  12538. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  12539. */
  12540. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  12541. static const sqlite3_mem_methods defaultMethods = {
  12542. sqlite3MemMalloc,
  12543. sqlite3MemFree,
  12544. sqlite3MemRealloc,
  12545. sqlite3MemSize,
  12546. sqlite3MemRoundup,
  12547. sqlite3MemInit,
  12548. sqlite3MemShutdown,
  12549. 0
  12550. };
  12551. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  12552. }
  12553. #endif /* SQLITE_SYSTEM_MALLOC */
  12554. /************** End of mem1.c ************************************************/
  12555. /************** Begin file mem2.c ********************************************/
  12556. /*
  12557. ** 2007 August 15
  12558. **
  12559. ** The author disclaims copyright to this source code. In place of
  12560. ** a legal notice, here is a blessing:
  12561. **
  12562. ** May you do good and not evil.
  12563. ** May you find forgiveness for yourself and forgive others.
  12564. ** May you share freely, never taking more than you give.
  12565. **
  12566. *************************************************************************
  12567. **
  12568. ** This file contains low-level memory allocation drivers for when
  12569. ** SQLite will use the standard C-library malloc/realloc/free interface
  12570. ** to obtain the memory it needs while adding lots of additional debugging
  12571. ** information to each allocation in order to help detect and fix memory
  12572. ** leaks and memory usage errors.
  12573. **
  12574. ** This file contains implementations of the low-level memory allocation
  12575. ** routines specified in the sqlite3_mem_methods object.
  12576. **
  12577. ** $Id: mem2.c,v 1.42 2008/12/10 19:26:24 drh Exp $
  12578. */
  12579. /*
  12580. ** This version of the memory allocator is used only if the
  12581. ** SQLITE_MEMDEBUG macro is defined
  12582. */
  12583. #ifdef SQLITE_MEMDEBUG
  12584. /*
  12585. ** The backtrace functionality is only available with GLIBC
  12586. */
  12587. #ifdef __GLIBC__
  12588. extern int backtrace(void**,int);
  12589. extern void backtrace_symbols_fd(void*const*,int,int);
  12590. #else
  12591. # define backtrace(A,B) 1
  12592. # define backtrace_symbols_fd(A,B,C)
  12593. #endif
  12594. /*
  12595. ** Each memory allocation looks like this:
  12596. **
  12597. ** ------------------------------------------------------------------------
  12598. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  12599. ** ------------------------------------------------------------------------
  12600. **
  12601. ** The application code sees only a pointer to the allocation. We have
  12602. ** to back up from the allocation pointer to find the MemBlockHdr. The
  12603. ** MemBlockHdr tells us the size of the allocation and the number of
  12604. ** backtrace pointers. There is also a guard word at the end of the
  12605. ** MemBlockHdr.
  12606. */
  12607. struct MemBlockHdr {
  12608. i64 iSize; /* Size of this allocation */
  12609. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  12610. char nBacktrace; /* Number of backtraces on this alloc */
  12611. char nBacktraceSlots; /* Available backtrace slots */
  12612. short nTitle; /* Bytes of title; includes '\0' */
  12613. int iForeGuard; /* Guard word for sanity */
  12614. };
  12615. /*
  12616. ** Guard words
  12617. */
  12618. #define FOREGUARD 0x80F5E153
  12619. #define REARGUARD 0xE4676B53
  12620. /*
  12621. ** Number of malloc size increments to track.
  12622. */
  12623. #define NCSIZE 1000
  12624. /*
  12625. ** All of the static variables used by this module are collected
  12626. ** into a single structure named "mem". This is to keep the
  12627. ** static variables organized and to reduce namespace pollution
  12628. ** when this module is combined with other in the amalgamation.
  12629. */
  12630. static struct {
  12631. /*
  12632. ** Mutex to control access to the memory allocation subsystem.
  12633. */
  12634. sqlite3_mutex *mutex;
  12635. /*
  12636. ** Head and tail of a linked list of all outstanding allocations
  12637. */
  12638. struct MemBlockHdr *pFirst;
  12639. struct MemBlockHdr *pLast;
  12640. /*
  12641. ** The number of levels of backtrace to save in new allocations.
  12642. */
  12643. int nBacktrace;
  12644. void (*xBacktrace)(int, int, void **);
  12645. /*
  12646. ** Title text to insert in front of each block
  12647. */
  12648. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  12649. char zTitle[100]; /* The title text */
  12650. /*
  12651. ** sqlite3MallocDisallow() increments the following counter.
  12652. ** sqlite3MallocAllow() decrements it.
  12653. */
  12654. int disallow; /* Do not allow memory allocation */
  12655. /*
  12656. ** Gather statistics on the sizes of memory allocations.
  12657. ** nAlloc[i] is the number of allocation attempts of i*8
  12658. ** bytes. i==NCSIZE is the number of allocation attempts for
  12659. ** sizes more than NCSIZE*8 bytes.
  12660. */
  12661. int nAlloc[NCSIZE]; /* Total number of allocations */
  12662. int nCurrent[NCSIZE]; /* Current number of allocations */
  12663. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  12664. } mem;
  12665. /*
  12666. ** Adjust memory usage statistics
  12667. */
  12668. static void adjustStats(int iSize, int increment){
  12669. int i = ((iSize+7)&~7)/8;
  12670. if( i>NCSIZE-1 ){
  12671. i = NCSIZE - 1;
  12672. }
  12673. if( increment>0 ){
  12674. mem.nAlloc[i]++;
  12675. mem.nCurrent[i]++;
  12676. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  12677. mem.mxCurrent[i] = mem.nCurrent[i];
  12678. }
  12679. }else{
  12680. mem.nCurrent[i]--;
  12681. assert( mem.nCurrent[i]>=0 );
  12682. }
  12683. }
  12684. /*
  12685. ** Given an allocation, find the MemBlockHdr for that allocation.
  12686. **
  12687. ** This routine checks the guards at either end of the allocation and
  12688. ** if they are incorrect it asserts.
  12689. */
  12690. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  12691. struct MemBlockHdr *p;
  12692. int *pInt;
  12693. u8 *pU8;
  12694. int nReserve;
  12695. p = (struct MemBlockHdr*)pAllocation;
  12696. p--;
  12697. assert( p->iForeGuard==(int)FOREGUARD );
  12698. nReserve = (p->iSize+7)&~7;
  12699. pInt = (int*)pAllocation;
  12700. pU8 = (u8*)pAllocation;
  12701. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  12702. assert( (nReserve-0)<=p->iSize || pU8[nReserve-1]==0x65 );
  12703. assert( (nReserve-1)<=p->iSize || pU8[nReserve-2]==0x65 );
  12704. assert( (nReserve-2)<=p->iSize || pU8[nReserve-3]==0x65 );
  12705. return p;
  12706. }
  12707. /*
  12708. ** Return the number of bytes currently allocated at address p.
  12709. */
  12710. static int sqlite3MemSize(void *p){
  12711. struct MemBlockHdr *pHdr;
  12712. if( !p ){
  12713. return 0;
  12714. }
  12715. pHdr = sqlite3MemsysGetHeader(p);
  12716. return pHdr->iSize;
  12717. }
  12718. /*
  12719. ** Initialize the memory allocation subsystem.
  12720. */
  12721. static int sqlite3MemInit(void *NotUsed){
  12722. UNUSED_PARAMETER(NotUsed);
  12723. if( !sqlite3GlobalConfig.bMemstat ){
  12724. /* If memory status is enabled, then the malloc.c wrapper will already
  12725. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  12726. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  12727. }
  12728. return SQLITE_OK;
  12729. }
  12730. /*
  12731. ** Deinitialize the memory allocation subsystem.
  12732. */
  12733. static void sqlite3MemShutdown(void *NotUsed){
  12734. UNUSED_PARAMETER(NotUsed);
  12735. mem.mutex = 0;
  12736. }
  12737. /*
  12738. ** Round up a request size to the next valid allocation size.
  12739. */
  12740. static int sqlite3MemRoundup(int n){
  12741. return (n+7) & ~7;
  12742. }
  12743. /*
  12744. ** Allocate nByte bytes of memory.
  12745. */
  12746. static void *sqlite3MemMalloc(int nByte){
  12747. struct MemBlockHdr *pHdr;
  12748. void **pBt;
  12749. char *z;
  12750. int *pInt;
  12751. void *p = 0;
  12752. int totalSize;
  12753. int nReserve;
  12754. sqlite3_mutex_enter(mem.mutex);
  12755. assert( mem.disallow==0 );
  12756. nReserve = (nByte+7)&~7;
  12757. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  12758. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  12759. p = malloc(totalSize);
  12760. if( p ){
  12761. z = p;
  12762. pBt = (void**)&z[mem.nTitle];
  12763. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  12764. pHdr->pNext = 0;
  12765. pHdr->pPrev = mem.pLast;
  12766. if( mem.pLast ){
  12767. mem.pLast->pNext = pHdr;
  12768. }else{
  12769. mem.pFirst = pHdr;
  12770. }
  12771. mem.pLast = pHdr;
  12772. pHdr->iForeGuard = FOREGUARD;
  12773. pHdr->nBacktraceSlots = mem.nBacktrace;
  12774. pHdr->nTitle = mem.nTitle;
  12775. if( mem.nBacktrace ){
  12776. void *aAddr[40];
  12777. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  12778. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  12779. if( mem.xBacktrace ){
  12780. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  12781. }
  12782. }else{
  12783. pHdr->nBacktrace = 0;
  12784. }
  12785. if( mem.nTitle ){
  12786. memcpy(z, mem.zTitle, mem.nTitle);
  12787. }
  12788. pHdr->iSize = nByte;
  12789. adjustStats(nByte, +1);
  12790. pInt = (int*)&pHdr[1];
  12791. pInt[nReserve/sizeof(int)] = REARGUARD;
  12792. memset(pInt, 0x65, nReserve);
  12793. p = (void*)pInt;
  12794. }
  12795. sqlite3_mutex_leave(mem.mutex);
  12796. return p;
  12797. }
  12798. /*
  12799. ** Free memory.
  12800. */
  12801. static void sqlite3MemFree(void *pPrior){
  12802. struct MemBlockHdr *pHdr;
  12803. void **pBt;
  12804. char *z;
  12805. assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
  12806. pHdr = sqlite3MemsysGetHeader(pPrior);
  12807. pBt = (void**)pHdr;
  12808. pBt -= pHdr->nBacktraceSlots;
  12809. sqlite3_mutex_enter(mem.mutex);
  12810. if( pHdr->pPrev ){
  12811. assert( pHdr->pPrev->pNext==pHdr );
  12812. pHdr->pPrev->pNext = pHdr->pNext;
  12813. }else{
  12814. assert( mem.pFirst==pHdr );
  12815. mem.pFirst = pHdr->pNext;
  12816. }
  12817. if( pHdr->pNext ){
  12818. assert( pHdr->pNext->pPrev==pHdr );
  12819. pHdr->pNext->pPrev = pHdr->pPrev;
  12820. }else{
  12821. assert( mem.pLast==pHdr );
  12822. mem.pLast = pHdr->pPrev;
  12823. }
  12824. z = (char*)pBt;
  12825. z -= pHdr->nTitle;
  12826. adjustStats(pHdr->iSize, -1);
  12827. memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  12828. pHdr->iSize + sizeof(int) + pHdr->nTitle);
  12829. free(z);
  12830. sqlite3_mutex_leave(mem.mutex);
  12831. }
  12832. /*
  12833. ** Change the size of an existing memory allocation.
  12834. **
  12835. ** For this debugging implementation, we *always* make a copy of the
  12836. ** allocation into a new place in memory. In this way, if the
  12837. ** higher level code is using pointer to the old allocation, it is
  12838. ** much more likely to break and we are much more liking to find
  12839. ** the error.
  12840. */
  12841. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  12842. struct MemBlockHdr *pOldHdr;
  12843. void *pNew;
  12844. assert( mem.disallow==0 );
  12845. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  12846. pNew = sqlite3MemMalloc(nByte);
  12847. if( pNew ){
  12848. memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
  12849. if( nByte>pOldHdr->iSize ){
  12850. memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
  12851. }
  12852. sqlite3MemFree(pPrior);
  12853. }
  12854. return pNew;
  12855. }
  12856. /*
  12857. ** Populate the low-level memory allocation function pointers in
  12858. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  12859. */
  12860. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  12861. static const sqlite3_mem_methods defaultMethods = {
  12862. sqlite3MemMalloc,
  12863. sqlite3MemFree,
  12864. sqlite3MemRealloc,
  12865. sqlite3MemSize,
  12866. sqlite3MemRoundup,
  12867. sqlite3MemInit,
  12868. sqlite3MemShutdown,
  12869. 0
  12870. };
  12871. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  12872. }
  12873. /*
  12874. ** Set the number of backtrace levels kept for each allocation.
  12875. ** A value of zero turns off backtracing. The number is always rounded
  12876. ** up to a multiple of 2.
  12877. */
  12878. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  12879. if( depth<0 ){ depth = 0; }
  12880. if( depth>20 ){ depth = 20; }
  12881. depth = (depth+1)&0xfe;
  12882. mem.nBacktrace = depth;
  12883. }
  12884. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  12885. mem.xBacktrace = xBacktrace;
  12886. }
  12887. /*
  12888. ** Set the title string for subsequent allocations.
  12889. */
  12890. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  12891. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  12892. sqlite3_mutex_enter(mem.mutex);
  12893. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  12894. memcpy(mem.zTitle, zTitle, n);
  12895. mem.zTitle[n] = 0;
  12896. mem.nTitle = (n+7)&~7;
  12897. sqlite3_mutex_leave(mem.mutex);
  12898. }
  12899. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  12900. struct MemBlockHdr *pHdr;
  12901. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  12902. void **pBt = (void**)pHdr;
  12903. pBt -= pHdr->nBacktraceSlots;
  12904. mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  12905. }
  12906. }
  12907. /*
  12908. ** Open the file indicated and write a log of all unfreed memory
  12909. ** allocations into that log.
  12910. */
  12911. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  12912. FILE *out;
  12913. struct MemBlockHdr *pHdr;
  12914. void **pBt;
  12915. int i;
  12916. out = fopen(zFilename, "w");
  12917. if( out==0 ){
  12918. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  12919. zFilename);
  12920. return;
  12921. }
  12922. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  12923. char *z = (char*)pHdr;
  12924. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  12925. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  12926. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  12927. if( pHdr->nBacktrace ){
  12928. fflush(out);
  12929. pBt = (void**)pHdr;
  12930. pBt -= pHdr->nBacktraceSlots;
  12931. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  12932. fprintf(out, "\n");
  12933. }
  12934. }
  12935. fprintf(out, "COUNTS:\n");
  12936. for(i=0; i<NCSIZE-1; i++){
  12937. if( mem.nAlloc[i] ){
  12938. fprintf(out, " %5d: %10d %10d %10d\n",
  12939. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  12940. }
  12941. }
  12942. if( mem.nAlloc[NCSIZE-1] ){
  12943. fprintf(out, " %5d: %10d %10d %10d\n",
  12944. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  12945. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  12946. }
  12947. fclose(out);
  12948. }
  12949. /*
  12950. ** Return the number of times sqlite3MemMalloc() has been called.
  12951. */
  12952. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  12953. int i;
  12954. int nTotal = 0;
  12955. for(i=0; i<NCSIZE; i++){
  12956. nTotal += mem.nAlloc[i];
  12957. }
  12958. return nTotal;
  12959. }
  12960. #endif /* SQLITE_MEMDEBUG */
  12961. /************** End of mem2.c ************************************************/
  12962. /************** Begin file mem3.c ********************************************/
  12963. /*
  12964. ** 2007 October 14
  12965. **
  12966. ** The author disclaims copyright to this source code. In place of
  12967. ** a legal notice, here is a blessing:
  12968. **
  12969. ** May you do good and not evil.
  12970. ** May you find forgiveness for yourself and forgive others.
  12971. ** May you share freely, never taking more than you give.
  12972. **
  12973. *************************************************************************
  12974. ** This file contains the C functions that implement a memory
  12975. ** allocation subsystem for use by SQLite.
  12976. **
  12977. ** This version of the memory allocation subsystem omits all
  12978. ** use of malloc(). The SQLite user supplies a block of memory
  12979. ** before calling sqlite3_initialize() from which allocations
  12980. ** are made and returned by the xMalloc() and xRealloc()
  12981. ** implementations. Once sqlite3_initialize() has been called,
  12982. ** the amount of memory available to SQLite is fixed and cannot
  12983. ** be changed.
  12984. **
  12985. ** This version of the memory allocation subsystem is included
  12986. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  12987. **
  12988. ** $Id: mem3.c,v 1.25 2008/11/19 16:52:44 danielk1977 Exp $
  12989. */
  12990. /*
  12991. ** This version of the memory allocator is only built into the library
  12992. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  12993. ** mean that the library will use a memory-pool by default, just that
  12994. ** it is available. The mempool allocator is activated by calling
  12995. ** sqlite3_config().
  12996. */
  12997. #ifdef SQLITE_ENABLE_MEMSYS3
  12998. /*
  12999. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  13000. */
  13001. #define MX_SMALL 10
  13002. /*
  13003. ** Number of freelist hash slots
  13004. */
  13005. #define N_HASH 61
  13006. /*
  13007. ** A memory allocation (also called a "chunk") consists of two or
  13008. ** more blocks where each block is 8 bytes. The first 8 bytes are
  13009. ** a header that is not returned to the user.
  13010. **
  13011. ** A chunk is two or more blocks that is either checked out or
  13012. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  13013. ** size of the allocation in blocks if the allocation is free.
  13014. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  13015. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  13016. ** is true if the previous chunk is checked out and false if the
  13017. ** previous chunk is free. The u.hdr.prevSize field is the size of
  13018. ** the previous chunk in blocks if the previous chunk is on the
  13019. ** freelist. If the previous chunk is checked out, then
  13020. ** u.hdr.prevSize can be part of the data for that chunk and should
  13021. ** not be read or written.
  13022. **
  13023. ** We often identify a chunk by its index in mem3.aPool[]. When
  13024. ** this is done, the chunk index refers to the second block of
  13025. ** the chunk. In this way, the first chunk has an index of 1.
  13026. ** A chunk index of 0 means "no such chunk" and is the equivalent
  13027. ** of a NULL pointer.
  13028. **
  13029. ** The second block of free chunks is of the form u.list. The
  13030. ** two fields form a double-linked list of chunks of related sizes.
  13031. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  13032. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  13033. **
  13034. ** The second block of a chunk is user data if the chunk is checked
  13035. ** out. If a chunk is checked out, the user data may extend into
  13036. ** the u.hdr.prevSize value of the following chunk.
  13037. */
  13038. typedef struct Mem3Block Mem3Block;
  13039. struct Mem3Block {
  13040. union {
  13041. struct {
  13042. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  13043. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  13044. } hdr;
  13045. struct {
  13046. u32 next; /* Index in mem3.aPool[] of next free chunk */
  13047. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  13048. } list;
  13049. } u;
  13050. };
  13051. /*
  13052. ** All of the static variables used by this module are collected
  13053. ** into a single structure named "mem3". This is to keep the
  13054. ** static variables organized and to reduce namespace pollution
  13055. ** when this module is combined with other in the amalgamation.
  13056. */
  13057. static SQLITE_WSD struct Mem3Global {
  13058. /*
  13059. ** Memory available for allocation. nPool is the size of the array
  13060. ** (in Mem3Blocks) pointed to by aPool less 2.
  13061. */
  13062. u32 nPool;
  13063. Mem3Block *aPool;
  13064. /*
  13065. ** True if we are evaluating an out-of-memory callback.
  13066. */
  13067. int alarmBusy;
  13068. /*
  13069. ** Mutex to control access to the memory allocation subsystem.
  13070. */
  13071. sqlite3_mutex *mutex;
  13072. /*
  13073. ** The minimum amount of free space that we have seen.
  13074. */
  13075. u32 mnMaster;
  13076. /*
  13077. ** iMaster is the index of the master chunk. Most new allocations
  13078. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  13079. ** of the current master. iMaster is 0 if there is not master chunk.
  13080. ** The master chunk is not in either the aiHash[] or aiSmall[].
  13081. */
  13082. u32 iMaster;
  13083. u32 szMaster;
  13084. /*
  13085. ** Array of lists of free blocks according to the block size
  13086. ** for smaller chunks, or a hash on the block size for larger
  13087. ** chunks.
  13088. */
  13089. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  13090. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  13091. } mem3 = { 97535575 };
  13092. #define mem3 GLOBAL(struct Mem3Global, mem3)
  13093. /*
  13094. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  13095. ** on. *pRoot is the list that i is a member of.
  13096. */
  13097. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  13098. u32 next = mem3.aPool[i].u.list.next;
  13099. u32 prev = mem3.aPool[i].u.list.prev;
  13100. assert( sqlite3_mutex_held(mem3.mutex) );
  13101. if( prev==0 ){
  13102. *pRoot = next;
  13103. }else{
  13104. mem3.aPool[prev].u.list.next = next;
  13105. }
  13106. if( next ){
  13107. mem3.aPool[next].u.list.prev = prev;
  13108. }
  13109. mem3.aPool[i].u.list.next = 0;
  13110. mem3.aPool[i].u.list.prev = 0;
  13111. }
  13112. /*
  13113. ** Unlink the chunk at index i from
  13114. ** whatever list is currently a member of.
  13115. */
  13116. static void memsys3Unlink(u32 i){
  13117. u32 size, hash;
  13118. assert( sqlite3_mutex_held(mem3.mutex) );
  13119. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  13120. assert( i>=1 );
  13121. size = mem3.aPool[i-1].u.hdr.size4x/4;
  13122. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  13123. assert( size>=2 );
  13124. if( size <= MX_SMALL ){
  13125. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  13126. }else{
  13127. hash = size % N_HASH;
  13128. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  13129. }
  13130. }
  13131. /*
  13132. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  13133. ** at *pRoot.
  13134. */
  13135. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  13136. assert( sqlite3_mutex_held(mem3.mutex) );
  13137. mem3.aPool[i].u.list.next = *pRoot;
  13138. mem3.aPool[i].u.list.prev = 0;
  13139. if( *pRoot ){
  13140. mem3.aPool[*pRoot].u.list.prev = i;
  13141. }
  13142. *pRoot = i;
  13143. }
  13144. /*
  13145. ** Link the chunk at index i into either the appropriate
  13146. ** small chunk list, or into the large chunk hash table.
  13147. */
  13148. static void memsys3Link(u32 i){
  13149. u32 size, hash;
  13150. assert( sqlite3_mutex_held(mem3.mutex) );
  13151. assert( i>=1 );
  13152. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  13153. size = mem3.aPool[i-1].u.hdr.size4x/4;
  13154. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  13155. assert( size>=2 );
  13156. if( size <= MX_SMALL ){
  13157. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  13158. }else{
  13159. hash = size % N_HASH;
  13160. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  13161. }
  13162. }
  13163. /*
  13164. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  13165. ** will already be held (obtained by code in malloc.c) if
  13166. ** sqlite3GlobalConfig.bMemStat is true.
  13167. */
  13168. static void memsys3Enter(void){
  13169. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  13170. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  13171. }
  13172. sqlite3_mutex_enter(mem3.mutex);
  13173. }
  13174. static void memsys3Leave(void){
  13175. sqlite3_mutex_leave(mem3.mutex);
  13176. }
  13177. /*
  13178. ** Called when we are unable to satisfy an allocation of nBytes.
  13179. */
  13180. static void memsys3OutOfMemory(int nByte){
  13181. if( !mem3.alarmBusy ){
  13182. mem3.alarmBusy = 1;
  13183. assert( sqlite3_mutex_held(mem3.mutex) );
  13184. sqlite3_mutex_leave(mem3.mutex);
  13185. sqlite3_release_memory(nByte);
  13186. sqlite3_mutex_enter(mem3.mutex);
  13187. mem3.alarmBusy = 0;
  13188. }
  13189. }
  13190. /*
  13191. ** Chunk i is a free chunk that has been unlinked. Adjust its
  13192. ** size parameters for check-out and return a pointer to the
  13193. ** user portion of the chunk.
  13194. */
  13195. static void *memsys3Checkout(u32 i, u32 nBlock){
  13196. u32 x;
  13197. assert( sqlite3_mutex_held(mem3.mutex) );
  13198. assert( i>=1 );
  13199. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  13200. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  13201. x = mem3.aPool[i-1].u.hdr.size4x;
  13202. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  13203. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  13204. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  13205. return &mem3.aPool[i];
  13206. }
  13207. /*
  13208. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  13209. ** Return a pointer to the new allocation. Or, if the master chunk
  13210. ** is not large enough, return 0.
  13211. */
  13212. static void *memsys3FromMaster(u32 nBlock){
  13213. assert( sqlite3_mutex_held(mem3.mutex) );
  13214. assert( mem3.szMaster>=nBlock );
  13215. if( nBlock>=mem3.szMaster-1 ){
  13216. /* Use the entire master */
  13217. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  13218. mem3.iMaster = 0;
  13219. mem3.szMaster = 0;
  13220. mem3.mnMaster = 0;
  13221. return p;
  13222. }else{
  13223. /* Split the master block. Return the tail. */
  13224. u32 newi, x;
  13225. newi = mem3.iMaster + mem3.szMaster - nBlock;
  13226. assert( newi > mem3.iMaster+1 );
  13227. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  13228. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  13229. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  13230. mem3.szMaster -= nBlock;
  13231. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  13232. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  13233. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  13234. if( mem3.szMaster < mem3.mnMaster ){
  13235. mem3.mnMaster = mem3.szMaster;
  13236. }
  13237. return (void*)&mem3.aPool[newi];
  13238. }
  13239. }
  13240. /*
  13241. ** *pRoot is the head of a list of free chunks of the same size
  13242. ** or same size hash. In other words, *pRoot is an entry in either
  13243. ** mem3.aiSmall[] or mem3.aiHash[].
  13244. **
  13245. ** This routine examines all entries on the given list and tries
  13246. ** to coalesce each entries with adjacent free chunks.
  13247. **
  13248. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  13249. ** the current mem3.iMaster with the new larger chunk. In order for
  13250. ** this mem3.iMaster replacement to work, the master chunk must be
  13251. ** linked into the hash tables. That is not the normal state of
  13252. ** affairs, of course. The calling routine must link the master
  13253. ** chunk before invoking this routine, then must unlink the (possibly
  13254. ** changed) master chunk once this routine has finished.
  13255. */
  13256. static void memsys3Merge(u32 *pRoot){
  13257. u32 iNext, prev, size, i, x;
  13258. assert( sqlite3_mutex_held(mem3.mutex) );
  13259. for(i=*pRoot; i>0; i=iNext){
  13260. iNext = mem3.aPool[i].u.list.next;
  13261. size = mem3.aPool[i-1].u.hdr.size4x;
  13262. assert( (size&1)==0 );
  13263. if( (size&2)==0 ){
  13264. memsys3UnlinkFromList(i, pRoot);
  13265. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  13266. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  13267. if( prev==iNext ){
  13268. iNext = mem3.aPool[prev].u.list.next;
  13269. }
  13270. memsys3Unlink(prev);
  13271. size = i + size/4 - prev;
  13272. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  13273. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  13274. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  13275. memsys3Link(prev);
  13276. i = prev;
  13277. }else{
  13278. size /= 4;
  13279. }
  13280. if( size>mem3.szMaster ){
  13281. mem3.iMaster = i;
  13282. mem3.szMaster = size;
  13283. }
  13284. }
  13285. }
  13286. /*
  13287. ** Return a block of memory of at least nBytes in size.
  13288. ** Return NULL if unable.
  13289. **
  13290. ** This function assumes that the necessary mutexes, if any, are
  13291. ** already held by the caller. Hence "Unsafe".
  13292. */
  13293. static void *memsys3MallocUnsafe(int nByte){
  13294. u32 i;
  13295. u32 nBlock;
  13296. u32 toFree;
  13297. assert( sqlite3_mutex_held(mem3.mutex) );
  13298. assert( sizeof(Mem3Block)==8 );
  13299. if( nByte<=12 ){
  13300. nBlock = 2;
  13301. }else{
  13302. nBlock = (nByte + 11)/8;
  13303. }
  13304. assert( nBlock>=2 );
  13305. /* STEP 1:
  13306. ** Look for an entry of the correct size in either the small
  13307. ** chunk table or in the large chunk hash table. This is
  13308. ** successful most of the time (about 9 times out of 10).
  13309. */
  13310. if( nBlock <= MX_SMALL ){
  13311. i = mem3.aiSmall[nBlock-2];
  13312. if( i>0 ){
  13313. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  13314. return memsys3Checkout(i, nBlock);
  13315. }
  13316. }else{
  13317. int hash = nBlock % N_HASH;
  13318. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  13319. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  13320. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  13321. return memsys3Checkout(i, nBlock);
  13322. }
  13323. }
  13324. }
  13325. /* STEP 2:
  13326. ** Try to satisfy the allocation by carving a piece off of the end
  13327. ** of the master chunk. This step usually works if step 1 fails.
  13328. */
  13329. if( mem3.szMaster>=nBlock ){
  13330. return memsys3FromMaster(nBlock);
  13331. }
  13332. /* STEP 3:
  13333. ** Loop through the entire memory pool. Coalesce adjacent free
  13334. ** chunks. Recompute the master chunk as the largest free chunk.
  13335. ** Then try again to satisfy the allocation by carving a piece off
  13336. ** of the end of the master chunk. This step happens very
  13337. ** rarely (we hope!)
  13338. */
  13339. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  13340. memsys3OutOfMemory(toFree);
  13341. if( mem3.iMaster ){
  13342. memsys3Link(mem3.iMaster);
  13343. mem3.iMaster = 0;
  13344. mem3.szMaster = 0;
  13345. }
  13346. for(i=0; i<N_HASH; i++){
  13347. memsys3Merge(&mem3.aiHash[i]);
  13348. }
  13349. for(i=0; i<MX_SMALL-1; i++){
  13350. memsys3Merge(&mem3.aiSmall[i]);
  13351. }
  13352. if( mem3.szMaster ){
  13353. memsys3Unlink(mem3.iMaster);
  13354. if( mem3.szMaster>=nBlock ){
  13355. return memsys3FromMaster(nBlock);
  13356. }
  13357. }
  13358. }
  13359. /* If none of the above worked, then we fail. */
  13360. return 0;
  13361. }
  13362. /*
  13363. ** Free an outstanding memory allocation.
  13364. **
  13365. ** This function assumes that the necessary mutexes, if any, are
  13366. ** already held by the caller. Hence "Unsafe".
  13367. */
  13368. void memsys3FreeUnsafe(void *pOld){
  13369. Mem3Block *p = (Mem3Block*)pOld;
  13370. int i;
  13371. u32 size, x;
  13372. assert( sqlite3_mutex_held(mem3.mutex) );
  13373. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  13374. i = p - mem3.aPool;
  13375. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  13376. size = mem3.aPool[i-1].u.hdr.size4x/4;
  13377. assert( i+size<=mem3.nPool+1 );
  13378. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  13379. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  13380. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  13381. memsys3Link(i);
  13382. /* Try to expand the master using the newly freed chunk */
  13383. if( mem3.iMaster ){
  13384. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  13385. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  13386. mem3.iMaster -= size;
  13387. mem3.szMaster += size;
  13388. memsys3Unlink(mem3.iMaster);
  13389. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  13390. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  13391. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  13392. }
  13393. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  13394. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  13395. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  13396. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  13397. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  13398. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  13399. }
  13400. }
  13401. }
  13402. /*
  13403. ** Return the size of an outstanding allocation, in bytes. The
  13404. ** size returned omits the 8-byte header overhead. This only
  13405. ** works for chunks that are currently checked out.
  13406. */
  13407. static int memsys3Size(void *p){
  13408. Mem3Block *pBlock;
  13409. if( p==0 ) return 0;
  13410. pBlock = (Mem3Block*)p;
  13411. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  13412. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  13413. }
  13414. /*
  13415. ** Round up a request size to the next valid allocation size.
  13416. */
  13417. static int memsys3Roundup(int n){
  13418. if( n<=12 ){
  13419. return 12;
  13420. }else{
  13421. return ((n+11)&~7) - 4;
  13422. }
  13423. }
  13424. /*
  13425. ** Allocate nBytes of memory.
  13426. */
  13427. static void *memsys3Malloc(int nBytes){
  13428. sqlite3_int64 *p;
  13429. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  13430. memsys3Enter();
  13431. p = memsys3MallocUnsafe(nBytes);
  13432. memsys3Leave();
  13433. return (void*)p;
  13434. }
  13435. /*
  13436. ** Free memory.
  13437. */
  13438. void memsys3Free(void *pPrior){
  13439. assert( pPrior );
  13440. memsys3Enter();
  13441. memsys3FreeUnsafe(pPrior);
  13442. memsys3Leave();
  13443. }
  13444. /*
  13445. ** Change the size of an existing memory allocation
  13446. */
  13447. void *memsys3Realloc(void *pPrior, int nBytes){
  13448. int nOld;
  13449. void *p;
  13450. if( pPrior==0 ){
  13451. return sqlite3_malloc(nBytes);
  13452. }
  13453. if( nBytes<=0 ){
  13454. sqlite3_free(pPrior);
  13455. return 0;
  13456. }
  13457. nOld = memsys3Size(pPrior);
  13458. if( nBytes<=nOld && nBytes>=nOld-128 ){
  13459. return pPrior;
  13460. }
  13461. memsys3Enter();
  13462. p = memsys3MallocUnsafe(nBytes);
  13463. if( p ){
  13464. if( nOld<nBytes ){
  13465. memcpy(p, pPrior, nOld);
  13466. }else{
  13467. memcpy(p, pPrior, nBytes);
  13468. }
  13469. memsys3FreeUnsafe(pPrior);
  13470. }
  13471. memsys3Leave();
  13472. return p;
  13473. }
  13474. /*
  13475. ** Initialize this module.
  13476. */
  13477. static int memsys3Init(void *NotUsed){
  13478. UNUSED_PARAMETER(NotUsed);
  13479. if( !sqlite3GlobalConfig.pHeap ){
  13480. return SQLITE_ERROR;
  13481. }
  13482. /* Store a pointer to the memory block in global structure mem3. */
  13483. assert( sizeof(Mem3Block)==8 );
  13484. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  13485. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  13486. /* Initialize the master block. */
  13487. mem3.szMaster = mem3.nPool;
  13488. mem3.mnMaster = mem3.szMaster;
  13489. mem3.iMaster = 1;
  13490. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  13491. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  13492. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  13493. return SQLITE_OK;
  13494. }
  13495. /*
  13496. ** Deinitialize this module.
  13497. */
  13498. static void memsys3Shutdown(void *NotUsed){
  13499. UNUSED_PARAMETER(NotUsed);
  13500. return;
  13501. }
  13502. /*
  13503. ** Open the file indicated and write a log of all unfreed memory
  13504. ** allocations into that log.
  13505. */
  13506. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  13507. #ifdef SQLITE_DEBUG
  13508. FILE *out;
  13509. u32 i, j;
  13510. u32 size;
  13511. if( zFilename==0 || zFilename[0]==0 ){
  13512. out = stdout;
  13513. }else{
  13514. out = fopen(zFilename, "w");
  13515. if( out==0 ){
  13516. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  13517. zFilename);
  13518. return;
  13519. }
  13520. }
  13521. memsys3Enter();
  13522. fprintf(out, "CHUNKS:\n");
  13523. for(i=1; i<=mem3.nPool; i+=size/4){
  13524. size = mem3.aPool[i-1].u.hdr.size4x;
  13525. if( size/4<=1 ){
  13526. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  13527. assert( 0 );
  13528. break;
  13529. }
  13530. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  13531. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  13532. assert( 0 );
  13533. break;
  13534. }
  13535. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  13536. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  13537. assert( 0 );
  13538. break;
  13539. }
  13540. if( size&1 ){
  13541. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  13542. }else{
  13543. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  13544. i==mem3.iMaster ? " **master**" : "");
  13545. }
  13546. }
  13547. for(i=0; i<MX_SMALL-1; i++){
  13548. if( mem3.aiSmall[i]==0 ) continue;
  13549. fprintf(out, "small(%2d):", i);
  13550. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  13551. fprintf(out, " %p(%d)", &mem3.aPool[j],
  13552. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  13553. }
  13554. fprintf(out, "\n");
  13555. }
  13556. for(i=0; i<N_HASH; i++){
  13557. if( mem3.aiHash[i]==0 ) continue;
  13558. fprintf(out, "hash(%2d):", i);
  13559. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  13560. fprintf(out, " %p(%d)", &mem3.aPool[j],
  13561. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  13562. }
  13563. fprintf(out, "\n");
  13564. }
  13565. fprintf(out, "master=%d\n", mem3.iMaster);
  13566. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  13567. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  13568. sqlite3_mutex_leave(mem3.mutex);
  13569. if( out==stdout ){
  13570. fflush(stdout);
  13571. }else{
  13572. fclose(out);
  13573. }
  13574. #else
  13575. UNUSED_PARAMETER(zFilename);
  13576. #endif
  13577. }
  13578. /*
  13579. ** This routine is the only routine in this file with external
  13580. ** linkage.
  13581. **
  13582. ** Populate the low-level memory allocation function pointers in
  13583. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  13584. ** arguments specify the block of memory to manage.
  13585. **
  13586. ** This routine is only called by sqlite3_config(), and therefore
  13587. ** is not required to be threadsafe (it is not).
  13588. */
  13589. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  13590. static const sqlite3_mem_methods mempoolMethods = {
  13591. memsys3Malloc,
  13592. memsys3Free,
  13593. memsys3Realloc,
  13594. memsys3Size,
  13595. memsys3Roundup,
  13596. memsys3Init,
  13597. memsys3Shutdown,
  13598. 0
  13599. };
  13600. return &mempoolMethods;
  13601. }
  13602. #endif /* SQLITE_ENABLE_MEMSYS3 */
  13603. /************** End of mem3.c ************************************************/
  13604. /************** Begin file mem5.c ********************************************/
  13605. /*
  13606. ** 2007 October 14
  13607. **
  13608. ** The author disclaims copyright to this source code. In place of
  13609. ** a legal notice, here is a blessing:
  13610. **
  13611. ** May you do good and not evil.
  13612. ** May you find forgiveness for yourself and forgive others.
  13613. ** May you share freely, never taking more than you give.
  13614. **
  13615. *************************************************************************
  13616. ** This file contains the C functions that implement a memory
  13617. ** allocation subsystem for use by SQLite.
  13618. **
  13619. ** This version of the memory allocation subsystem omits all
  13620. ** use of malloc(). The SQLite user supplies a block of memory
  13621. ** before calling sqlite3_initialize() from which allocations
  13622. ** are made and returned by the xMalloc() and xRealloc()
  13623. ** implementations. Once sqlite3_initialize() has been called,
  13624. ** the amount of memory available to SQLite is fixed and cannot
  13625. ** be changed.
  13626. **
  13627. ** This version of the memory allocation subsystem is included
  13628. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  13629. **
  13630. ** $Id: mem5.c,v 1.19 2008/11/19 16:52:44 danielk1977 Exp $
  13631. */
  13632. /*
  13633. ** This version of the memory allocator is used only when
  13634. ** SQLITE_ENABLE_MEMSYS5 is defined.
  13635. */
  13636. #ifdef SQLITE_ENABLE_MEMSYS5
  13637. /*
  13638. ** A minimum allocation is an instance of the following structure.
  13639. ** Larger allocations are an array of these structures where the
  13640. ** size of the array is a power of 2.
  13641. */
  13642. typedef struct Mem5Link Mem5Link;
  13643. struct Mem5Link {
  13644. int next; /* Index of next free chunk */
  13645. int prev; /* Index of previous free chunk */
  13646. };
  13647. /*
  13648. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.nAtom). Since
  13649. ** mem5.nAtom is always at least 8, this is not really a practical
  13650. ** limitation.
  13651. */
  13652. #define LOGMAX 30
  13653. /*
  13654. ** Masks used for mem5.aCtrl[] elements.
  13655. */
  13656. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block relative to POW2_MIN */
  13657. #define CTRL_FREE 0x20 /* True if not checked out */
  13658. /*
  13659. ** All of the static variables used by this module are collected
  13660. ** into a single structure named "mem5". This is to keep the
  13661. ** static variables organized and to reduce namespace pollution
  13662. ** when this module is combined with other in the amalgamation.
  13663. */
  13664. static SQLITE_WSD struct Mem5Global {
  13665. /*
  13666. ** Memory available for allocation
  13667. */
  13668. int nAtom; /* Smallest possible allocation in bytes */
  13669. int nBlock; /* Number of nAtom sized blocks in zPool */
  13670. u8 *zPool;
  13671. /*
  13672. ** Mutex to control access to the memory allocation subsystem.
  13673. */
  13674. sqlite3_mutex *mutex;
  13675. /*
  13676. ** Performance statistics
  13677. */
  13678. u64 nAlloc; /* Total number of calls to malloc */
  13679. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  13680. u64 totalExcess; /* Total internal fragmentation */
  13681. u32 currentOut; /* Current checkout, including internal fragmentation */
  13682. u32 currentCount; /* Current number of distinct checkouts */
  13683. u32 maxOut; /* Maximum instantaneous currentOut */
  13684. u32 maxCount; /* Maximum instantaneous currentCount */
  13685. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  13686. /*
  13687. ** Lists of free blocks of various sizes.
  13688. */
  13689. int aiFreelist[LOGMAX+1];
  13690. /*
  13691. ** Space for tracking which blocks are checked out and the size
  13692. ** of each block. One byte per block.
  13693. */
  13694. u8 *aCtrl;
  13695. } mem5 = { 19804167 };
  13696. #define mem5 GLOBAL(struct Mem5Global, mem5)
  13697. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.nAtom]))
  13698. /*
  13699. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  13700. ** on. It should be found on mem5.aiFreelist[iLogsize].
  13701. */
  13702. static void memsys5Unlink(int i, int iLogsize){
  13703. int next, prev;
  13704. assert( i>=0 && i<mem5.nBlock );
  13705. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  13706. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  13707. next = MEM5LINK(i)->next;
  13708. prev = MEM5LINK(i)->prev;
  13709. if( prev<0 ){
  13710. mem5.aiFreelist[iLogsize] = next;
  13711. }else{
  13712. MEM5LINK(prev)->next = next;
  13713. }
  13714. if( next>=0 ){
  13715. MEM5LINK(next)->prev = prev;
  13716. }
  13717. }
  13718. /*
  13719. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  13720. ** free list.
  13721. */
  13722. static void memsys5Link(int i, int iLogsize){
  13723. int x;
  13724. assert( sqlite3_mutex_held(mem5.mutex) );
  13725. assert( i>=0 && i<mem5.nBlock );
  13726. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  13727. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  13728. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  13729. MEM5LINK(i)->prev = -1;
  13730. if( x>=0 ){
  13731. assert( x<mem5.nBlock );
  13732. MEM5LINK(x)->prev = i;
  13733. }
  13734. mem5.aiFreelist[iLogsize] = i;
  13735. }
  13736. /*
  13737. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  13738. ** will already be held (obtained by code in malloc.c) if
  13739. ** sqlite3GlobalConfig.bMemStat is true.
  13740. */
  13741. static void memsys5Enter(void){
  13742. if( sqlite3GlobalConfig.bMemstat==0 && mem5.mutex==0 ){
  13743. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  13744. }
  13745. sqlite3_mutex_enter(mem5.mutex);
  13746. }
  13747. static void memsys5Leave(void){
  13748. sqlite3_mutex_leave(mem5.mutex);
  13749. }
  13750. /*
  13751. ** Return the size of an outstanding allocation, in bytes. The
  13752. ** size returned omits the 8-byte header overhead. This only
  13753. ** works for chunks that are currently checked out.
  13754. */
  13755. static int memsys5Size(void *p){
  13756. int iSize = 0;
  13757. if( p ){
  13758. int i = ((u8 *)p-mem5.zPool)/mem5.nAtom;
  13759. assert( i>=0 && i<mem5.nBlock );
  13760. iSize = mem5.nAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  13761. }
  13762. return iSize;
  13763. }
  13764. /*
  13765. ** Find the first entry on the freelist iLogsize. Unlink that
  13766. ** entry and return its index.
  13767. */
  13768. static int memsys5UnlinkFirst(int iLogsize){
  13769. int i;
  13770. int iFirst;
  13771. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  13772. i = iFirst = mem5.aiFreelist[iLogsize];
  13773. assert( iFirst>=0 );
  13774. while( i>0 ){
  13775. if( i<iFirst ) iFirst = i;
  13776. i = MEM5LINK(i)->next;
  13777. }
  13778. memsys5Unlink(iFirst, iLogsize);
  13779. return iFirst;
  13780. }
  13781. /*
  13782. ** Return a block of memory of at least nBytes in size.
  13783. ** Return NULL if unable.
  13784. */
  13785. static void *memsys5MallocUnsafe(int nByte){
  13786. int i; /* Index of a mem5.aPool[] slot */
  13787. int iBin; /* Index into mem5.aiFreelist[] */
  13788. int iFullSz; /* Size of allocation rounded up to power of 2 */
  13789. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  13790. /* Keep track of the maximum allocation request. Even unfulfilled
  13791. ** requests are counted */
  13792. if( (u32)nByte>mem5.maxRequest ){
  13793. mem5.maxRequest = nByte;
  13794. }
  13795. /* Round nByte up to the next valid power of two */
  13796. for(iFullSz=mem5.nAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  13797. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  13798. ** block. If not, then split a block of the next larger power of
  13799. ** two in order to create a new free block of size iLogsize.
  13800. */
  13801. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  13802. if( iBin>LOGMAX ) return 0;
  13803. i = memsys5UnlinkFirst(iBin);
  13804. while( iBin>iLogsize ){
  13805. int newSize;
  13806. iBin--;
  13807. newSize = 1 << iBin;
  13808. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  13809. memsys5Link(i+newSize, iBin);
  13810. }
  13811. mem5.aCtrl[i] = iLogsize;
  13812. /* Update allocator performance statistics. */
  13813. mem5.nAlloc++;
  13814. mem5.totalAlloc += iFullSz;
  13815. mem5.totalExcess += iFullSz - nByte;
  13816. mem5.currentCount++;
  13817. mem5.currentOut += iFullSz;
  13818. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  13819. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  13820. /* Return a pointer to the allocated memory. */
  13821. return (void*)&mem5.zPool[i*mem5.nAtom];
  13822. }
  13823. /*
  13824. ** Free an outstanding memory allocation.
  13825. */
  13826. static void memsys5FreeUnsafe(void *pOld){
  13827. u32 size, iLogsize;
  13828. int iBlock;
  13829. /* Set iBlock to the index of the block pointed to by pOld in
  13830. ** the array of mem5.nAtom byte blocks pointed to by mem5.zPool.
  13831. */
  13832. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.nAtom;
  13833. /* Check that the pointer pOld points to a valid, non-free block. */
  13834. assert( iBlock>=0 && iBlock<mem5.nBlock );
  13835. assert( ((u8 *)pOld-mem5.zPool)%mem5.nAtom==0 );
  13836. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  13837. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  13838. size = 1<<iLogsize;
  13839. assert( iBlock+size-1<(u32)mem5.nBlock );
  13840. mem5.aCtrl[iBlock] |= CTRL_FREE;
  13841. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  13842. assert( mem5.currentCount>0 );
  13843. assert( mem5.currentOut>=(size*mem5.nAtom) );
  13844. mem5.currentCount--;
  13845. mem5.currentOut -= size*mem5.nAtom;
  13846. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  13847. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  13848. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  13849. while( iLogsize<LOGMAX ){
  13850. int iBuddy;
  13851. if( (iBlock>>iLogsize) & 1 ){
  13852. iBuddy = iBlock - size;
  13853. }else{
  13854. iBuddy = iBlock + size;
  13855. }
  13856. assert( iBuddy>=0 );
  13857. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  13858. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  13859. memsys5Unlink(iBuddy, iLogsize);
  13860. iLogsize++;
  13861. if( iBuddy<iBlock ){
  13862. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  13863. mem5.aCtrl[iBlock] = 0;
  13864. iBlock = iBuddy;
  13865. }else{
  13866. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  13867. mem5.aCtrl[iBuddy] = 0;
  13868. }
  13869. size *= 2;
  13870. }
  13871. memsys5Link(iBlock, iLogsize);
  13872. }
  13873. /*
  13874. ** Allocate nBytes of memory
  13875. */
  13876. static void *memsys5Malloc(int nBytes){
  13877. sqlite3_int64 *p = 0;
  13878. if( nBytes>0 ){
  13879. memsys5Enter();
  13880. p = memsys5MallocUnsafe(nBytes);
  13881. memsys5Leave();
  13882. }
  13883. return (void*)p;
  13884. }
  13885. /*
  13886. ** Free memory.
  13887. */
  13888. static void memsys5Free(void *pPrior){
  13889. if( pPrior==0 ){
  13890. assert(0);
  13891. return;
  13892. }
  13893. memsys5Enter();
  13894. memsys5FreeUnsafe(pPrior);
  13895. memsys5Leave();
  13896. }
  13897. /*
  13898. ** Change the size of an existing memory allocation
  13899. */
  13900. static void *memsys5Realloc(void *pPrior, int nBytes){
  13901. int nOld;
  13902. void *p;
  13903. if( pPrior==0 ){
  13904. return memsys5Malloc(nBytes);
  13905. }
  13906. if( nBytes<=0 ){
  13907. memsys5Free(pPrior);
  13908. return 0;
  13909. }
  13910. nOld = memsys5Size(pPrior);
  13911. if( nBytes<=nOld ){
  13912. return pPrior;
  13913. }
  13914. memsys5Enter();
  13915. p = memsys5MallocUnsafe(nBytes);
  13916. if( p ){
  13917. memcpy(p, pPrior, nOld);
  13918. memsys5FreeUnsafe(pPrior);
  13919. }
  13920. memsys5Leave();
  13921. return p;
  13922. }
  13923. /*
  13924. ** Round up a request size to the next valid allocation size.
  13925. */
  13926. static int memsys5Roundup(int n){
  13927. int iFullSz;
  13928. for(iFullSz=mem5.nAtom; iFullSz<n; iFullSz *= 2);
  13929. return iFullSz;
  13930. }
  13931. static int memsys5Log(int iValue){
  13932. int iLog;
  13933. for(iLog=0; (1<<iLog)<iValue; iLog++);
  13934. return iLog;
  13935. }
  13936. /*
  13937. ** Initialize this module.
  13938. */
  13939. static int memsys5Init(void *NotUsed){
  13940. int ii;
  13941. int nByte = sqlite3GlobalConfig.nHeap;
  13942. u8 *zByte = (u8 *)sqlite3GlobalConfig.pHeap;
  13943. int nMinLog; /* Log of minimum allocation size in bytes*/
  13944. int iOffset;
  13945. UNUSED_PARAMETER(NotUsed);
  13946. if( !zByte ){
  13947. return SQLITE_ERROR;
  13948. }
  13949. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  13950. mem5.nAtom = (1<<nMinLog);
  13951. while( (int)sizeof(Mem5Link)>mem5.nAtom ){
  13952. mem5.nAtom = mem5.nAtom << 1;
  13953. }
  13954. mem5.nBlock = (nByte / (mem5.nAtom+sizeof(u8)));
  13955. mem5.zPool = zByte;
  13956. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.nAtom];
  13957. for(ii=0; ii<=LOGMAX; ii++){
  13958. mem5.aiFreelist[ii] = -1;
  13959. }
  13960. iOffset = 0;
  13961. for(ii=LOGMAX; ii>=0; ii--){
  13962. int nAlloc = (1<<ii);
  13963. if( (iOffset+nAlloc)<=mem5.nBlock ){
  13964. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  13965. memsys5Link(iOffset, ii);
  13966. iOffset += nAlloc;
  13967. }
  13968. assert((iOffset+nAlloc)>mem5.nBlock);
  13969. }
  13970. return SQLITE_OK;
  13971. }
  13972. /*
  13973. ** Deinitialize this module.
  13974. */
  13975. static void memsys5Shutdown(void *NotUsed){
  13976. UNUSED_PARAMETER(NotUsed);
  13977. return;
  13978. }
  13979. /*
  13980. ** Open the file indicated and write a log of all unfreed memory
  13981. ** allocations into that log.
  13982. */
  13983. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  13984. #ifdef SQLITE_DEBUG
  13985. FILE *out;
  13986. int i, j, n;
  13987. int nMinLog;
  13988. if( zFilename==0 || zFilename[0]==0 ){
  13989. out = stdout;
  13990. }else{
  13991. out = fopen(zFilename, "w");
  13992. if( out==0 ){
  13993. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  13994. zFilename);
  13995. return;
  13996. }
  13997. }
  13998. memsys5Enter();
  13999. nMinLog = memsys5Log(mem5.nAtom);
  14000. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  14001. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  14002. fprintf(out, "freelist items of size %d: %d\n", mem5.nAtom << i, n);
  14003. }
  14004. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  14005. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  14006. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  14007. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  14008. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  14009. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  14010. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  14011. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  14012. memsys5Leave();
  14013. if( out==stdout ){
  14014. fflush(stdout);
  14015. }else{
  14016. fclose(out);
  14017. }
  14018. #else
  14019. UNUSED_PARAMETER(zFilename);
  14020. #endif
  14021. }
  14022. /*
  14023. ** This routine is the only routine in this file with external
  14024. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  14025. ** struct populated with the memsys5 methods.
  14026. */
  14027. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  14028. static const sqlite3_mem_methods memsys5Methods = {
  14029. memsys5Malloc,
  14030. memsys5Free,
  14031. memsys5Realloc,
  14032. memsys5Size,
  14033. memsys5Roundup,
  14034. memsys5Init,
  14035. memsys5Shutdown,
  14036. 0
  14037. };
  14038. return &memsys5Methods;
  14039. }
  14040. #endif /* SQLITE_ENABLE_MEMSYS5 */
  14041. /************** End of mem5.c ************************************************/
  14042. /************** Begin file mutex.c *******************************************/
  14043. /*
  14044. ** 2007 August 14
  14045. **
  14046. ** The author disclaims copyright to this source code. In place of
  14047. ** a legal notice, here is a blessing:
  14048. **
  14049. ** May you do good and not evil.
  14050. ** May you find forgiveness for yourself and forgive others.
  14051. ** May you share freely, never taking more than you give.
  14052. **
  14053. *************************************************************************
  14054. ** This file contains the C functions that implement mutexes.
  14055. **
  14056. ** This file contains code that is common across all mutex implementations.
  14057. **
  14058. ** $Id: mutex.c,v 1.29 2008/10/07 15:25:48 drh Exp $
  14059. */
  14060. #ifndef SQLITE_MUTEX_OMIT
  14061. /*
  14062. ** Initialize the mutex system.
  14063. */
  14064. SQLITE_PRIVATE int sqlite3MutexInit(void){
  14065. int rc = SQLITE_OK;
  14066. if( sqlite3GlobalConfig.bCoreMutex ){
  14067. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  14068. /* If the xMutexAlloc method has not been set, then the user did not
  14069. ** install a mutex implementation via sqlite3_config() prior to
  14070. ** sqlite3_initialize() being called. This block copies pointers to
  14071. ** the default implementation into the sqlite3GlobalConfig structure.
  14072. **
  14073. ** The danger is that although sqlite3_config() is not a threadsafe
  14074. ** API, sqlite3_initialize() is, and so multiple threads may be
  14075. ** attempting to run this function simultaneously. To guard write
  14076. ** access to the sqlite3GlobalConfig structure, the 'MASTER' static mutex
  14077. ** is obtained before modifying it.
  14078. */
  14079. sqlite3_mutex_methods *p = sqlite3DefaultMutex();
  14080. sqlite3_mutex *pMaster = 0;
  14081. rc = p->xMutexInit();
  14082. if( rc==SQLITE_OK ){
  14083. pMaster = p->xMutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14084. assert(pMaster);
  14085. p->xMutexEnter(pMaster);
  14086. assert( sqlite3GlobalConfig.mutex.xMutexAlloc==0
  14087. || sqlite3GlobalConfig.mutex.xMutexAlloc==p->xMutexAlloc
  14088. );
  14089. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  14090. sqlite3GlobalConfig.mutex = *p;
  14091. }
  14092. p->xMutexLeave(pMaster);
  14093. }
  14094. }else{
  14095. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  14096. }
  14097. }
  14098. return rc;
  14099. }
  14100. /*
  14101. ** Shutdown the mutex system. This call frees resources allocated by
  14102. ** sqlite3MutexInit().
  14103. */
  14104. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  14105. int rc = SQLITE_OK;
  14106. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  14107. return rc;
  14108. }
  14109. /*
  14110. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  14111. */
  14112. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  14113. #ifndef SQLITE_OMIT_AUTOINIT
  14114. if( sqlite3_initialize() ) return 0;
  14115. #endif
  14116. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  14117. }
  14118. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  14119. if( !sqlite3GlobalConfig.bCoreMutex ){
  14120. return 0;
  14121. }
  14122. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  14123. }
  14124. /*
  14125. ** Free a dynamic mutex.
  14126. */
  14127. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  14128. if( p ){
  14129. sqlite3GlobalConfig.mutex.xMutexFree(p);
  14130. }
  14131. }
  14132. /*
  14133. ** Obtain the mutex p. If some other thread already has the mutex, block
  14134. ** until it can be obtained.
  14135. */
  14136. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  14137. if( p ){
  14138. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  14139. }
  14140. }
  14141. /*
  14142. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  14143. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  14144. */
  14145. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  14146. int rc = SQLITE_OK;
  14147. if( p ){
  14148. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  14149. }
  14150. return rc;
  14151. }
  14152. /*
  14153. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  14154. ** entered by the same thread. The behavior is undefined if the mutex
  14155. ** is not currently entered. If a NULL pointer is passed as an argument
  14156. ** this function is a no-op.
  14157. */
  14158. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  14159. if( p ){
  14160. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  14161. }
  14162. }
  14163. #ifndef NDEBUG
  14164. /*
  14165. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  14166. ** intended for use inside assert() statements.
  14167. */
  14168. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  14169. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  14170. }
  14171. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  14172. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  14173. }
  14174. #endif
  14175. #endif /* SQLITE_OMIT_MUTEX */
  14176. /************** End of mutex.c ***********************************************/
  14177. /************** Begin file mutex_noop.c **************************************/
  14178. /*
  14179. ** 2008 October 07
  14180. **
  14181. ** The author disclaims copyright to this source code. In place of
  14182. ** a legal notice, here is a blessing:
  14183. **
  14184. ** May you do good and not evil.
  14185. ** May you find forgiveness for yourself and forgive others.
  14186. ** May you share freely, never taking more than you give.
  14187. **
  14188. *************************************************************************
  14189. ** This file contains the C functions that implement mutexes.
  14190. **
  14191. ** This implementation in this file does not provide any mutual
  14192. ** exclusion and is thus suitable for use only in applications
  14193. ** that use SQLite in a single thread. The routines defined
  14194. ** here are place-holders. Applications can substitute working
  14195. ** mutex routines at start-time using the
  14196. **
  14197. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  14198. **
  14199. ** interface.
  14200. **
  14201. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  14202. ** that does error checking on mutexes to make sure they are being
  14203. ** called correctly.
  14204. **
  14205. ** $Id: mutex_noop.c,v 1.3 2008/12/05 17:17:08 drh Exp $
  14206. */
  14207. #if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
  14208. /*
  14209. ** Stub routines for all mutex methods.
  14210. **
  14211. ** This routines provide no mutual exclusion or error checking.
  14212. */
  14213. static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
  14214. static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
  14215. static int noopMutexInit(void){ return SQLITE_OK; }
  14216. static int noopMutexEnd(void){ return SQLITE_OK; }
  14217. static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
  14218. static void noopMutexFree(sqlite3_mutex *p){ return; }
  14219. static void noopMutexEnter(sqlite3_mutex *p){ return; }
  14220. static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
  14221. static void noopMutexLeave(sqlite3_mutex *p){ return; }
  14222. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  14223. static sqlite3_mutex_methods sMutex = {
  14224. noopMutexInit,
  14225. noopMutexEnd,
  14226. noopMutexAlloc,
  14227. noopMutexFree,
  14228. noopMutexEnter,
  14229. noopMutexTry,
  14230. noopMutexLeave,
  14231. noopMutexHeld,
  14232. noopMutexNotheld
  14233. };
  14234. return &sMutex;
  14235. }
  14236. #endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
  14237. #if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
  14238. /*
  14239. ** In this implementation, error checking is provided for testing
  14240. ** and debugging purposes. The mutexes still do not provide any
  14241. ** mutual exclusion.
  14242. */
  14243. /*
  14244. ** The mutex object
  14245. */
  14246. struct sqlite3_mutex {
  14247. int id; /* The mutex type */
  14248. int cnt; /* Number of entries without a matching leave */
  14249. };
  14250. /*
  14251. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  14252. ** intended for use inside assert() statements.
  14253. */
  14254. static int debugMutexHeld(sqlite3_mutex *p){
  14255. return p==0 || p->cnt>0;
  14256. }
  14257. static int debugMutexNotheld(sqlite3_mutex *p){
  14258. return p==0 || p->cnt==0;
  14259. }
  14260. /*
  14261. ** Initialize and deinitialize the mutex subsystem.
  14262. */
  14263. static int debugMutexInit(void){ return SQLITE_OK; }
  14264. static int debugMutexEnd(void){ return SQLITE_OK; }
  14265. /*
  14266. ** The sqlite3_mutex_alloc() routine allocates a new
  14267. ** mutex and returns a pointer to it. If it returns NULL
  14268. ** that means that a mutex could not be allocated.
  14269. */
  14270. static sqlite3_mutex *debugMutexAlloc(int id){
  14271. static sqlite3_mutex aStatic[6];
  14272. sqlite3_mutex *pNew = 0;
  14273. switch( id ){
  14274. case SQLITE_MUTEX_FAST:
  14275. case SQLITE_MUTEX_RECURSIVE: {
  14276. pNew = sqlite3Malloc(sizeof(*pNew));
  14277. if( pNew ){
  14278. pNew->id = id;
  14279. pNew->cnt = 0;
  14280. }
  14281. break;
  14282. }
  14283. default: {
  14284. assert( id-2 >= 0 );
  14285. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  14286. pNew = &aStatic[id-2];
  14287. pNew->id = id;
  14288. break;
  14289. }
  14290. }
  14291. return pNew;
  14292. }
  14293. /*
  14294. ** This routine deallocates a previously allocated mutex.
  14295. */
  14296. static void debugMutexFree(sqlite3_mutex *p){
  14297. assert( p->cnt==0 );
  14298. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  14299. sqlite3_free(p);
  14300. }
  14301. /*
  14302. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  14303. ** to enter a mutex. If another thread is already within the mutex,
  14304. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  14305. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  14306. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  14307. ** be entered multiple times by the same thread. In such cases the,
  14308. ** mutex must be exited an equal number of times before another thread
  14309. ** can enter. If the same thread tries to enter any other kind of mutex
  14310. ** more than once, the behavior is undefined.
  14311. */
  14312. static void debugMutexEnter(sqlite3_mutex *p){
  14313. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
  14314. p->cnt++;
  14315. }
  14316. static int debugMutexTry(sqlite3_mutex *p){
  14317. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
  14318. p->cnt++;
  14319. return SQLITE_OK;
  14320. }
  14321. /*
  14322. ** The sqlite3_mutex_leave() routine exits a mutex that was
  14323. ** previously entered by the same thread. The behavior
  14324. ** is undefined if the mutex is not currently entered or
  14325. ** is not currently allocated. SQLite will never do either.
  14326. */
  14327. static void debugMutexLeave(sqlite3_mutex *p){
  14328. assert( debugMutexHeld(p) );
  14329. p->cnt--;
  14330. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
  14331. }
  14332. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  14333. static sqlite3_mutex_methods sMutex = {
  14334. debugMutexInit,
  14335. debugMutexEnd,
  14336. debugMutexAlloc,
  14337. debugMutexFree,
  14338. debugMutexEnter,
  14339. debugMutexTry,
  14340. debugMutexLeave,
  14341. debugMutexHeld,
  14342. debugMutexNotheld
  14343. };
  14344. return &sMutex;
  14345. }
  14346. #endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
  14347. /************** End of mutex_noop.c ******************************************/
  14348. /************** Begin file mutex_os2.c ***************************************/
  14349. /*
  14350. ** 2007 August 28
  14351. **
  14352. ** The author disclaims copyright to this source code. In place of
  14353. ** a legal notice, here is a blessing:
  14354. **
  14355. ** May you do good and not evil.
  14356. ** May you find forgiveness for yourself and forgive others.
  14357. ** May you share freely, never taking more than you give.
  14358. **
  14359. *************************************************************************
  14360. ** This file contains the C functions that implement mutexes for OS/2
  14361. **
  14362. ** $Id: mutex_os2.c,v 1.11 2008/11/22 19:50:54 pweilbacher Exp $
  14363. */
  14364. /*
  14365. ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
  14366. ** See the mutex.h file for details.
  14367. */
  14368. #ifdef SQLITE_MUTEX_OS2
  14369. /********************** OS/2 Mutex Implementation **********************
  14370. **
  14371. ** This implementation of mutexes is built using the OS/2 API.
  14372. */
  14373. /*
  14374. ** The mutex object
  14375. ** Each recursive mutex is an instance of the following structure.
  14376. */
  14377. struct sqlite3_mutex {
  14378. HMTX mutex; /* Mutex controlling the lock */
  14379. int id; /* Mutex type */
  14380. int nRef; /* Number of references */
  14381. TID owner; /* Thread holding this mutex */
  14382. };
  14383. #define OS2_MUTEX_INITIALIZER 0,0,0,0
  14384. /*
  14385. ** Initialize and deinitialize the mutex subsystem.
  14386. */
  14387. static int os2MutexInit(void){ return SQLITE_OK; }
  14388. static int os2MutexEnd(void){ return SQLITE_OK; }
  14389. /*
  14390. ** The sqlite3_mutex_alloc() routine allocates a new
  14391. ** mutex and returns a pointer to it. If it returns NULL
  14392. ** that means that a mutex could not be allocated.
  14393. ** SQLite will unwind its stack and return an error. The argument
  14394. ** to sqlite3_mutex_alloc() is one of these integer constants:
  14395. **
  14396. ** <ul>
  14397. ** <li> SQLITE_MUTEX_FAST 0
  14398. ** <li> SQLITE_MUTEX_RECURSIVE 1
  14399. ** <li> SQLITE_MUTEX_STATIC_MASTER 2
  14400. ** <li> SQLITE_MUTEX_STATIC_MEM 3
  14401. ** <li> SQLITE_MUTEX_STATIC_PRNG 4
  14402. ** </ul>
  14403. **
  14404. ** The first two constants cause sqlite3_mutex_alloc() to create
  14405. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  14406. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  14407. ** The mutex implementation does not need to make a distinction
  14408. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  14409. ** not want to. But SQLite will only request a recursive mutex in
  14410. ** cases where it really needs one. If a faster non-recursive mutex
  14411. ** implementation is available on the host platform, the mutex subsystem
  14412. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  14413. **
  14414. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  14415. ** a pointer to a static preexisting mutex. Three static mutexes are
  14416. ** used by the current version of SQLite. Future versions of SQLite
  14417. ** may add additional static mutexes. Static mutexes are for internal
  14418. ** use by SQLite only. Applications that use SQLite mutexes should
  14419. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  14420. ** SQLITE_MUTEX_RECURSIVE.
  14421. **
  14422. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  14423. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  14424. ** returns a different mutex on every call. But for the static
  14425. ** mutex types, the same mutex is returned on every call that has
  14426. ** the same type number.
  14427. */
  14428. static sqlite3_mutex *os2MutexAlloc(int iType){
  14429. sqlite3_mutex *p = NULL;
  14430. switch( iType ){
  14431. case SQLITE_MUTEX_FAST:
  14432. case SQLITE_MUTEX_RECURSIVE: {
  14433. p = sqlite3MallocZero( sizeof(*p) );
  14434. if( p ){
  14435. p->id = iType;
  14436. if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
  14437. sqlite3_free( p );
  14438. p = NULL;
  14439. }
  14440. }
  14441. break;
  14442. }
  14443. default: {
  14444. static volatile int isInit = 0;
  14445. static sqlite3_mutex staticMutexes[] = {
  14446. { OS2_MUTEX_INITIALIZER, },
  14447. { OS2_MUTEX_INITIALIZER, },
  14448. { OS2_MUTEX_INITIALIZER, },
  14449. { OS2_MUTEX_INITIALIZER, },
  14450. { OS2_MUTEX_INITIALIZER, },
  14451. { OS2_MUTEX_INITIALIZER, },
  14452. };
  14453. if ( !isInit ){
  14454. APIRET rc;
  14455. PTIB ptib;
  14456. PPIB ppib;
  14457. HMTX mutex;
  14458. char name[32];
  14459. DosGetInfoBlocks( &ptib, &ppib );
  14460. sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
  14461. ppib->pib_ulpid );
  14462. while( !isInit ){
  14463. mutex = 0;
  14464. rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
  14465. if( rc == NO_ERROR ){
  14466. unsigned int i;
  14467. if( !isInit ){
  14468. for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
  14469. DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
  14470. }
  14471. isInit = 1;
  14472. }
  14473. DosCloseMutexSem( mutex );
  14474. }else if( rc == ERROR_DUPLICATE_NAME ){
  14475. DosSleep( 1 );
  14476. }else{
  14477. return p;
  14478. }
  14479. }
  14480. }
  14481. assert( iType-2 >= 0 );
  14482. assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
  14483. p = &staticMutexes[iType-2];
  14484. p->id = iType;
  14485. break;
  14486. }
  14487. }
  14488. return p;
  14489. }
  14490. /*
  14491. ** This routine deallocates a previously allocated mutex.
  14492. ** SQLite is careful to deallocate every mutex that it allocates.
  14493. */
  14494. static void os2MutexFree(sqlite3_mutex *p){
  14495. if( p==0 ) return;
  14496. assert( p->nRef==0 );
  14497. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  14498. DosCloseMutexSem( p->mutex );
  14499. sqlite3_free( p );
  14500. }
  14501. /*
  14502. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  14503. ** to enter a mutex. If another thread is already within the mutex,
  14504. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  14505. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  14506. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  14507. ** be entered multiple times by the same thread. In such cases the,
  14508. ** mutex must be exited an equal number of times before another thread
  14509. ** can enter. If the same thread tries to enter any other kind of mutex
  14510. ** more than once, the behavior is undefined.
  14511. */
  14512. static void os2MutexEnter(sqlite3_mutex *p){
  14513. TID tid;
  14514. PID holder1;
  14515. ULONG holder2;
  14516. if( p==0 ) return;
  14517. assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
  14518. DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
  14519. DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
  14520. p->owner = tid;
  14521. p->nRef++;
  14522. }
  14523. static int os2MutexTry(sqlite3_mutex *p){
  14524. int rc;
  14525. TID tid;
  14526. PID holder1;
  14527. ULONG holder2;
  14528. if( p==0 ) return SQLITE_OK;
  14529. assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
  14530. if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
  14531. DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
  14532. p->owner = tid;
  14533. p->nRef++;
  14534. rc = SQLITE_OK;
  14535. } else {
  14536. rc = SQLITE_BUSY;
  14537. }
  14538. return rc;
  14539. }
  14540. /*
  14541. ** The sqlite3_mutex_leave() routine exits a mutex that was
  14542. ** previously entered by the same thread. The behavior
  14543. ** is undefined if the mutex is not currently entered or
  14544. ** is not currently allocated. SQLite will never do either.
  14545. */
  14546. static void os2MutexLeave(sqlite3_mutex *p){
  14547. TID tid;
  14548. PID holder1;
  14549. ULONG holder2;
  14550. if( p==0 ) return;
  14551. assert( p->nRef>0 );
  14552. DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
  14553. assert( p->owner==tid );
  14554. p->nRef--;
  14555. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  14556. DosReleaseMutexSem(p->mutex);
  14557. }
  14558. #ifdef SQLITE_DEBUG
  14559. /*
  14560. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  14561. ** intended for use inside assert() statements.
  14562. */
  14563. static int os2MutexHeld(sqlite3_mutex *p){
  14564. TID tid;
  14565. PID pid;
  14566. ULONG ulCount;
  14567. PTIB ptib;
  14568. if( p!=0 ) {
  14569. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  14570. } else {
  14571. DosGetInfoBlocks(&ptib, NULL);
  14572. tid = ptib->tib_ptib2->tib2_ultid;
  14573. }
  14574. return p==0 || (p->nRef!=0 && p->owner==tid);
  14575. }
  14576. static int os2MutexNotheld(sqlite3_mutex *p){
  14577. TID tid;
  14578. PID pid;
  14579. ULONG ulCount;
  14580. PTIB ptib;
  14581. if( p!= 0 ) {
  14582. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  14583. } else {
  14584. DosGetInfoBlocks(&ptib, NULL);
  14585. tid = ptib->tib_ptib2->tib2_ultid;
  14586. }
  14587. return p==0 || p->nRef==0 || p->owner!=tid;
  14588. }
  14589. #endif
  14590. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  14591. static sqlite3_mutex_methods sMutex = {
  14592. os2MutexInit,
  14593. os2MutexEnd,
  14594. os2MutexAlloc,
  14595. os2MutexFree,
  14596. os2MutexEnter,
  14597. os2MutexTry,
  14598. os2MutexLeave,
  14599. #ifdef SQLITE_DEBUG
  14600. os2MutexHeld,
  14601. os2MutexNotheld
  14602. #endif
  14603. };
  14604. return &sMutex;
  14605. }
  14606. #endif /* SQLITE_MUTEX_OS2 */
  14607. /************** End of mutex_os2.c *******************************************/
  14608. /************** Begin file mutex_unix.c **************************************/
  14609. /*
  14610. ** 2007 August 28
  14611. **
  14612. ** The author disclaims copyright to this source code. In place of
  14613. ** a legal notice, here is a blessing:
  14614. **
  14615. ** May you do good and not evil.
  14616. ** May you find forgiveness for yourself and forgive others.
  14617. ** May you share freely, never taking more than you give.
  14618. **
  14619. *************************************************************************
  14620. ** This file contains the C functions that implement mutexes for pthreads
  14621. **
  14622. ** $Id: mutex_unix.c,v 1.16 2008/12/08 18:19:18 drh Exp $
  14623. */
  14624. /*
  14625. ** The code in this file is only used if we are compiling threadsafe
  14626. ** under unix with pthreads.
  14627. **
  14628. ** Note that this implementation requires a version of pthreads that
  14629. ** supports recursive mutexes.
  14630. */
  14631. #ifdef SQLITE_MUTEX_PTHREADS
  14632. #include <pthread.h>
  14633. /*
  14634. ** Each recursive mutex is an instance of the following structure.
  14635. */
  14636. struct sqlite3_mutex {
  14637. pthread_mutex_t mutex; /* Mutex controlling the lock */
  14638. int id; /* Mutex type */
  14639. int nRef; /* Number of entrances */
  14640. pthread_t owner; /* Thread that is within this mutex */
  14641. #ifdef SQLITE_DEBUG
  14642. int trace; /* True to trace changes */
  14643. #endif
  14644. };
  14645. #ifdef SQLITE_DEBUG
  14646. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  14647. #else
  14648. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
  14649. #endif
  14650. /*
  14651. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  14652. ** intended for use only inside assert() statements. On some platforms,
  14653. ** there might be race conditions that can cause these routines to
  14654. ** deliver incorrect results. In particular, if pthread_equal() is
  14655. ** not an atomic operation, then these routines might delivery
  14656. ** incorrect results. On most platforms, pthread_equal() is a
  14657. ** comparison of two integers and is therefore atomic. But we are
  14658. ** told that HPUX is not such a platform. If so, then these routines
  14659. ** will not always work correctly on HPUX.
  14660. **
  14661. ** On those platforms where pthread_equal() is not atomic, SQLite
  14662. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  14663. ** make sure no assert() statements are evaluated and hence these
  14664. ** routines are never called.
  14665. */
  14666. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  14667. static int pthreadMutexHeld(sqlite3_mutex *p){
  14668. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  14669. }
  14670. static int pthreadMutexNotheld(sqlite3_mutex *p){
  14671. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  14672. }
  14673. #endif
  14674. /*
  14675. ** Initialize and deinitialize the mutex subsystem.
  14676. */
  14677. static int pthreadMutexInit(void){ return SQLITE_OK; }
  14678. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  14679. /*
  14680. ** The sqlite3_mutex_alloc() routine allocates a new
  14681. ** mutex and returns a pointer to it. If it returns NULL
  14682. ** that means that a mutex could not be allocated. SQLite
  14683. ** will unwind its stack and return an error. The argument
  14684. ** to sqlite3_mutex_alloc() is one of these integer constants:
  14685. **
  14686. ** <ul>
  14687. ** <li> SQLITE_MUTEX_FAST
  14688. ** <li> SQLITE_MUTEX_RECURSIVE
  14689. ** <li> SQLITE_MUTEX_STATIC_MASTER
  14690. ** <li> SQLITE_MUTEX_STATIC_MEM
  14691. ** <li> SQLITE_MUTEX_STATIC_MEM2
  14692. ** <li> SQLITE_MUTEX_STATIC_PRNG
  14693. ** <li> SQLITE_MUTEX_STATIC_LRU
  14694. ** </ul>
  14695. **
  14696. ** The first two constants cause sqlite3_mutex_alloc() to create
  14697. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  14698. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  14699. ** The mutex implementation does not need to make a distinction
  14700. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  14701. ** not want to. But SQLite will only request a recursive mutex in
  14702. ** cases where it really needs one. If a faster non-recursive mutex
  14703. ** implementation is available on the host platform, the mutex subsystem
  14704. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  14705. **
  14706. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  14707. ** a pointer to a static preexisting mutex. Three static mutexes are
  14708. ** used by the current version of SQLite. Future versions of SQLite
  14709. ** may add additional static mutexes. Static mutexes are for internal
  14710. ** use by SQLite only. Applications that use SQLite mutexes should
  14711. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  14712. ** SQLITE_MUTEX_RECURSIVE.
  14713. **
  14714. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  14715. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  14716. ** returns a different mutex on every call. But for the static
  14717. ** mutex types, the same mutex is returned on every call that has
  14718. ** the same type number.
  14719. */
  14720. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  14721. static sqlite3_mutex staticMutexes[] = {
  14722. SQLITE3_MUTEX_INITIALIZER,
  14723. SQLITE3_MUTEX_INITIALIZER,
  14724. SQLITE3_MUTEX_INITIALIZER,
  14725. SQLITE3_MUTEX_INITIALIZER,
  14726. SQLITE3_MUTEX_INITIALIZER,
  14727. SQLITE3_MUTEX_INITIALIZER
  14728. };
  14729. sqlite3_mutex *p;
  14730. switch( iType ){
  14731. case SQLITE_MUTEX_RECURSIVE: {
  14732. p = sqlite3MallocZero( sizeof(*p) );
  14733. if( p ){
  14734. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  14735. /* If recursive mutexes are not available, we will have to
  14736. ** build our own. See below. */
  14737. pthread_mutex_init(&p->mutex, 0);
  14738. #else
  14739. /* Use a recursive mutex if it is available */
  14740. pthread_mutexattr_t recursiveAttr;
  14741. pthread_mutexattr_init(&recursiveAttr);
  14742. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  14743. pthread_mutex_init(&p->mutex, &recursiveAttr);
  14744. pthread_mutexattr_destroy(&recursiveAttr);
  14745. #endif
  14746. p->id = iType;
  14747. }
  14748. break;
  14749. }
  14750. case SQLITE_MUTEX_FAST: {
  14751. p = sqlite3MallocZero( sizeof(*p) );
  14752. if( p ){
  14753. p->id = iType;
  14754. pthread_mutex_init(&p->mutex, 0);
  14755. }
  14756. break;
  14757. }
  14758. default: {
  14759. assert( iType-2 >= 0 );
  14760. assert( iType-2 < ArraySize(staticMutexes) );
  14761. p = &staticMutexes[iType-2];
  14762. p->id = iType;
  14763. break;
  14764. }
  14765. }
  14766. return p;
  14767. }
  14768. /*
  14769. ** This routine deallocates a previously
  14770. ** allocated mutex. SQLite is careful to deallocate every
  14771. ** mutex that it allocates.
  14772. */
  14773. static void pthreadMutexFree(sqlite3_mutex *p){
  14774. assert( p->nRef==0 );
  14775. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  14776. pthread_mutex_destroy(&p->mutex);
  14777. sqlite3_free(p);
  14778. }
  14779. /*
  14780. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  14781. ** to enter a mutex. If another thread is already within the mutex,
  14782. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  14783. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  14784. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  14785. ** be entered multiple times by the same thread. In such cases the,
  14786. ** mutex must be exited an equal number of times before another thread
  14787. ** can enter. If the same thread tries to enter any other kind of mutex
  14788. ** more than once, the behavior is undefined.
  14789. */
  14790. static void pthreadMutexEnter(sqlite3_mutex *p){
  14791. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  14792. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  14793. /* If recursive mutexes are not available, then we have to grow
  14794. ** our own. This implementation assumes that pthread_equal()
  14795. ** is atomic - that it cannot be deceived into thinking self
  14796. ** and p->owner are equal if p->owner changes between two values
  14797. ** that are not equal to self while the comparison is taking place.
  14798. ** This implementation also assumes a coherent cache - that
  14799. ** separate processes cannot read different values from the same
  14800. ** address at the same time. If either of these two conditions
  14801. ** are not met, then the mutexes will fail and problems will result.
  14802. */
  14803. {
  14804. pthread_t self = pthread_self();
  14805. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  14806. p->nRef++;
  14807. }else{
  14808. pthread_mutex_lock(&p->mutex);
  14809. assert( p->nRef==0 );
  14810. p->owner = self;
  14811. p->nRef = 1;
  14812. }
  14813. }
  14814. #else
  14815. /* Use the built-in recursive mutexes if they are available.
  14816. */
  14817. pthread_mutex_lock(&p->mutex);
  14818. p->owner = pthread_self();
  14819. p->nRef++;
  14820. #endif
  14821. #ifdef SQLITE_DEBUG
  14822. if( p->trace ){
  14823. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  14824. }
  14825. #endif
  14826. }
  14827. static int pthreadMutexTry(sqlite3_mutex *p){
  14828. int rc;
  14829. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  14830. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  14831. /* If recursive mutexes are not available, then we have to grow
  14832. ** our own. This implementation assumes that pthread_equal()
  14833. ** is atomic - that it cannot be deceived into thinking self
  14834. ** and p->owner are equal if p->owner changes between two values
  14835. ** that are not equal to self while the comparison is taking place.
  14836. ** This implementation also assumes a coherent cache - that
  14837. ** separate processes cannot read different values from the same
  14838. ** address at the same time. If either of these two conditions
  14839. ** are not met, then the mutexes will fail and problems will result.
  14840. */
  14841. {
  14842. pthread_t self = pthread_self();
  14843. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  14844. p->nRef++;
  14845. rc = SQLITE_OK;
  14846. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  14847. assert( p->nRef==0 );
  14848. p->owner = self;
  14849. p->nRef = 1;
  14850. rc = SQLITE_OK;
  14851. }else{
  14852. rc = SQLITE_BUSY;
  14853. }
  14854. }
  14855. #else
  14856. /* Use the built-in recursive mutexes if they are available.
  14857. */
  14858. if( pthread_mutex_trylock(&p->mutex)==0 ){
  14859. p->owner = pthread_self();
  14860. p->nRef++;
  14861. rc = SQLITE_OK;
  14862. }else{
  14863. rc = SQLITE_BUSY;
  14864. }
  14865. #endif
  14866. #ifdef SQLITE_DEBUG
  14867. if( rc==SQLITE_OK && p->trace ){
  14868. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  14869. }
  14870. #endif
  14871. return rc;
  14872. }
  14873. /*
  14874. ** The sqlite3_mutex_leave() routine exits a mutex that was
  14875. ** previously entered by the same thread. The behavior
  14876. ** is undefined if the mutex is not currently entered or
  14877. ** is not currently allocated. SQLite will never do either.
  14878. */
  14879. static void pthreadMutexLeave(sqlite3_mutex *p){
  14880. assert( pthreadMutexHeld(p) );
  14881. p->nRef--;
  14882. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  14883. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  14884. if( p->nRef==0 ){
  14885. pthread_mutex_unlock(&p->mutex);
  14886. }
  14887. #else
  14888. pthread_mutex_unlock(&p->mutex);
  14889. #endif
  14890. #ifdef SQLITE_DEBUG
  14891. if( p->trace ){
  14892. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  14893. }
  14894. #endif
  14895. }
  14896. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  14897. static sqlite3_mutex_methods sMutex = {
  14898. pthreadMutexInit,
  14899. pthreadMutexEnd,
  14900. pthreadMutexAlloc,
  14901. pthreadMutexFree,
  14902. pthreadMutexEnter,
  14903. pthreadMutexTry,
  14904. pthreadMutexLeave,
  14905. #ifdef SQLITE_DEBUG
  14906. pthreadMutexHeld,
  14907. pthreadMutexNotheld
  14908. #else
  14909. 0,
  14910. 0
  14911. #endif
  14912. };
  14913. return &sMutex;
  14914. }
  14915. #endif /* SQLITE_MUTEX_PTHREAD */
  14916. /************** End of mutex_unix.c ******************************************/
  14917. /************** Begin file mutex_w32.c ***************************************/
  14918. /*
  14919. ** 2007 August 14
  14920. **
  14921. ** The author disclaims copyright to this source code. In place of
  14922. ** a legal notice, here is a blessing:
  14923. **
  14924. ** May you do good and not evil.
  14925. ** May you find forgiveness for yourself and forgive others.
  14926. ** May you share freely, never taking more than you give.
  14927. **
  14928. *************************************************************************
  14929. ** This file contains the C functions that implement mutexes for win32
  14930. **
  14931. ** $Id: mutex_w32.c,v 1.13 2008/12/08 18:19:18 drh Exp $
  14932. */
  14933. /*
  14934. ** The code in this file is only used if we are compiling multithreaded
  14935. ** on a win32 system.
  14936. */
  14937. #ifdef SQLITE_MUTEX_W32
  14938. /*
  14939. ** Each recursive mutex is an instance of the following structure.
  14940. */
  14941. struct sqlite3_mutex {
  14942. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  14943. int id; /* Mutex type */
  14944. int nRef; /* Number of enterances */
  14945. DWORD owner; /* Thread holding this mutex */
  14946. };
  14947. /*
  14948. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  14949. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  14950. **
  14951. ** Here is an interesting observation: Win95, Win98, and WinME lack
  14952. ** the LockFileEx() API. But we can still statically link against that
  14953. ** API as long as we don't call it win running Win95/98/ME. A call to
  14954. ** this routine is used to determine if the host is Win95/98/ME or
  14955. ** WinNT/2K/XP so that we will know whether or not we can safely call
  14956. ** the LockFileEx() API.
  14957. **
  14958. ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
  14959. ** which is only available if your application was compiled with
  14960. ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
  14961. ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
  14962. ** this out as well.
  14963. */
  14964. #if 0
  14965. #if SQLITE_OS_WINCE
  14966. # define mutexIsNT() (1)
  14967. #else
  14968. static int mutexIsNT(void){
  14969. static int osType = 0;
  14970. if( osType==0 ){
  14971. OSVERSIONINFO sInfo;
  14972. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  14973. GetVersionEx(&sInfo);
  14974. osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  14975. }
  14976. return osType==2;
  14977. }
  14978. #endif /* SQLITE_OS_WINCE */
  14979. #endif
  14980. #ifdef SQLITE_DEBUG
  14981. /*
  14982. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  14983. ** intended for use only inside assert() statements.
  14984. */
  14985. static int winMutexHeld(sqlite3_mutex *p){
  14986. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  14987. }
  14988. static int winMutexNotheld(sqlite3_mutex *p){
  14989. return p->nRef==0 || p->owner!=GetCurrentThreadId();
  14990. }
  14991. #endif
  14992. /*
  14993. ** Initialize and deinitialize the mutex subsystem.
  14994. */
  14995. static int winMutexInit(void){ return SQLITE_OK; }
  14996. static int winMutexEnd(void){ return SQLITE_OK; }
  14997. /*
  14998. ** The sqlite3_mutex_alloc() routine allocates a new
  14999. ** mutex and returns a pointer to it. If it returns NULL
  15000. ** that means that a mutex could not be allocated. SQLite
  15001. ** will unwind its stack and return an error. The argument
  15002. ** to sqlite3_mutex_alloc() is one of these integer constants:
  15003. **
  15004. ** <ul>
  15005. ** <li> SQLITE_MUTEX_FAST 0
  15006. ** <li> SQLITE_MUTEX_RECURSIVE 1
  15007. ** <li> SQLITE_MUTEX_STATIC_MASTER 2
  15008. ** <li> SQLITE_MUTEX_STATIC_MEM 3
  15009. ** <li> SQLITE_MUTEX_STATIC_PRNG 4
  15010. ** </ul>
  15011. **
  15012. ** The first two constants cause sqlite3_mutex_alloc() to create
  15013. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  15014. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  15015. ** The mutex implementation does not need to make a distinction
  15016. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  15017. ** not want to. But SQLite will only request a recursive mutex in
  15018. ** cases where it really needs one. If a faster non-recursive mutex
  15019. ** implementation is available on the host platform, the mutex subsystem
  15020. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  15021. **
  15022. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  15023. ** a pointer to a static preexisting mutex. Three static mutexes are
  15024. ** used by the current version of SQLite. Future versions of SQLite
  15025. ** may add additional static mutexes. Static mutexes are for internal
  15026. ** use by SQLite only. Applications that use SQLite mutexes should
  15027. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  15028. ** SQLITE_MUTEX_RECURSIVE.
  15029. **
  15030. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  15031. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  15032. ** returns a different mutex on every call. But for the static
  15033. ** mutex types, the same mutex is returned on every call that has
  15034. ** the same type number.
  15035. */
  15036. static sqlite3_mutex *winMutexAlloc(int iType){
  15037. sqlite3_mutex *p;
  15038. switch( iType ){
  15039. case SQLITE_MUTEX_FAST:
  15040. case SQLITE_MUTEX_RECURSIVE: {
  15041. p = sqlite3MallocZero( sizeof(*p) );
  15042. if( p ){
  15043. p->id = iType;
  15044. InitializeCriticalSection(&p->mutex);
  15045. }
  15046. break;
  15047. }
  15048. default: {
  15049. static sqlite3_mutex staticMutexes[6];
  15050. static int isInit = 0;
  15051. while( !isInit ){
  15052. static long lock = 0;
  15053. if( InterlockedIncrement(&lock)==1 ){
  15054. int i;
  15055. for(i=0; i<sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++){
  15056. InitializeCriticalSection(&staticMutexes[i].mutex);
  15057. }
  15058. isInit = 1;
  15059. }else{
  15060. Sleep(1);
  15061. }
  15062. }
  15063. assert( iType-2 >= 0 );
  15064. assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
  15065. p = &staticMutexes[iType-2];
  15066. p->id = iType;
  15067. break;
  15068. }
  15069. }
  15070. return p;
  15071. }
  15072. /*
  15073. ** This routine deallocates a previously
  15074. ** allocated mutex. SQLite is careful to deallocate every
  15075. ** mutex that it allocates.
  15076. */
  15077. static void winMutexFree(sqlite3_mutex *p){
  15078. assert( p );
  15079. assert( p->nRef==0 );
  15080. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  15081. DeleteCriticalSection(&p->mutex);
  15082. sqlite3_free(p);
  15083. }
  15084. /*
  15085. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  15086. ** to enter a mutex. If another thread is already within the mutex,
  15087. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  15088. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  15089. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  15090. ** be entered multiple times by the same thread. In such cases the,
  15091. ** mutex must be exited an equal number of times before another thread
  15092. ** can enter. If the same thread tries to enter any other kind of mutex
  15093. ** more than once, the behavior is undefined.
  15094. */
  15095. static void winMutexEnter(sqlite3_mutex *p){
  15096. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
  15097. EnterCriticalSection(&p->mutex);
  15098. p->owner = GetCurrentThreadId();
  15099. p->nRef++;
  15100. }
  15101. static int winMutexTry(sqlite3_mutex *p){
  15102. int rc = SQLITE_BUSY;
  15103. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
  15104. /*
  15105. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  15106. ** is used it is merely an optimization. So it is OK for it to always
  15107. ** fail.
  15108. **
  15109. ** The TryEnterCriticalSection() interface is only available on WinNT.
  15110. ** And some windows compilers complain if you try to use it without
  15111. ** first doing some #defines that prevent SQLite from building on Win98.
  15112. ** For that reason, we will omit this optimization for now. See
  15113. ** ticket #2685.
  15114. */
  15115. #if 0
  15116. if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
  15117. p->owner = GetCurrentThreadId();
  15118. p->nRef++;
  15119. rc = SQLITE_OK;
  15120. }
  15121. #endif
  15122. return rc;
  15123. }
  15124. /*
  15125. ** The sqlite3_mutex_leave() routine exits a mutex that was
  15126. ** previously entered by the same thread. The behavior
  15127. ** is undefined if the mutex is not currently entered or
  15128. ** is not currently allocated. SQLite will never do either.
  15129. */
  15130. static void winMutexLeave(sqlite3_mutex *p){
  15131. assert( p->nRef>0 );
  15132. assert( p->owner==GetCurrentThreadId() );
  15133. p->nRef--;
  15134. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  15135. LeaveCriticalSection(&p->mutex);
  15136. }
  15137. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  15138. static sqlite3_mutex_methods sMutex = {
  15139. winMutexInit,
  15140. winMutexEnd,
  15141. winMutexAlloc,
  15142. winMutexFree,
  15143. winMutexEnter,
  15144. winMutexTry,
  15145. winMutexLeave,
  15146. #ifdef SQLITE_DEBUG
  15147. winMutexHeld,
  15148. winMutexNotheld
  15149. #else
  15150. 0,
  15151. 0
  15152. #endif
  15153. };
  15154. return &sMutex;
  15155. }
  15156. #endif /* SQLITE_MUTEX_W32 */
  15157. /************** End of mutex_w32.c *******************************************/
  15158. /************** Begin file malloc.c ******************************************/
  15159. /*
  15160. ** 2001 September 15
  15161. **
  15162. ** The author disclaims copyright to this source code. In place of
  15163. ** a legal notice, here is a blessing:
  15164. **
  15165. ** May you do good and not evil.
  15166. ** May you find forgiveness for yourself and forgive others.
  15167. ** May you share freely, never taking more than you give.
  15168. **
  15169. *************************************************************************
  15170. **
  15171. ** Memory allocation functions used throughout sqlite.
  15172. **
  15173. ** $Id: malloc.c,v 1.53 2008/12/16 17:20:38 shane Exp $
  15174. */
  15175. /*
  15176. ** This routine runs when the memory allocator sees that the
  15177. ** total memory allocation is about to exceed the soft heap
  15178. ** limit.
  15179. */
  15180. static void softHeapLimitEnforcer(
  15181. void *NotUsed,
  15182. sqlite3_int64 NotUsed2,
  15183. int allocSize
  15184. ){
  15185. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15186. sqlite3_release_memory(allocSize);
  15187. }
  15188. /*
  15189. ** Set the soft heap-size limit for the library. Passing a zero or
  15190. ** negative value indicates no limit.
  15191. */
  15192. SQLITE_API void sqlite3_soft_heap_limit(int n){
  15193. sqlite3_uint64 iLimit;
  15194. int overage;
  15195. if( n<0 ){
  15196. iLimit = 0;
  15197. }else{
  15198. iLimit = n;
  15199. }
  15200. sqlite3_initialize();
  15201. if( iLimit>0 ){
  15202. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
  15203. }else{
  15204. sqlite3MemoryAlarm(0, 0, 0);
  15205. }
  15206. overage = (int)(sqlite3_memory_used() - (i64)n);
  15207. if( overage>0 ){
  15208. sqlite3_release_memory(overage);
  15209. }
  15210. }
  15211. /*
  15212. ** Attempt to release up to n bytes of non-essential memory currently
  15213. ** held by SQLite. An example of non-essential memory is memory used to
  15214. ** cache database pages that are not currently in use.
  15215. */
  15216. SQLITE_API int sqlite3_release_memory(int n){
  15217. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  15218. int nRet = 0;
  15219. #if 0
  15220. nRet += sqlite3VdbeReleaseMemory(n);
  15221. #endif
  15222. nRet += sqlite3PcacheReleaseMemory(n-nRet);
  15223. return nRet;
  15224. #else
  15225. UNUSED_PARAMETER(n);
  15226. return SQLITE_OK;
  15227. #endif
  15228. }
  15229. /*
  15230. ** State information local to the memory allocation subsystem.
  15231. */
  15232. static SQLITE_WSD struct Mem0Global {
  15233. /* Number of free pages for scratch and page-cache memory */
  15234. u32 nScratchFree;
  15235. u32 nPageFree;
  15236. sqlite3_mutex *mutex; /* Mutex to serialize access */
  15237. /*
  15238. ** The alarm callback and its arguments. The mem0.mutex lock will
  15239. ** be held while the callback is running. Recursive calls into
  15240. ** the memory subsystem are allowed, but no new callbacks will be
  15241. ** issued. The alarmBusy variable is set to prevent recursive
  15242. ** callbacks.
  15243. */
  15244. sqlite3_int64 alarmThreshold;
  15245. void (*alarmCallback)(void*, sqlite3_int64,int);
  15246. void *alarmArg;
  15247. int alarmBusy;
  15248. /*
  15249. ** Pointers to the end of sqlite3GlobalConfig.pScratch and
  15250. ** sqlite3GlobalConfig.pPage to a block of memory that records
  15251. ** which pages are available.
  15252. */
  15253. u32 *aScratchFree;
  15254. u32 *aPageFree;
  15255. } mem0 = { 62560955, 0, 0, 0, 0, 0, 0, 0, 0 };
  15256. #define mem0 GLOBAL(struct Mem0Global, mem0)
  15257. /*
  15258. ** Initialize the memory allocation subsystem.
  15259. */
  15260. SQLITE_PRIVATE int sqlite3MallocInit(void){
  15261. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  15262. sqlite3MemSetDefault();
  15263. }
  15264. memset(&mem0, 0, sizeof(mem0));
  15265. if( sqlite3GlobalConfig.bCoreMutex ){
  15266. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15267. }
  15268. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  15269. && sqlite3GlobalConfig.nScratch>=0 ){
  15270. int i;
  15271. sqlite3GlobalConfig.szScratch = (sqlite3GlobalConfig.szScratch - 4) & ~7;
  15272. mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
  15273. [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
  15274. for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
  15275. mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
  15276. }else{
  15277. sqlite3GlobalConfig.pScratch = 0;
  15278. sqlite3GlobalConfig.szScratch = 0;
  15279. }
  15280. if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
  15281. && sqlite3GlobalConfig.nPage>=1 ){
  15282. int i;
  15283. int overhead;
  15284. int sz = sqlite3GlobalConfig.szPage & ~7;
  15285. int n = sqlite3GlobalConfig.nPage;
  15286. overhead = (4*n + sz - 1)/sz;
  15287. sqlite3GlobalConfig.nPage -= overhead;
  15288. mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
  15289. [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
  15290. for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
  15291. mem0.nPageFree = sqlite3GlobalConfig.nPage;
  15292. }else{
  15293. sqlite3GlobalConfig.pPage = 0;
  15294. sqlite3GlobalConfig.szPage = 0;
  15295. }
  15296. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  15297. }
  15298. /*
  15299. ** Deinitialize the memory allocation subsystem.
  15300. */
  15301. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  15302. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  15303. memset(&mem0, 0, sizeof(mem0));
  15304. }
  15305. /*
  15306. ** Return the amount of memory currently checked out.
  15307. */
  15308. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  15309. int n, mx;
  15310. sqlite3_int64 res;
  15311. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  15312. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  15313. return res;
  15314. }
  15315. /*
  15316. ** Return the maximum amount of memory that has ever been
  15317. ** checked out since either the beginning of this process
  15318. ** or since the most recent reset.
  15319. */
  15320. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  15321. int n, mx;
  15322. sqlite3_int64 res;
  15323. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  15324. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  15325. return res;
  15326. }
  15327. /*
  15328. ** Change the alarm callback
  15329. */
  15330. SQLITE_PRIVATE int sqlite3MemoryAlarm(
  15331. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  15332. void *pArg,
  15333. sqlite3_int64 iThreshold
  15334. ){
  15335. sqlite3_mutex_enter(mem0.mutex);
  15336. mem0.alarmCallback = xCallback;
  15337. mem0.alarmArg = pArg;
  15338. mem0.alarmThreshold = iThreshold;
  15339. sqlite3_mutex_leave(mem0.mutex);
  15340. return SQLITE_OK;
  15341. }
  15342. #ifndef SQLITE_OMIT_DEPRECATED
  15343. /*
  15344. ** Deprecated external interface. Internal/core SQLite code
  15345. ** should call sqlite3MemoryAlarm.
  15346. */
  15347. SQLITE_API int sqlite3_memory_alarm(
  15348. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  15349. void *pArg,
  15350. sqlite3_int64 iThreshold
  15351. ){
  15352. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  15353. }
  15354. #endif
  15355. /*
  15356. ** Trigger the alarm
  15357. */
  15358. static void sqlite3MallocAlarm(int nByte){
  15359. void (*xCallback)(void*,sqlite3_int64,int);
  15360. sqlite3_int64 nowUsed;
  15361. void *pArg;
  15362. if( mem0.alarmCallback==0 || mem0.alarmBusy ) return;
  15363. mem0.alarmBusy = 1;
  15364. xCallback = mem0.alarmCallback;
  15365. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  15366. pArg = mem0.alarmArg;
  15367. sqlite3_mutex_leave(mem0.mutex);
  15368. xCallback(pArg, nowUsed, nByte);
  15369. sqlite3_mutex_enter(mem0.mutex);
  15370. mem0.alarmBusy = 0;
  15371. }
  15372. /*
  15373. ** Do a memory allocation with statistics and alarms. Assume the
  15374. ** lock is already held.
  15375. */
  15376. static int mallocWithAlarm(int n, void **pp){
  15377. int nFull;
  15378. void *p;
  15379. assert( sqlite3_mutex_held(mem0.mutex) );
  15380. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  15381. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  15382. if( mem0.alarmCallback!=0 ){
  15383. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  15384. if( nUsed+nFull >= mem0.alarmThreshold ){
  15385. sqlite3MallocAlarm(nFull);
  15386. }
  15387. }
  15388. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  15389. if( p==0 && mem0.alarmCallback ){
  15390. sqlite3MallocAlarm(nFull);
  15391. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  15392. }
  15393. if( p ){
  15394. nFull = sqlite3MallocSize(p);
  15395. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  15396. }
  15397. *pp = p;
  15398. return nFull;
  15399. }
  15400. /*
  15401. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  15402. ** assumes the memory subsystem has already been initialized.
  15403. */
  15404. SQLITE_PRIVATE void *sqlite3Malloc(int n){
  15405. void *p;
  15406. if( n<=0 ){
  15407. p = 0;
  15408. }else if( sqlite3GlobalConfig.bMemstat ){
  15409. sqlite3_mutex_enter(mem0.mutex);
  15410. mallocWithAlarm(n, &p);
  15411. sqlite3_mutex_leave(mem0.mutex);
  15412. }else{
  15413. p = sqlite3GlobalConfig.m.xMalloc(n);
  15414. }
  15415. return p;
  15416. }
  15417. /*
  15418. ** This version of the memory allocation is for use by the application.
  15419. ** First make sure the memory subsystem is initialized, then do the
  15420. ** allocation.
  15421. */
  15422. SQLITE_API void *sqlite3_malloc(int n){
  15423. #ifndef SQLITE_OMIT_AUTOINIT
  15424. if( sqlite3_initialize() ) return 0;
  15425. #endif
  15426. return sqlite3Malloc(n);
  15427. }
  15428. /*
  15429. ** Each thread may only have a single outstanding allocation from
  15430. ** xScratchMalloc(). We verify this constraint in the single-threaded
  15431. ** case by setting scratchAllocOut to 1 when an allocation
  15432. ** is outstanding clearing it when the allocation is freed.
  15433. */
  15434. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  15435. static int scratchAllocOut = 0;
  15436. #endif
  15437. /*
  15438. ** Allocate memory that is to be used and released right away.
  15439. ** This routine is similar to alloca() in that it is not intended
  15440. ** for situations where the memory might be held long-term. This
  15441. ** routine is intended to get memory to old large transient data
  15442. ** structures that would not normally fit on the stack of an
  15443. ** embedded processor.
  15444. */
  15445. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  15446. void *p;
  15447. assert( n>0 );
  15448. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  15449. /* Verify that no more than one scratch allocation per thread
  15450. ** is outstanding at one time. (This is only checked in the
  15451. ** single-threaded case since checking in the multi-threaded case
  15452. ** would be much more complicated.) */
  15453. assert( scratchAllocOut==0 );
  15454. #endif
  15455. if( sqlite3GlobalConfig.szScratch<n ){
  15456. goto scratch_overflow;
  15457. }else{
  15458. sqlite3_mutex_enter(mem0.mutex);
  15459. if( mem0.nScratchFree==0 ){
  15460. sqlite3_mutex_leave(mem0.mutex);
  15461. goto scratch_overflow;
  15462. }else{
  15463. int i;
  15464. i = mem0.aScratchFree[--mem0.nScratchFree];
  15465. i *= sqlite3GlobalConfig.szScratch;
  15466. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  15467. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  15468. sqlite3_mutex_leave(mem0.mutex);
  15469. p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
  15470. assert( (((u8*)p - (u8*)0) & 7)==0 );
  15471. }
  15472. }
  15473. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  15474. scratchAllocOut = p!=0;
  15475. #endif
  15476. return p;
  15477. scratch_overflow:
  15478. if( sqlite3GlobalConfig.bMemstat ){
  15479. sqlite3_mutex_enter(mem0.mutex);
  15480. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  15481. n = mallocWithAlarm(n, &p);
  15482. if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
  15483. sqlite3_mutex_leave(mem0.mutex);
  15484. }else{
  15485. p = sqlite3GlobalConfig.m.xMalloc(n);
  15486. }
  15487. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  15488. scratchAllocOut = p!=0;
  15489. #endif
  15490. return p;
  15491. }
  15492. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  15493. if( p ){
  15494. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  15495. /* Verify that no more than one scratch allocation per thread
  15496. ** is outstanding at one time. (This is only checked in the
  15497. ** single-threaded case since checking in the multi-threaded case
  15498. ** would be much more complicated.) */
  15499. assert( scratchAllocOut==1 );
  15500. scratchAllocOut = 0;
  15501. #endif
  15502. if( sqlite3GlobalConfig.pScratch==0
  15503. || p<sqlite3GlobalConfig.pScratch
  15504. || p>=(void*)mem0.aScratchFree ){
  15505. if( sqlite3GlobalConfig.bMemstat ){
  15506. int iSize = sqlite3MallocSize(p);
  15507. sqlite3_mutex_enter(mem0.mutex);
  15508. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  15509. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  15510. sqlite3GlobalConfig.m.xFree(p);
  15511. sqlite3_mutex_leave(mem0.mutex);
  15512. }else{
  15513. sqlite3GlobalConfig.m.xFree(p);
  15514. }
  15515. }else{
  15516. int i;
  15517. i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
  15518. i /= sqlite3GlobalConfig.szScratch;
  15519. assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
  15520. sqlite3_mutex_enter(mem0.mutex);
  15521. assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
  15522. mem0.aScratchFree[mem0.nScratchFree++] = i;
  15523. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  15524. sqlite3_mutex_leave(mem0.mutex);
  15525. }
  15526. }
  15527. }
  15528. /*
  15529. ** Allocate memory to be used by the page cache. Make use of the
  15530. ** memory buffer provided by SQLITE_CONFIG_PAGECACHE if there is one
  15531. ** and that memory is of the right size and is not completely
  15532. ** consumed. Otherwise, failover to sqlite3Malloc().
  15533. */
  15534. #if 0
  15535. SQLITE_PRIVATE void *sqlite3PageMalloc(int n){
  15536. void *p;
  15537. assert( n>0 );
  15538. assert( (n & (n-1))==0 );
  15539. assert( n>=512 && n<=32768 );
  15540. if( sqlite3GlobalConfig.szPage<n ){
  15541. goto page_overflow;
  15542. }else{
  15543. sqlite3_mutex_enter(mem0.mutex);
  15544. if( mem0.nPageFree==0 ){
  15545. sqlite3_mutex_leave(mem0.mutex);
  15546. goto page_overflow;
  15547. }else{
  15548. int i;
  15549. i = mem0.aPageFree[--mem0.nPageFree];
  15550. sqlite3_mutex_leave(mem0.mutex);
  15551. i *= sqlite3GlobalConfig.szPage;
  15552. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
  15553. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  15554. p = (void*)&((char*)sqlite3GlobalConfig.pPage)[i];
  15555. }
  15556. }
  15557. return p;
  15558. page_overflow:
  15559. if( sqlite3GlobalConfig.bMemstat ){
  15560. sqlite3_mutex_enter(mem0.mutex);
  15561. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
  15562. n = mallocWithAlarm(n, &p);
  15563. if( p ) sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, n);
  15564. sqlite3_mutex_leave(mem0.mutex);
  15565. }else{
  15566. p = sqlite3GlobalConfig.m.xMalloc(n);
  15567. }
  15568. return p;
  15569. }
  15570. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  15571. if( p ){
  15572. if( sqlite3GlobalConfig.pPage==0
  15573. || p<sqlite3GlobalConfig.pPage
  15574. || p>=(void*)mem0.aPageFree ){
  15575. /* In this case, the page allocation was obtained from a regular
  15576. ** call to sqlite3_mem_methods.xMalloc() (a page-cache-memory
  15577. ** "overflow"). Free the block with sqlite3_mem_methods.xFree().
  15578. */
  15579. if( sqlite3GlobalConfig.bMemstat ){
  15580. int iSize = sqlite3MallocSize(p);
  15581. sqlite3_mutex_enter(mem0.mutex);
  15582. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
  15583. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  15584. sqlite3GlobalConfig.m.xFree(p);
  15585. sqlite3_mutex_leave(mem0.mutex);
  15586. }else{
  15587. sqlite3GlobalConfig.m.xFree(p);
  15588. }
  15589. }else{
  15590. /* The page allocation was allocated from the sqlite3GlobalConfig.pPage
  15591. ** buffer. In this case all that is add the index of the page in
  15592. ** the sqlite3GlobalConfig.pPage array to the set of free indexes stored
  15593. ** in the mem0.aPageFree[] array.
  15594. */
  15595. int i;
  15596. i = (u8 *)p - (u8 *)sqlite3GlobalConfig.pPage;
  15597. i /= sqlite3GlobalConfig.szPage;
  15598. assert( i>=0 && i<sqlite3GlobalConfig.nPage );
  15599. sqlite3_mutex_enter(mem0.mutex);
  15600. assert( mem0.nPageFree<sqlite3GlobalConfig.nPage );
  15601. mem0.aPageFree[mem0.nPageFree++] = i;
  15602. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  15603. sqlite3_mutex_leave(mem0.mutex);
  15604. #if !defined(NDEBUG) && 0
  15605. /* Assert that a duplicate was not just inserted into aPageFree[]. */
  15606. for(i=0; i<mem0.nPageFree-1; i++){
  15607. assert( mem0.aPageFree[i]!=mem0.aPageFree[mem0.nPageFree-1] );
  15608. }
  15609. #endif
  15610. }
  15611. }
  15612. }
  15613. #endif
  15614. /*
  15615. ** TRUE if p is a lookaside memory allocation from db
  15616. */
  15617. #ifndef SQLITE_OMIT_LOOKASIDE
  15618. static int isLookaside(sqlite3 *db, void *p){
  15619. return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  15620. }
  15621. #else
  15622. #define isLookaside(A,B) 0
  15623. #endif
  15624. /*
  15625. ** Return the size of a memory allocation previously obtained from
  15626. ** sqlite3Malloc() or sqlite3_malloc().
  15627. */
  15628. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  15629. return sqlite3GlobalConfig.m.xSize(p);
  15630. }
  15631. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  15632. if( p==0 ){
  15633. return 0;
  15634. }else if( isLookaside(db, p) ){
  15635. return db->lookaside.sz;
  15636. }else{
  15637. return sqlite3GlobalConfig.m.xSize(p);
  15638. }
  15639. }
  15640. /*
  15641. ** Free memory previously obtained from sqlite3Malloc().
  15642. */
  15643. SQLITE_API void sqlite3_free(void *p){
  15644. if( p==0 ) return;
  15645. if( sqlite3GlobalConfig.bMemstat ){
  15646. sqlite3_mutex_enter(mem0.mutex);
  15647. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  15648. sqlite3GlobalConfig.m.xFree(p);
  15649. sqlite3_mutex_leave(mem0.mutex);
  15650. }else{
  15651. sqlite3GlobalConfig.m.xFree(p);
  15652. }
  15653. }
  15654. /*
  15655. ** Free memory that might be associated with a particular database
  15656. ** connection.
  15657. */
  15658. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  15659. if( isLookaside(db, p) ){
  15660. LookasideSlot *pBuf = (LookasideSlot*)p;
  15661. pBuf->pNext = db->lookaside.pFree;
  15662. db->lookaside.pFree = pBuf;
  15663. db->lookaside.nOut--;
  15664. }else{
  15665. sqlite3_free(p);
  15666. }
  15667. }
  15668. /*
  15669. ** Change the size of an existing memory allocation
  15670. */
  15671. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
  15672. int nOld, nNew;
  15673. void *pNew;
  15674. if( pOld==0 ){
  15675. return sqlite3Malloc(nBytes);
  15676. }
  15677. if( nBytes<=0 ){
  15678. sqlite3_free(pOld);
  15679. return 0;
  15680. }
  15681. nOld = sqlite3MallocSize(pOld);
  15682. if( sqlite3GlobalConfig.bMemstat ){
  15683. sqlite3_mutex_enter(mem0.mutex);
  15684. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
  15685. nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  15686. if( nOld==nNew ){
  15687. pNew = pOld;
  15688. }else{
  15689. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
  15690. mem0.alarmThreshold ){
  15691. sqlite3MallocAlarm(nNew-nOld);
  15692. }
  15693. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  15694. if( pNew==0 && mem0.alarmCallback ){
  15695. sqlite3MallocAlarm(nBytes);
  15696. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  15697. }
  15698. if( pNew ){
  15699. nNew = sqlite3MallocSize(pNew);
  15700. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  15701. }
  15702. }
  15703. sqlite3_mutex_leave(mem0.mutex);
  15704. }else{
  15705. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nBytes);
  15706. }
  15707. return pNew;
  15708. }
  15709. /*
  15710. ** The public interface to sqlite3Realloc. Make sure that the memory
  15711. ** subsystem is initialized prior to invoking sqliteRealloc.
  15712. */
  15713. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  15714. #ifndef SQLITE_OMIT_AUTOINIT
  15715. if( sqlite3_initialize() ) return 0;
  15716. #endif
  15717. return sqlite3Realloc(pOld, n);
  15718. }
  15719. /*
  15720. ** Allocate and zero memory.
  15721. */
  15722. SQLITE_PRIVATE void *sqlite3MallocZero(int n){
  15723. void *p = sqlite3Malloc(n);
  15724. if( p ){
  15725. memset(p, 0, n);
  15726. }
  15727. return p;
  15728. }
  15729. /*
  15730. ** Allocate and zero memory. If the allocation fails, make
  15731. ** the mallocFailed flag in the connection pointer.
  15732. */
  15733. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
  15734. void *p = sqlite3DbMallocRaw(db, n);
  15735. if( p ){
  15736. memset(p, 0, n);
  15737. }
  15738. return p;
  15739. }
  15740. /*
  15741. ** Allocate and zero memory. If the allocation fails, make
  15742. ** the mallocFailed flag in the connection pointer.
  15743. **
  15744. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  15745. ** failure on the same database connection) then always return 0.
  15746. ** Hence for a particular database connection, once malloc starts
  15747. ** failing, it fails consistently until mallocFailed is reset.
  15748. ** This is an important assumption. There are many places in the
  15749. ** code that do things like this:
  15750. **
  15751. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  15752. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  15753. ** if( b ) a[10] = 9;
  15754. **
  15755. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  15756. ** that all prior mallocs (ex: "a") worked too.
  15757. */
  15758. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  15759. void *p;
  15760. #ifndef SQLITE_OMIT_LOOKASIDE
  15761. if( db ){
  15762. LookasideSlot *pBuf;
  15763. if( db->mallocFailed ){
  15764. return 0;
  15765. }
  15766. if( db->lookaside.bEnabled && n<=db->lookaside.sz
  15767. && (pBuf = db->lookaside.pFree)!=0 ){
  15768. db->lookaside.pFree = pBuf->pNext;
  15769. db->lookaside.nOut++;
  15770. if( db->lookaside.nOut>db->lookaside.mxOut ){
  15771. db->lookaside.mxOut = db->lookaside.nOut;
  15772. }
  15773. return (void*)pBuf;
  15774. }
  15775. }
  15776. #else
  15777. if( db && db->mallocFailed ){
  15778. return 0;
  15779. }
  15780. #endif
  15781. p = sqlite3Malloc(n);
  15782. if( !p && db ){
  15783. db->mallocFailed = 1;
  15784. }
  15785. return p;
  15786. }
  15787. /*
  15788. ** Resize the block of memory pointed to by p to n bytes. If the
  15789. ** resize fails, set the mallocFailed flag in the connection object.
  15790. */
  15791. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  15792. void *pNew = 0;
  15793. if( db->mallocFailed==0 ){
  15794. if( p==0 ){
  15795. return sqlite3DbMallocRaw(db, n);
  15796. }
  15797. if( isLookaside(db, p) ){
  15798. if( n<=db->lookaside.sz ){
  15799. return p;
  15800. }
  15801. pNew = sqlite3DbMallocRaw(db, n);
  15802. if( pNew ){
  15803. memcpy(pNew, p, db->lookaside.sz);
  15804. sqlite3DbFree(db, p);
  15805. }
  15806. }else{
  15807. pNew = sqlite3_realloc(p, n);
  15808. if( !pNew ){
  15809. db->mallocFailed = 1;
  15810. }
  15811. }
  15812. }
  15813. return pNew;
  15814. }
  15815. /*
  15816. ** Attempt to reallocate p. If the reallocation fails, then free p
  15817. ** and set the mallocFailed flag in the database connection.
  15818. */
  15819. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  15820. void *pNew;
  15821. pNew = sqlite3DbRealloc(db, p, n);
  15822. if( !pNew ){
  15823. sqlite3DbFree(db, p);
  15824. }
  15825. return pNew;
  15826. }
  15827. /*
  15828. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  15829. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  15830. ** is because when memory debugging is turned on, these two functions are
  15831. ** called via macros that record the current file and line number in the
  15832. ** ThreadData structure.
  15833. */
  15834. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  15835. char *zNew;
  15836. size_t n;
  15837. if( z==0 ){
  15838. return 0;
  15839. }
  15840. n = (db ? sqlite3Strlen(db, z) : sqlite3Strlen30(z))+1;
  15841. assert( (n&0x7fffffff)==n );
  15842. zNew = sqlite3DbMallocRaw(db, (int)n);
  15843. if( zNew ){
  15844. memcpy(zNew, z, n);
  15845. }
  15846. return zNew;
  15847. }
  15848. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  15849. char *zNew;
  15850. if( z==0 ){
  15851. return 0;
  15852. }
  15853. assert( (n&0x7fffffff)==n );
  15854. zNew = sqlite3DbMallocRaw(db, n+1);
  15855. if( zNew ){
  15856. memcpy(zNew, z, n);
  15857. zNew[n] = 0;
  15858. }
  15859. return zNew;
  15860. }
  15861. /*
  15862. ** Create a string from the zFromat argument and the va_list that follows.
  15863. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  15864. ** point to that string.
  15865. */
  15866. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  15867. va_list ap;
  15868. char *z;
  15869. va_start(ap, zFormat);
  15870. z = sqlite3VMPrintf(db, zFormat, ap);
  15871. va_end(ap);
  15872. sqlite3DbFree(db, *pz);
  15873. *pz = z;
  15874. }
  15875. /*
  15876. ** This function must be called before exiting any API function (i.e.
  15877. ** returning control to the user) that has called sqlite3_malloc or
  15878. ** sqlite3_realloc.
  15879. **
  15880. ** The returned value is normally a copy of the second argument to this
  15881. ** function. However, if a malloc() failure has occured since the previous
  15882. ** invocation SQLITE_NOMEM is returned instead.
  15883. **
  15884. ** If the first argument, db, is not NULL and a malloc() error has occured,
  15885. ** then the connection error-code (the value returned by sqlite3_errcode())
  15886. ** is set to SQLITE_NOMEM.
  15887. */
  15888. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  15889. /* If the db handle is not NULL, then we must hold the connection handle
  15890. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  15891. ** is unsafe, as is the call to sqlite3Error().
  15892. */
  15893. assert( !db || sqlite3_mutex_held(db->mutex) );
  15894. if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
  15895. sqlite3Error(db, SQLITE_NOMEM, 0);
  15896. db->mallocFailed = 0;
  15897. rc = SQLITE_NOMEM;
  15898. }
  15899. return rc & (db ? db->errMask : 0xff);
  15900. }
  15901. /************** End of malloc.c **********************************************/
  15902. /************** Begin file printf.c ******************************************/
  15903. /*
  15904. ** The "printf" code that follows dates from the 1980's. It is in
  15905. ** the public domain. The original comments are included here for
  15906. ** completeness. They are very out-of-date but might be useful as
  15907. ** an historical reference. Most of the "enhancements" have been backed
  15908. ** out so that the functionality is now the same as standard printf().
  15909. **
  15910. ** $Id: printf.c,v 1.99 2008/12/10 19:26:24 drh Exp $
  15911. **
  15912. **************************************************************************
  15913. **
  15914. ** The following modules is an enhanced replacement for the "printf" subroutines
  15915. ** found in the standard C library. The following enhancements are
  15916. ** supported:
  15917. **
  15918. ** + Additional functions. The standard set of "printf" functions
  15919. ** includes printf, fprintf, sprintf, vprintf, vfprintf, and
  15920. ** vsprintf. This module adds the following:
  15921. **
  15922. ** * snprintf -- Works like sprintf, but has an extra argument
  15923. ** which is the size of the buffer written to.
  15924. **
  15925. ** * mprintf -- Similar to sprintf. Writes output to memory
  15926. ** obtained from malloc.
  15927. **
  15928. ** * xprintf -- Calls a function to dispose of output.
  15929. **
  15930. ** * nprintf -- No output, but returns the number of characters
  15931. ** that would have been output by printf.
  15932. **
  15933. ** * A v- version (ex: vsnprintf) of every function is also
  15934. ** supplied.
  15935. **
  15936. ** + A few extensions to the formatting notation are supported:
  15937. **
  15938. ** * The "=" flag (similar to "-") causes the output to be
  15939. ** be centered in the appropriately sized field.
  15940. **
  15941. ** * The %b field outputs an integer in binary notation.
  15942. **
  15943. ** * The %c field now accepts a precision. The character output
  15944. ** is repeated by the number of times the precision specifies.
  15945. **
  15946. ** * The %' field works like %c, but takes as its character the
  15947. ** next character of the format string, instead of the next
  15948. ** argument. For example, printf("%.78'-") prints 78 minus
  15949. ** signs, the same as printf("%.78c",'-').
  15950. **
  15951. ** + When compiled using GCC on a SPARC, this version of printf is
  15952. ** faster than the library printf for SUN OS 4.1.
  15953. **
  15954. ** + All functions are fully reentrant.
  15955. **
  15956. */
  15957. /*
  15958. ** Conversion types fall into various categories as defined by the
  15959. ** following enumeration.
  15960. */
  15961. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  15962. #define etFLOAT 2 /* Floating point. %f */
  15963. #define etEXP 3 /* Exponentional notation. %e and %E */
  15964. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  15965. #define etSIZE 5 /* Return number of characters processed so far. %n */
  15966. #define etSTRING 6 /* Strings. %s */
  15967. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  15968. #define etPERCENT 8 /* Percent symbol. %% */
  15969. #define etCHARX 9 /* Characters. %c */
  15970. /* The rest are extensions, not normally found in printf() */
  15971. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  15972. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  15973. NULL pointers replaced by SQL NULL. %Q */
  15974. #define etTOKEN 12 /* a pointer to a Token structure */
  15975. #define etSRCLIST 13 /* a pointer to a SrcList */
  15976. #define etPOINTER 14 /* The %p conversion */
  15977. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  15978. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  15979. /*
  15980. ** An "etByte" is an 8-bit unsigned value.
  15981. */
  15982. typedef unsigned char etByte;
  15983. /*
  15984. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  15985. ** by an instance of the following structure
  15986. */
  15987. typedef struct et_info { /* Information about each format field */
  15988. char fmttype; /* The format field code letter */
  15989. etByte base; /* The base for radix conversion */
  15990. etByte flags; /* One or more of FLAG_ constants below */
  15991. etByte type; /* Conversion paradigm */
  15992. etByte charset; /* Offset into aDigits[] of the digits string */
  15993. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  15994. } et_info;
  15995. /*
  15996. ** Allowed values for et_info.flags
  15997. */
  15998. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  15999. #define FLAG_INTERN 2 /* True if for internal use only */
  16000. #define FLAG_STRING 4 /* Allow infinity precision */
  16001. /*
  16002. ** The following table is searched linearly, so it is good to put the
  16003. ** most frequently used conversion types first.
  16004. */
  16005. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  16006. static const char aPrefix[] = "-x0\000X0";
  16007. static const et_info fmtinfo[] = {
  16008. { 'd', 10, 1, etRADIX, 0, 0 },
  16009. { 's', 0, 4, etSTRING, 0, 0 },
  16010. { 'g', 0, 1, etGENERIC, 30, 0 },
  16011. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  16012. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  16013. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  16014. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  16015. { 'c', 0, 0, etCHARX, 0, 0 },
  16016. { 'o', 8, 0, etRADIX, 0, 2 },
  16017. { 'u', 10, 0, etRADIX, 0, 0 },
  16018. { 'x', 16, 0, etRADIX, 16, 1 },
  16019. { 'X', 16, 0, etRADIX, 0, 4 },
  16020. #ifndef SQLITE_OMIT_FLOATING_POINT
  16021. { 'f', 0, 1, etFLOAT, 0, 0 },
  16022. { 'e', 0, 1, etEXP, 30, 0 },
  16023. { 'E', 0, 1, etEXP, 14, 0 },
  16024. { 'G', 0, 1, etGENERIC, 14, 0 },
  16025. #endif
  16026. { 'i', 10, 1, etRADIX, 0, 0 },
  16027. { 'n', 0, 0, etSIZE, 0, 0 },
  16028. { '%', 0, 0, etPERCENT, 0, 0 },
  16029. { 'p', 16, 0, etPOINTER, 0, 1 },
  16030. { 'T', 0, 2, etTOKEN, 0, 0 },
  16031. { 'S', 0, 2, etSRCLIST, 0, 0 },
  16032. { 'r', 10, 3, etORDINAL, 0, 0 },
  16033. };
  16034. /*
  16035. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  16036. ** conversions will work.
  16037. */
  16038. #ifndef SQLITE_OMIT_FLOATING_POINT
  16039. /*
  16040. ** "*val" is a double such that 0.1 <= *val < 10.0
  16041. ** Return the ascii code for the leading digit of *val, then
  16042. ** multiply "*val" by 10.0 to renormalize.
  16043. **
  16044. ** Example:
  16045. ** input: *val = 3.14159
  16046. ** output: *val = 1.4159 function return = '3'
  16047. **
  16048. ** The counter *cnt is incremented each time. After counter exceeds
  16049. ** 16 (the number of significant digits in a 64-bit float) '0' is
  16050. ** always returned.
  16051. */
  16052. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  16053. int digit;
  16054. LONGDOUBLE_TYPE d;
  16055. if( (*cnt)++ >= 16 ) return '0';
  16056. digit = (int)*val;
  16057. d = digit;
  16058. digit += '0';
  16059. *val = (*val - d)*10.0;
  16060. return (char)digit;
  16061. }
  16062. #endif /* SQLITE_OMIT_FLOATING_POINT */
  16063. /*
  16064. ** Append N space characters to the given string buffer.
  16065. */
  16066. static void appendSpace(StrAccum *pAccum, int N){
  16067. static const char zSpaces[] = " ";
  16068. while( N>=(int)sizeof(zSpaces)-1 ){
  16069. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  16070. N -= sizeof(zSpaces)-1;
  16071. }
  16072. if( N>0 ){
  16073. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  16074. }
  16075. }
  16076. /*
  16077. ** On machines with a small stack size, you can redefine the
  16078. ** SQLITE_PRINT_BUF_SIZE to be less than 350. But beware - for
  16079. ** smaller values some %f conversions may go into an infinite loop.
  16080. */
  16081. #ifndef SQLITE_PRINT_BUF_SIZE
  16082. # define SQLITE_PRINT_BUF_SIZE 350
  16083. #endif
  16084. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  16085. /*
  16086. ** The root program. All variations call this core.
  16087. **
  16088. ** INPUTS:
  16089. ** func This is a pointer to a function taking three arguments
  16090. ** 1. A pointer to anything. Same as the "arg" parameter.
  16091. ** 2. A pointer to the list of characters to be output
  16092. ** (Note, this list is NOT null terminated.)
  16093. ** 3. An integer number of characters to be output.
  16094. ** (Note: This number might be zero.)
  16095. **
  16096. ** arg This is the pointer to anything which will be passed as the
  16097. ** first argument to "func". Use it for whatever you like.
  16098. **
  16099. ** fmt This is the format string, as in the usual print.
  16100. **
  16101. ** ap This is a pointer to a list of arguments. Same as in
  16102. ** vfprint.
  16103. **
  16104. ** OUTPUTS:
  16105. ** The return value is the total number of characters sent to
  16106. ** the function "func". Returns -1 on a error.
  16107. **
  16108. ** Note that the order in which automatic variables are declared below
  16109. ** seems to make a big difference in determining how fast this beast
  16110. ** will run.
  16111. */
  16112. SQLITE_PRIVATE void sqlite3VXPrintf(
  16113. StrAccum *pAccum, /* Accumulate results here */
  16114. int useExtended, /* Allow extended %-conversions */
  16115. const char *fmt, /* Format string */
  16116. va_list ap /* arguments */
  16117. ){
  16118. int c; /* Next character in the format string */
  16119. char *bufpt; /* Pointer to the conversion buffer */
  16120. int precision; /* Precision of the current field */
  16121. int length; /* Length of the field */
  16122. int idx; /* A general purpose loop counter */
  16123. int width; /* Width of the current field */
  16124. etByte flag_leftjustify; /* True if "-" flag is present */
  16125. etByte flag_plussign; /* True if "+" flag is present */
  16126. etByte flag_blanksign; /* True if " " flag is present */
  16127. etByte flag_alternateform; /* True if "#" flag is present */
  16128. etByte flag_altform2; /* True if "!" flag is present */
  16129. etByte flag_zeropad; /* True if field width constant starts with zero */
  16130. etByte flag_long; /* True if "l" flag is present */
  16131. etByte flag_longlong; /* True if the "ll" flag is present */
  16132. etByte done; /* Loop termination flag */
  16133. sqlite_uint64 longvalue; /* Value for integer types */
  16134. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  16135. const et_info *infop; /* Pointer to the appropriate info structure */
  16136. char buf[etBUFSIZE]; /* Conversion buffer */
  16137. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  16138. etByte xtype = 0; /* Conversion paradigm */
  16139. char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
  16140. #ifndef SQLITE_OMIT_FLOATING_POINT
  16141. int exp, e2; /* exponent of real numbers */
  16142. double rounder; /* Used for rounding floating point values */
  16143. etByte flag_dp; /* True if decimal point should be shown */
  16144. etByte flag_rtz; /* True if trailing zeros should be removed */
  16145. etByte flag_exp; /* True to force display of the exponent */
  16146. int nsd; /* Number of significant digits returned */
  16147. #endif
  16148. length = 0;
  16149. bufpt = 0;
  16150. for(; (c=(*fmt))!=0; ++fmt){
  16151. if( c!='%' ){
  16152. int amt;
  16153. bufpt = (char *)fmt;
  16154. amt = 1;
  16155. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  16156. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  16157. if( c==0 ) break;
  16158. }
  16159. if( (c=(*++fmt))==0 ){
  16160. sqlite3StrAccumAppend(pAccum, "%", 1);
  16161. break;
  16162. }
  16163. /* Find out what flags are present */
  16164. flag_leftjustify = flag_plussign = flag_blanksign =
  16165. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  16166. done = 0;
  16167. do{
  16168. switch( c ){
  16169. case '-': flag_leftjustify = 1; break;
  16170. case '+': flag_plussign = 1; break;
  16171. case ' ': flag_blanksign = 1; break;
  16172. case '#': flag_alternateform = 1; break;
  16173. case '!': flag_altform2 = 1; break;
  16174. case '0': flag_zeropad = 1; break;
  16175. default: done = 1; break;
  16176. }
  16177. }while( !done && (c=(*++fmt))!=0 );
  16178. /* Get the field width */
  16179. width = 0;
  16180. if( c=='*' ){
  16181. width = va_arg(ap,int);
  16182. if( width<0 ){
  16183. flag_leftjustify = 1;
  16184. width = -width;
  16185. }
  16186. c = *++fmt;
  16187. }else{
  16188. while( c>='0' && c<='9' ){
  16189. width = width*10 + c - '0';
  16190. c = *++fmt;
  16191. }
  16192. }
  16193. if( width > etBUFSIZE-10 ){
  16194. width = etBUFSIZE-10;
  16195. }
  16196. /* Get the precision */
  16197. if( c=='.' ){
  16198. precision = 0;
  16199. c = *++fmt;
  16200. if( c=='*' ){
  16201. precision = va_arg(ap,int);
  16202. if( precision<0 ) precision = -precision;
  16203. c = *++fmt;
  16204. }else{
  16205. while( c>='0' && c<='9' ){
  16206. precision = precision*10 + c - '0';
  16207. c = *++fmt;
  16208. }
  16209. }
  16210. }else{
  16211. precision = -1;
  16212. }
  16213. /* Get the conversion type modifier */
  16214. if( c=='l' ){
  16215. flag_long = 1;
  16216. c = *++fmt;
  16217. if( c=='l' ){
  16218. flag_longlong = 1;
  16219. c = *++fmt;
  16220. }else{
  16221. flag_longlong = 0;
  16222. }
  16223. }else{
  16224. flag_long = flag_longlong = 0;
  16225. }
  16226. /* Fetch the info entry for the field */
  16227. infop = 0;
  16228. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  16229. if( c==fmtinfo[idx].fmttype ){
  16230. infop = &fmtinfo[idx];
  16231. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  16232. xtype = infop->type;
  16233. }else{
  16234. return;
  16235. }
  16236. break;
  16237. }
  16238. }
  16239. zExtra = 0;
  16240. if( infop==0 ){
  16241. return;
  16242. }
  16243. /* Limit the precision to prevent overflowing buf[] during conversion */
  16244. if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
  16245. precision = etBUFSIZE-40;
  16246. }
  16247. /*
  16248. ** At this point, variables are initialized as follows:
  16249. **
  16250. ** flag_alternateform TRUE if a '#' is present.
  16251. ** flag_altform2 TRUE if a '!' is present.
  16252. ** flag_plussign TRUE if a '+' is present.
  16253. ** flag_leftjustify TRUE if a '-' is present or if the
  16254. ** field width was negative.
  16255. ** flag_zeropad TRUE if the width began with 0.
  16256. ** flag_long TRUE if the letter 'l' (ell) prefixed
  16257. ** the conversion character.
  16258. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  16259. ** the conversion character.
  16260. ** flag_blanksign TRUE if a ' ' is present.
  16261. ** width The specified field width. This is
  16262. ** always non-negative. Zero is the default.
  16263. ** precision The specified precision. The default
  16264. ** is -1.
  16265. ** xtype The class of the conversion.
  16266. ** infop Pointer to the appropriate info struct.
  16267. */
  16268. switch( xtype ){
  16269. case etPOINTER:
  16270. flag_longlong = sizeof(char*)==sizeof(i64);
  16271. flag_long = sizeof(char*)==sizeof(long int);
  16272. /* Fall through into the next case */
  16273. case etORDINAL:
  16274. case etRADIX:
  16275. if( infop->flags & FLAG_SIGNED ){
  16276. i64 v;
  16277. if( flag_longlong ) v = va_arg(ap,i64);
  16278. else if( flag_long ) v = va_arg(ap,long int);
  16279. else v = va_arg(ap,int);
  16280. if( v<0 ){
  16281. longvalue = -v;
  16282. prefix = '-';
  16283. }else{
  16284. longvalue = v;
  16285. if( flag_plussign ) prefix = '+';
  16286. else if( flag_blanksign ) prefix = ' ';
  16287. else prefix = 0;
  16288. }
  16289. }else{
  16290. if( flag_longlong ) longvalue = va_arg(ap,u64);
  16291. else if( flag_long ) longvalue = va_arg(ap,unsigned long int);
  16292. else longvalue = va_arg(ap,unsigned int);
  16293. prefix = 0;
  16294. }
  16295. if( longvalue==0 ) flag_alternateform = 0;
  16296. if( flag_zeropad && precision<width-(prefix!=0) ){
  16297. precision = width-(prefix!=0);
  16298. }
  16299. bufpt = &buf[etBUFSIZE-1];
  16300. if( xtype==etORDINAL ){
  16301. static const char zOrd[] = "thstndrd";
  16302. int x = (int)(longvalue % 10);
  16303. if( x>=4 || (longvalue/10)%10==1 ){
  16304. x = 0;
  16305. }
  16306. buf[etBUFSIZE-3] = zOrd[x*2];
  16307. buf[etBUFSIZE-2] = zOrd[x*2+1];
  16308. bufpt -= 2;
  16309. }
  16310. {
  16311. register const char *cset; /* Use registers for speed */
  16312. register int base;
  16313. cset = &aDigits[infop->charset];
  16314. base = infop->base;
  16315. do{ /* Convert to ascii */
  16316. *(--bufpt) = cset[longvalue%base];
  16317. longvalue = longvalue/base;
  16318. }while( longvalue>0 );
  16319. }
  16320. length = (int)(&buf[etBUFSIZE-1]-bufpt);
  16321. for(idx=precision-length; idx>0; idx--){
  16322. *(--bufpt) = '0'; /* Zero pad */
  16323. }
  16324. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  16325. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  16326. const char *pre;
  16327. char x;
  16328. pre = &aPrefix[infop->prefix];
  16329. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  16330. }
  16331. length = (int)(&buf[etBUFSIZE-1]-bufpt);
  16332. break;
  16333. case etFLOAT:
  16334. case etEXP:
  16335. case etGENERIC:
  16336. realvalue = va_arg(ap,double);
  16337. #ifndef SQLITE_OMIT_FLOATING_POINT
  16338. if( precision<0 ) precision = 6; /* Set default precision */
  16339. if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
  16340. if( realvalue<0.0 ){
  16341. realvalue = -realvalue;
  16342. prefix = '-';
  16343. }else{
  16344. if( flag_plussign ) prefix = '+';
  16345. else if( flag_blanksign ) prefix = ' ';
  16346. else prefix = 0;
  16347. }
  16348. if( xtype==etGENERIC && precision>0 ) precision--;
  16349. #if 0
  16350. /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
  16351. for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
  16352. #else
  16353. /* It makes more sense to use 0.5 */
  16354. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  16355. #endif
  16356. if( xtype==etFLOAT ) realvalue += rounder;
  16357. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  16358. exp = 0;
  16359. if( sqlite3IsNaN((double)realvalue) ){
  16360. bufpt = "NaN";
  16361. length = 3;
  16362. break;
  16363. }
  16364. if( realvalue>0.0 ){
  16365. while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
  16366. while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
  16367. while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
  16368. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  16369. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  16370. if( exp>350 ){
  16371. if( prefix=='-' ){
  16372. bufpt = "-Inf";
  16373. }else if( prefix=='+' ){
  16374. bufpt = "+Inf";
  16375. }else{
  16376. bufpt = "Inf";
  16377. }
  16378. length = sqlite3Strlen30(bufpt);
  16379. break;
  16380. }
  16381. }
  16382. bufpt = buf;
  16383. /*
  16384. ** If the field type is etGENERIC, then convert to either etEXP
  16385. ** or etFLOAT, as appropriate.
  16386. */
  16387. flag_exp = xtype==etEXP;
  16388. if( xtype!=etFLOAT ){
  16389. realvalue += rounder;
  16390. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  16391. }
  16392. if( xtype==etGENERIC ){
  16393. flag_rtz = !flag_alternateform;
  16394. if( exp<-4 || exp>precision ){
  16395. xtype = etEXP;
  16396. }else{
  16397. precision = precision - exp;
  16398. xtype = etFLOAT;
  16399. }
  16400. }else{
  16401. flag_rtz = 0;
  16402. }
  16403. if( xtype==etEXP ){
  16404. e2 = 0;
  16405. }else{
  16406. e2 = exp;
  16407. }
  16408. nsd = 0;
  16409. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  16410. /* The sign in front of the number */
  16411. if( prefix ){
  16412. *(bufpt++) = prefix;
  16413. }
  16414. /* Digits prior to the decimal point */
  16415. if( e2<0 ){
  16416. *(bufpt++) = '0';
  16417. }else{
  16418. for(; e2>=0; e2--){
  16419. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  16420. }
  16421. }
  16422. /* The decimal point */
  16423. if( flag_dp ){
  16424. *(bufpt++) = '.';
  16425. }
  16426. /* "0" digits after the decimal point but before the first
  16427. ** significant digit of the number */
  16428. for(e2++; e2<0; precision--, e2++){
  16429. assert( precision>0 );
  16430. *(bufpt++) = '0';
  16431. }
  16432. /* Significant digits after the decimal point */
  16433. while( (precision--)>0 ){
  16434. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  16435. }
  16436. /* Remove trailing zeros and the "." if no digits follow the "." */
  16437. if( flag_rtz && flag_dp ){
  16438. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  16439. assert( bufpt>buf );
  16440. if( bufpt[-1]=='.' ){
  16441. if( flag_altform2 ){
  16442. *(bufpt++) = '0';
  16443. }else{
  16444. *(--bufpt) = 0;
  16445. }
  16446. }
  16447. }
  16448. /* Add the "eNNN" suffix */
  16449. if( flag_exp || xtype==etEXP ){
  16450. *(bufpt++) = aDigits[infop->charset];
  16451. if( exp<0 ){
  16452. *(bufpt++) = '-'; exp = -exp;
  16453. }else{
  16454. *(bufpt++) = '+';
  16455. }
  16456. if( exp>=100 ){
  16457. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  16458. exp %= 100;
  16459. }
  16460. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  16461. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  16462. }
  16463. *bufpt = 0;
  16464. /* The converted number is in buf[] and zero terminated. Output it.
  16465. ** Note that the number is in the usual order, not reversed as with
  16466. ** integer conversions. */
  16467. length = (int)(bufpt-buf);
  16468. bufpt = buf;
  16469. /* Special case: Add leading zeros if the flag_zeropad flag is
  16470. ** set and we are not left justified */
  16471. if( flag_zeropad && !flag_leftjustify && length < width){
  16472. int i;
  16473. int nPad = width - length;
  16474. for(i=width; i>=nPad; i--){
  16475. bufpt[i] = bufpt[i-nPad];
  16476. }
  16477. i = prefix!=0;
  16478. while( nPad-- ) bufpt[i++] = '0';
  16479. length = width;
  16480. }
  16481. #endif
  16482. break;
  16483. case etSIZE:
  16484. *(va_arg(ap,int*)) = pAccum->nChar;
  16485. length = width = 0;
  16486. break;
  16487. case etPERCENT:
  16488. buf[0] = '%';
  16489. bufpt = buf;
  16490. length = 1;
  16491. break;
  16492. case etCHARX:
  16493. c = va_arg(ap,int);
  16494. buf[0] = (char)c;
  16495. if( precision>=0 ){
  16496. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  16497. length = precision;
  16498. }else{
  16499. length =1;
  16500. }
  16501. bufpt = buf;
  16502. break;
  16503. case etSTRING:
  16504. case etDYNSTRING:
  16505. bufpt = va_arg(ap,char*);
  16506. if( bufpt==0 ){
  16507. bufpt = "";
  16508. }else if( xtype==etDYNSTRING ){
  16509. zExtra = bufpt;
  16510. }
  16511. if( precision>=0 ){
  16512. for(length=0; length<precision && bufpt[length]; length++){}
  16513. }else{
  16514. length = sqlite3Strlen30(bufpt);
  16515. }
  16516. break;
  16517. case etSQLESCAPE:
  16518. case etSQLESCAPE2:
  16519. case etSQLESCAPE3: {
  16520. int i, j, n, isnull;
  16521. int needQuote;
  16522. char ch;
  16523. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  16524. char *escarg = va_arg(ap,char*);
  16525. isnull = escarg==0;
  16526. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  16527. for(i=n=0; (ch=escarg[i])!=0; i++){
  16528. if( ch==q ) n++;
  16529. }
  16530. needQuote = !isnull && xtype==etSQLESCAPE2;
  16531. n += i + 1 + needQuote*2;
  16532. if( n>etBUFSIZE ){
  16533. bufpt = zExtra = sqlite3Malloc( n );
  16534. if( bufpt==0 ){
  16535. pAccum->mallocFailed = 1;
  16536. return;
  16537. }
  16538. }else{
  16539. bufpt = buf;
  16540. }
  16541. j = 0;
  16542. if( needQuote ) bufpt[j++] = q;
  16543. for(i=0; (ch=escarg[i])!=0; i++){
  16544. bufpt[j++] = ch;
  16545. if( ch==q ) bufpt[j++] = ch;
  16546. }
  16547. if( needQuote ) bufpt[j++] = q;
  16548. bufpt[j] = 0;
  16549. length = j;
  16550. /* The precision is ignored on %q and %Q */
  16551. /* if( precision>=0 && precision<length ) length = precision; */
  16552. break;
  16553. }
  16554. case etTOKEN: {
  16555. Token *pToken = va_arg(ap, Token*);
  16556. if( pToken ){
  16557. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  16558. }
  16559. length = width = 0;
  16560. break;
  16561. }
  16562. case etSRCLIST: {
  16563. SrcList *pSrc = va_arg(ap, SrcList*);
  16564. int k = va_arg(ap, int);
  16565. struct SrcList_item *pItem = &pSrc->a[k];
  16566. assert( k>=0 && k<pSrc->nSrc );
  16567. if( pItem->zDatabase ){
  16568. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  16569. sqlite3StrAccumAppend(pAccum, ".", 1);
  16570. }
  16571. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  16572. length = width = 0;
  16573. break;
  16574. }
  16575. }/* End switch over the format type */
  16576. /*
  16577. ** The text of the conversion is pointed to by "bufpt" and is
  16578. ** "length" characters long. The field width is "width". Do
  16579. ** the output.
  16580. */
  16581. if( !flag_leftjustify ){
  16582. register int nspace;
  16583. nspace = width-length;
  16584. if( nspace>0 ){
  16585. appendSpace(pAccum, nspace);
  16586. }
  16587. }
  16588. if( length>0 ){
  16589. sqlite3StrAccumAppend(pAccum, bufpt, length);
  16590. }
  16591. if( flag_leftjustify ){
  16592. register int nspace;
  16593. nspace = width-length;
  16594. if( nspace>0 ){
  16595. appendSpace(pAccum, nspace);
  16596. }
  16597. }
  16598. if( zExtra ){
  16599. sqlite3_free(zExtra);
  16600. }
  16601. }/* End for loop over the format string */
  16602. } /* End of function */
  16603. /*
  16604. ** Append N bytes of text from z to the StrAccum object.
  16605. */
  16606. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  16607. if( p->tooBig | p->mallocFailed ){
  16608. return;
  16609. }
  16610. if( N<0 ){
  16611. N = sqlite3Strlen30(z);
  16612. }
  16613. if( N==0 || z==0 ){
  16614. return;
  16615. }
  16616. if( p->nChar+N >= p->nAlloc ){
  16617. char *zNew;
  16618. if( !p->useMalloc ){
  16619. p->tooBig = 1;
  16620. N = p->nAlloc - p->nChar - 1;
  16621. if( N<=0 ){
  16622. return;
  16623. }
  16624. }else{
  16625. i64 szNew = p->nChar;
  16626. szNew += N + 1;
  16627. if( szNew > p->mxAlloc ){
  16628. sqlite3StrAccumReset(p);
  16629. p->tooBig = 1;
  16630. return;
  16631. }else{
  16632. p->nAlloc = (int)szNew;
  16633. }
  16634. zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
  16635. if( zNew ){
  16636. memcpy(zNew, p->zText, p->nChar);
  16637. sqlite3StrAccumReset(p);
  16638. p->zText = zNew;
  16639. }else{
  16640. p->mallocFailed = 1;
  16641. sqlite3StrAccumReset(p);
  16642. return;
  16643. }
  16644. }
  16645. }
  16646. memcpy(&p->zText[p->nChar], z, N);
  16647. p->nChar += N;
  16648. }
  16649. /*
  16650. ** Finish off a string by making sure it is zero-terminated.
  16651. ** Return a pointer to the resulting string. Return a NULL
  16652. ** pointer if any kind of error was encountered.
  16653. */
  16654. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  16655. if( p->zText ){
  16656. p->zText[p->nChar] = 0;
  16657. if( p->useMalloc && p->zText==p->zBase ){
  16658. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  16659. if( p->zText ){
  16660. memcpy(p->zText, p->zBase, p->nChar+1);
  16661. }else{
  16662. p->mallocFailed = 1;
  16663. }
  16664. }
  16665. }
  16666. return p->zText;
  16667. }
  16668. /*
  16669. ** Reset an StrAccum string. Reclaim all malloced memory.
  16670. */
  16671. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  16672. if( p->zText!=p->zBase ){
  16673. sqlite3DbFree(p->db, p->zText);
  16674. }
  16675. p->zText = 0;
  16676. }
  16677. /*
  16678. ** Initialize a string accumulator
  16679. */
  16680. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  16681. p->zText = p->zBase = zBase;
  16682. p->db = 0;
  16683. p->nChar = 0;
  16684. p->nAlloc = n;
  16685. p->mxAlloc = mx;
  16686. p->useMalloc = 1;
  16687. p->tooBig = 0;
  16688. p->mallocFailed = 0;
  16689. }
  16690. /*
  16691. ** Print into memory obtained from sqliteMalloc(). Use the internal
  16692. ** %-conversion extensions.
  16693. */
  16694. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  16695. char *z;
  16696. char zBase[SQLITE_PRINT_BUF_SIZE];
  16697. StrAccum acc;
  16698. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  16699. db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
  16700. acc.db = db;
  16701. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  16702. z = sqlite3StrAccumFinish(&acc);
  16703. if( acc.mallocFailed && db ){
  16704. db->mallocFailed = 1;
  16705. }
  16706. return z;
  16707. }
  16708. /*
  16709. ** Print into memory obtained from sqliteMalloc(). Use the internal
  16710. ** %-conversion extensions.
  16711. */
  16712. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  16713. va_list ap;
  16714. char *z;
  16715. va_start(ap, zFormat);
  16716. z = sqlite3VMPrintf(db, zFormat, ap);
  16717. va_end(ap);
  16718. return z;
  16719. }
  16720. /*
  16721. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  16722. ** the string and before returnning. This routine is intended to be used
  16723. ** to modify an existing string. For example:
  16724. **
  16725. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  16726. **
  16727. */
  16728. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  16729. va_list ap;
  16730. char *z;
  16731. va_start(ap, zFormat);
  16732. z = sqlite3VMPrintf(db, zFormat, ap);
  16733. va_end(ap);
  16734. sqlite3DbFree(db, zStr);
  16735. return z;
  16736. }
  16737. /*
  16738. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  16739. ** %-conversion extensions.
  16740. */
  16741. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  16742. char *z;
  16743. char zBase[SQLITE_PRINT_BUF_SIZE];
  16744. StrAccum acc;
  16745. #ifndef SQLITE_OMIT_AUTOINIT
  16746. if( sqlite3_initialize() ) return 0;
  16747. #endif
  16748. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  16749. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  16750. z = sqlite3StrAccumFinish(&acc);
  16751. return z;
  16752. }
  16753. /*
  16754. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  16755. ** %-conversion extensions.
  16756. */
  16757. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  16758. va_list ap;
  16759. char *z;
  16760. #ifndef SQLITE_OMIT_AUTOINIT
  16761. if( sqlite3_initialize() ) return 0;
  16762. #endif
  16763. va_start(ap, zFormat);
  16764. z = sqlite3_vmprintf(zFormat, ap);
  16765. va_end(ap);
  16766. return z;
  16767. }
  16768. /*
  16769. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  16770. ** current locale settings. This is important for SQLite because we
  16771. ** are not able to use a "," as the decimal point in place of "." as
  16772. ** specified by some locales.
  16773. */
  16774. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  16775. char *z;
  16776. va_list ap;
  16777. StrAccum acc;
  16778. if( n<=0 ){
  16779. return zBuf;
  16780. }
  16781. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  16782. acc.useMalloc = 0;
  16783. va_start(ap,zFormat);
  16784. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  16785. va_end(ap);
  16786. z = sqlite3StrAccumFinish(&acc);
  16787. return z;
  16788. }
  16789. #if defined(SQLITE_DEBUG)
  16790. /*
  16791. ** A version of printf() that understands %lld. Used for debugging.
  16792. ** The printf() built into some versions of windows does not understand %lld
  16793. ** and segfaults if you give it a long long int.
  16794. */
  16795. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  16796. va_list ap;
  16797. StrAccum acc;
  16798. char zBuf[500];
  16799. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  16800. acc.useMalloc = 0;
  16801. va_start(ap,zFormat);
  16802. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  16803. va_end(ap);
  16804. sqlite3StrAccumFinish(&acc);
  16805. fprintf(stdout,"%s", zBuf);
  16806. fflush(stdout);
  16807. }
  16808. #endif
  16809. /************** End of printf.c **********************************************/
  16810. /************** Begin file random.c ******************************************/
  16811. /*
  16812. ** 2001 September 15
  16813. **
  16814. ** The author disclaims copyright to this source code. In place of
  16815. ** a legal notice, here is a blessing:
  16816. **
  16817. ** May you do good and not evil.
  16818. ** May you find forgiveness for yourself and forgive others.
  16819. ** May you share freely, never taking more than you give.
  16820. **
  16821. *************************************************************************
  16822. ** This file contains code to implement a pseudo-random number
  16823. ** generator (PRNG) for SQLite.
  16824. **
  16825. ** Random numbers are used by some of the database backends in order
  16826. ** to generate random integer keys for tables or random filenames.
  16827. **
  16828. ** $Id: random.c,v 1.29 2008/12/10 19:26:24 drh Exp $
  16829. */
  16830. /* All threads share a single random number generator.
  16831. ** This structure is the current state of the generator.
  16832. */
  16833. static SQLITE_WSD struct sqlite3PrngType {
  16834. unsigned char isInit; /* True if initialized */
  16835. unsigned char i, j; /* State variables */
  16836. unsigned char s[256]; /* State variables */
  16837. } sqlite3Prng;
  16838. /*
  16839. ** Get a single 8-bit random value from the RC4 PRNG. The Mutex
  16840. ** must be held while executing this routine.
  16841. **
  16842. ** Why not just use a library random generator like lrand48() for this?
  16843. ** Because the OP_NewRowid opcode in the VDBE depends on having a very
  16844. ** good source of random numbers. The lrand48() library function may
  16845. ** well be good enough. But maybe not. Or maybe lrand48() has some
  16846. ** subtle problems on some systems that could cause problems. It is hard
  16847. ** to know. To minimize the risk of problems due to bad lrand48()
  16848. ** implementations, SQLite uses this random number generator based
  16849. ** on RC4, which we know works very well.
  16850. **
  16851. ** (Later): Actually, OP_NewRowid does not depend on a good source of
  16852. ** randomness any more. But we will leave this code in all the same.
  16853. */
  16854. static u8 randomByte(void){
  16855. unsigned char t;
  16856. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  16857. ** state vector. If writable static data is unsupported on the target,
  16858. ** we have to locate the state vector at run-time. In the more common
  16859. ** case where writable static data is supported, wsdPrng can refer directly
  16860. ** to the "sqlite3Prng" state vector declared above.
  16861. */
  16862. #ifdef SQLITE_OMIT_WSD
  16863. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  16864. # define wsdPrng p[0]
  16865. #else
  16866. # define wsdPrng sqlite3Prng
  16867. #endif
  16868. /* Initialize the state of the random number generator once,
  16869. ** the first time this routine is called. The seed value does
  16870. ** not need to contain a lot of randomness since we are not
  16871. ** trying to do secure encryption or anything like that...
  16872. **
  16873. ** Nothing in this file or anywhere else in SQLite does any kind of
  16874. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  16875. ** number generator) not as an encryption device.
  16876. */
  16877. if( !wsdPrng.isInit ){
  16878. int i;
  16879. char k[256];
  16880. wsdPrng.j = 0;
  16881. wsdPrng.i = 0;
  16882. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  16883. for(i=0; i<256; i++){
  16884. wsdPrng.s[i] = (u8)i;
  16885. }
  16886. for(i=0; i<256; i++){
  16887. wsdPrng.j += wsdPrng.s[i] + k[i];
  16888. t = wsdPrng.s[wsdPrng.j];
  16889. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  16890. wsdPrng.s[i] = t;
  16891. }
  16892. wsdPrng.isInit = 1;
  16893. }
  16894. /* Generate and return single random byte
  16895. */
  16896. wsdPrng.i++;
  16897. t = wsdPrng.s[wsdPrng.i];
  16898. wsdPrng.j += t;
  16899. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  16900. wsdPrng.s[wsdPrng.j] = t;
  16901. t += wsdPrng.s[wsdPrng.i];
  16902. return wsdPrng.s[t];
  16903. }
  16904. /*
  16905. ** Return N random bytes.
  16906. */
  16907. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  16908. unsigned char *zBuf = pBuf;
  16909. #if SQLITE_THREADSAFE
  16910. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  16911. #endif
  16912. sqlite3_mutex_enter(mutex);
  16913. while( N-- ){
  16914. *(zBuf++) = randomByte();
  16915. }
  16916. sqlite3_mutex_leave(mutex);
  16917. }
  16918. #ifndef SQLITE_OMIT_BUILTIN_TEST
  16919. /*
  16920. ** For testing purposes, we sometimes want to preserve the state of
  16921. ** PRNG and restore the PRNG to its saved state at a later time, or
  16922. ** to reset the PRNG to its initial state. These routines accomplish
  16923. ** those tasks.
  16924. **
  16925. ** The sqlite3_test_control() interface calls these routines to
  16926. ** control the PRNG.
  16927. */
  16928. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  16929. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  16930. memcpy(
  16931. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  16932. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  16933. sizeof(sqlite3Prng)
  16934. );
  16935. }
  16936. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  16937. memcpy(
  16938. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  16939. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  16940. sizeof(sqlite3Prng)
  16941. );
  16942. }
  16943. SQLITE_PRIVATE void sqlite3PrngResetState(void){
  16944. GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
  16945. }
  16946. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  16947. /************** End of random.c **********************************************/
  16948. /************** Begin file utf.c *********************************************/
  16949. /*
  16950. ** 2004 April 13
  16951. **
  16952. ** The author disclaims copyright to this source code. In place of
  16953. ** a legal notice, here is a blessing:
  16954. **
  16955. ** May you do good and not evil.
  16956. ** May you find forgiveness for yourself and forgive others.
  16957. ** May you share freely, never taking more than you give.
  16958. **
  16959. *************************************************************************
  16960. ** This file contains routines used to translate between UTF-8,
  16961. ** UTF-16, UTF-16BE, and UTF-16LE.
  16962. **
  16963. ** $Id: utf.c,v 1.70 2008/12/10 22:30:25 shane Exp $
  16964. **
  16965. ** Notes on UTF-8:
  16966. **
  16967. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  16968. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  16969. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  16970. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  16971. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  16972. **
  16973. **
  16974. ** Notes on UTF-16: (with wwww+1==uuuuu)
  16975. **
  16976. ** Word-0 Word-1 Value
  16977. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  16978. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  16979. **
  16980. **
  16981. ** BOM or Byte Order Mark:
  16982. ** 0xff 0xfe little-endian utf-16 follows
  16983. ** 0xfe 0xff big-endian utf-16 follows
  16984. **
  16985. */
  16986. /************** Include vdbeInt.h in the middle of utf.c *********************/
  16987. /************** Begin file vdbeInt.h *****************************************/
  16988. /*
  16989. ** 2003 September 6
  16990. **
  16991. ** The author disclaims copyright to this source code. In place of
  16992. ** a legal notice, here is a blessing:
  16993. **
  16994. ** May you do good and not evil.
  16995. ** May you find forgiveness for yourself and forgive others.
  16996. ** May you share freely, never taking more than you give.
  16997. **
  16998. *************************************************************************
  16999. ** This is the header file for information that is private to the
  17000. ** VDBE. This information used to all be at the top of the single
  17001. ** source code file "vdbe.c". When that file became too big (over
  17002. ** 6000 lines long) it was split up into several smaller files and
  17003. ** this header information was factored out.
  17004. **
  17005. ** $Id: vdbeInt.h,v 1.161 2009/01/05 18:02:27 drh Exp $
  17006. */
  17007. #ifndef _VDBEINT_H_
  17008. #define _VDBEINT_H_
  17009. /*
  17010. ** intToKey() and keyToInt() used to transform the rowid. But with
  17011. ** the latest versions of the design they are no-ops.
  17012. */
  17013. #define keyToInt(X) (X)
  17014. #define intToKey(X) (X)
  17015. /*
  17016. ** SQL is translated into a sequence of instructions to be
  17017. ** executed by a virtual machine. Each instruction is an instance
  17018. ** of the following structure.
  17019. */
  17020. typedef struct VdbeOp Op;
  17021. /*
  17022. ** Boolean values
  17023. */
  17024. typedef unsigned char Bool;
  17025. /*
  17026. ** A cursor is a pointer into a single BTree within a database file.
  17027. ** The cursor can seek to a BTree entry with a particular key, or
  17028. ** loop over all entries of the Btree. You can also insert new BTree
  17029. ** entries or retrieve the key or data from the entry that the cursor
  17030. ** is currently pointing to.
  17031. **
  17032. ** Every cursor that the virtual machine has open is represented by an
  17033. ** instance of the following structure.
  17034. **
  17035. ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
  17036. ** really a single row that represents the NEW or OLD pseudo-table of
  17037. ** a row trigger. The data for the row is stored in VdbeCursor.pData and
  17038. ** the rowid is in VdbeCursor.iKey.
  17039. */
  17040. struct VdbeCursor {
  17041. BtCursor *pCursor; /* The cursor structure of the backend */
  17042. int iDb; /* Index of cursor database in db->aDb[] (or -1) */
  17043. i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
  17044. i64 nextRowid; /* Next rowid returned by OP_NewRowid */
  17045. Bool zeroed; /* True if zeroed out and ready for reuse */
  17046. Bool rowidIsValid; /* True if lastRowid is valid */
  17047. Bool atFirst; /* True if pointing to first entry */
  17048. Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  17049. Bool nullRow; /* True if pointing to a row with no data */
  17050. Bool nextRowidValid; /* True if the nextRowid field is valid */
  17051. Bool pseudoTable; /* This is a NEW or OLD pseudo-tables of a trigger */
  17052. Bool ephemPseudoTable;
  17053. Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  17054. Bool isTable; /* True if a table requiring integer keys */
  17055. Bool isIndex; /* True if an index containing keys only - no data */
  17056. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  17057. Btree *pBt; /* Separate file holding temporary table */
  17058. int nData; /* Number of bytes in pData */
  17059. char *pData; /* Data for a NEW or OLD pseudo-table */
  17060. i64 iKey; /* Key for the NEW or OLD pseudo-table row */
  17061. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  17062. int nField; /* Number of fields in the header */
  17063. i64 seqCount; /* Sequence counter */
  17064. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  17065. const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
  17066. /* Cached information about the header for the data record that the
  17067. ** cursor is currently pointing to. Only valid if cacheValid is true.
  17068. ** aRow might point to (ephemeral) data for the current row, or it might
  17069. ** be NULL.
  17070. */
  17071. int cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  17072. int payloadSize; /* Total number of bytes in the record */
  17073. u32 *aType; /* Type values for all entries in the record */
  17074. u32 *aOffset; /* Cached offsets to the start of each columns data */
  17075. u8 *aRow; /* Data for the current row, if all on one page */
  17076. };
  17077. typedef struct VdbeCursor VdbeCursor;
  17078. /*
  17079. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  17080. */
  17081. #define CACHE_STALE 0
  17082. /*
  17083. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  17084. ** structures. Each Mem struct may cache multiple representations (string,
  17085. ** integer etc.) of the same value. A value (and therefore Mem structure)
  17086. ** has the following properties:
  17087. **
  17088. ** Each value has a manifest type. The manifest type of the value stored
  17089. ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
  17090. ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
  17091. ** SQLITE_BLOB.
  17092. */
  17093. struct Mem {
  17094. union {
  17095. i64 i; /* Integer value. */
  17096. int nZero; /* Used when bit MEM_Zero is set in flags */
  17097. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  17098. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  17099. } u;
  17100. double r; /* Real value */
  17101. sqlite3 *db; /* The associated database connection */
  17102. char *z; /* String or BLOB value */
  17103. int n; /* Number of characters in string value, excluding '\0' */
  17104. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  17105. u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  17106. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  17107. void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
  17108. char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
  17109. };
  17110. /* One or more of the following flags are set to indicate the validOK
  17111. ** representations of the value stored in the Mem struct.
  17112. **
  17113. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  17114. ** No other flags may be set in this case.
  17115. **
  17116. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  17117. ** Usually this is encoded in the same unicode encoding as the main
  17118. ** database (see below for exceptions). If the MEM_Term flag is also
  17119. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  17120. ** flags may coexist with the MEM_Str flag.
  17121. **
  17122. ** Multiple of these values can appear in Mem.flags. But only one
  17123. ** at a time can appear in Mem.type.
  17124. */
  17125. #define MEM_Null 0x0001 /* Value is NULL */
  17126. #define MEM_Str 0x0002 /* Value is a string */
  17127. #define MEM_Int 0x0004 /* Value is an integer */
  17128. #define MEM_Real 0x0008 /* Value is a real number */
  17129. #define MEM_Blob 0x0010 /* Value is a BLOB */
  17130. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  17131. #define MEM_TypeMask 0x00ff /* Mask of type bits */
  17132. /* Whenever Mem contains a valid string or blob representation, one of
  17133. ** the following flags must be set to determine the memory management
  17134. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  17135. ** string is \000 or \u0000 terminated
  17136. */
  17137. #define MEM_Term 0x0200 /* String rep is nul terminated */
  17138. #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
  17139. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  17140. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  17141. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  17142. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  17143. #ifdef SQLITE_OMIT_INCRBLOB
  17144. #undef MEM_Zero
  17145. #define MEM_Zero 0x0000
  17146. #endif
  17147. /*
  17148. ** Clear any existing type flags from a Mem and replace them with f
  17149. */
  17150. #define MemSetTypeFlag(p, f) \
  17151. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  17152. /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
  17153. ** additional information about auxiliary information bound to arguments
  17154. ** of the function. This is used to implement the sqlite3_get_auxdata()
  17155. ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
  17156. ** that can be associated with a constant argument to a function. This
  17157. ** allows functions such as "regexp" to compile their constant regular
  17158. ** expression argument once and reused the compiled code for multiple
  17159. ** invocations.
  17160. */
  17161. struct VdbeFunc {
  17162. FuncDef *pFunc; /* The definition of the function */
  17163. int nAux; /* Number of entries allocated for apAux[] */
  17164. struct AuxData {
  17165. void *pAux; /* Aux data for the i-th argument */
  17166. void (*xDelete)(void *); /* Destructor for the aux data */
  17167. } apAux[1]; /* One slot for each function argument */
  17168. };
  17169. /*
  17170. ** The "context" argument for a installable function. A pointer to an
  17171. ** instance of this structure is the first argument to the routines used
  17172. ** implement the SQL functions.
  17173. **
  17174. ** There is a typedef for this structure in sqlite.h. So all routines,
  17175. ** even the public interface to SQLite, can use a pointer to this structure.
  17176. ** But this file is the only place where the internal details of this
  17177. ** structure are known.
  17178. **
  17179. ** This structure is defined inside of vdbeInt.h because it uses substructures
  17180. ** (Mem) which are only defined there.
  17181. */
  17182. struct sqlite3_context {
  17183. FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  17184. VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
  17185. Mem s; /* The return value is stored here */
  17186. Mem *pMem; /* Memory cell used to store aggregate context */
  17187. int isError; /* Error code returned by the function. */
  17188. CollSeq *pColl; /* Collating sequence */
  17189. };
  17190. /*
  17191. ** A Set structure is used for quick testing to see if a value
  17192. ** is part of a small set. Sets are used to implement code like
  17193. ** this:
  17194. ** x.y IN ('hi','hoo','hum')
  17195. */
  17196. typedef struct Set Set;
  17197. struct Set {
  17198. Hash hash; /* A set is just a hash table */
  17199. HashElem *prev; /* Previously accessed hash elemen */
  17200. };
  17201. /*
  17202. ** A Context stores the last insert rowid, the last statement change count,
  17203. ** and the current statement change count (i.e. changes since last statement).
  17204. ** The current keylist is also stored in the context.
  17205. ** Elements of Context structure type make up the ContextStack, which is
  17206. ** updated by the ContextPush and ContextPop opcodes (used by triggers).
  17207. ** The context is pushed before executing a trigger a popped when the
  17208. ** trigger finishes.
  17209. */
  17210. typedef struct Context Context;
  17211. struct Context {
  17212. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  17213. int nChange; /* Statement changes (Vdbe.nChanges) */
  17214. };
  17215. /*
  17216. ** An instance of the virtual machine. This structure contains the complete
  17217. ** state of the virtual machine.
  17218. **
  17219. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
  17220. ** is really a pointer to an instance of this structure.
  17221. **
  17222. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  17223. ** any virtual table method invocations made by the vdbe program. It is
  17224. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  17225. ** variable is used for two purposes: to allow xDestroy methods to execute
  17226. ** "DROP TABLE" statements and to prevent some nasty side effects of
  17227. ** malloc failure when SQLite is invoked recursively by a virtual table
  17228. ** method function.
  17229. */
  17230. struct Vdbe {
  17231. sqlite3 *db; /* The whole database */
  17232. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  17233. int nOp; /* Number of instructions in the program */
  17234. int nOpAlloc; /* Number of slots allocated for aOp[] */
  17235. Op *aOp; /* Space to hold the virtual machine's program */
  17236. int nLabel; /* Number of labels used */
  17237. int nLabelAlloc; /* Number of slots allocated in aLabel[] */
  17238. int *aLabel; /* Space to hold the labels */
  17239. Mem **apArg; /* Arguments to currently executing user function */
  17240. Mem *aColName; /* Column names to return */
  17241. int nCursor; /* Number of slots in apCsr[] */
  17242. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  17243. int nVar; /* Number of entries in aVar[] */
  17244. Mem *aVar; /* Values for the OP_Variable opcode. */
  17245. char **azVar; /* Name of variables */
  17246. int okVar; /* True if azVar[] has been initialized */
  17247. u32 magic; /* Magic number for sanity checking */
  17248. int nMem; /* Number of memory locations currently allocated */
  17249. Mem *aMem; /* The memory locations */
  17250. int nCallback; /* Number of callbacks invoked so far */
  17251. int cacheCtr; /* VdbeCursor row cache generation counter */
  17252. int contextStackTop; /* Index of top element in the context stack */
  17253. int contextStackDepth; /* The size of the "context" stack */
  17254. Context *contextStack; /* Stack used by opcodes ContextPush & ContextPop*/
  17255. int pc; /* The program counter */
  17256. int rc; /* Value to return */
  17257. unsigned uniqueCnt; /* Used by OP_MakeRecord when P2!=0 */
  17258. int errorAction; /* Recovery action to do in case of an error */
  17259. int inTempTrans; /* True if temp database is transactioned */
  17260. int nResColumn; /* Number of columns in one row of the result set */
  17261. char **azResColumn; /* Values for one row of result */
  17262. char *zErrMsg; /* Error message written here */
  17263. Mem *pResultSet; /* Pointer to an array of results */
  17264. u8 explain; /* True if EXPLAIN present on SQL command */
  17265. u8 changeCntOn; /* True to update the change-counter */
  17266. u8 expired; /* True if the VM needs to be recompiled */
  17267. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  17268. u8 inVtabMethod; /* See comments above */
  17269. u8 usesStmtJournal; /* True if uses a statement journal */
  17270. u8 readOnly; /* True for read-only statements */
  17271. int nChange; /* Number of db changes made since last reset */
  17272. i64 startTime; /* Time when query started - used for profiling */
  17273. int btreeMask; /* Bitmask of db->aDb[] entries referenced */
  17274. BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
  17275. int aCounter[2]; /* Counters used by sqlite3_stmt_status() */
  17276. int nSql; /* Number of bytes in zSql */
  17277. char *zSql; /* Text of the SQL statement that generated this */
  17278. #ifdef SQLITE_DEBUG
  17279. FILE *trace; /* Write an execution trace here, if not NULL */
  17280. #endif
  17281. int openedStatement; /* True if this VM has opened a statement journal */
  17282. #ifdef SQLITE_SSE
  17283. int fetchId; /* Statement number used by sqlite3_fetch_statement */
  17284. int lru; /* Counter used for LRU cache replacement */
  17285. #endif
  17286. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17287. Vdbe *pLruPrev;
  17288. Vdbe *pLruNext;
  17289. #endif
  17290. };
  17291. /*
  17292. ** The following are allowed values for Vdbe.magic
  17293. */
  17294. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  17295. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  17296. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  17297. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  17298. /*
  17299. ** Function prototypes
  17300. */
  17301. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  17302. void sqliteVdbePopStack(Vdbe*,int);
  17303. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  17304. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  17305. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  17306. #endif
  17307. SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
  17308. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  17309. SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
  17310. SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  17311. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
  17312. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  17313. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
  17314. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
  17315. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  17316. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  17317. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  17318. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  17319. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  17320. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  17321. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  17322. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  17323. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  17324. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  17325. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  17326. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  17327. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  17328. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  17329. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  17330. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  17331. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  17332. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
  17333. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  17334. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  17335. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  17336. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  17337. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  17338. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  17339. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
  17340. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  17341. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
  17342. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  17343. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  17344. SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
  17345. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  17346. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17347. SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p);
  17348. #endif
  17349. #ifndef NDEBUG
  17350. SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem*);
  17351. #endif
  17352. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  17353. #ifdef SQLITE_DEBUG
  17354. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  17355. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  17356. #endif
  17357. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  17358. #ifndef SQLITE_OMIT_INCRBLOB
  17359. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  17360. #else
  17361. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  17362. #endif
  17363. #endif /* !defined(_VDBEINT_H_) */
  17364. /************** End of vdbeInt.h *********************************************/
  17365. /************** Continuing where we left off in utf.c ************************/
  17366. #ifndef SQLITE_AMALGAMATION
  17367. /*
  17368. ** The following constant value is used by the SQLITE_BIGENDIAN and
  17369. ** SQLITE_LITTLEENDIAN macros.
  17370. */
  17371. SQLITE_PRIVATE const int sqlite3one = 1;
  17372. #endif /* SQLITE_AMALGAMATION */
  17373. /*
  17374. ** This lookup table is used to help decode the first byte of
  17375. ** a multi-byte UTF8 character.
  17376. */
  17377. static const unsigned char sqlite3Utf8Trans1[] = {
  17378. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  17379. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  17380. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  17381. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  17382. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  17383. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  17384. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  17385. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  17386. };
  17387. #define WRITE_UTF8(zOut, c) { \
  17388. if( c<0x00080 ){ \
  17389. *zOut++ = (u8)(c&0xFF); \
  17390. } \
  17391. else if( c<0x00800 ){ \
  17392. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  17393. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  17394. } \
  17395. else if( c<0x10000 ){ \
  17396. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  17397. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  17398. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  17399. }else{ \
  17400. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  17401. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  17402. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  17403. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  17404. } \
  17405. }
  17406. #define WRITE_UTF16LE(zOut, c) { \
  17407. if( c<=0xFFFF ){ \
  17408. *zOut++ = (u8)(c&0x00FF); \
  17409. *zOut++ = (u8)((c>>8)&0x00FF); \
  17410. }else{ \
  17411. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  17412. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  17413. *zOut++ = (u8)(c&0x00FF); \
  17414. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  17415. } \
  17416. }
  17417. #define WRITE_UTF16BE(zOut, c) { \
  17418. if( c<=0xFFFF ){ \
  17419. *zOut++ = (u8)((c>>8)&0x00FF); \
  17420. *zOut++ = (u8)(c&0x00FF); \
  17421. }else{ \
  17422. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  17423. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  17424. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  17425. *zOut++ = (u8)(c&0x00FF); \
  17426. } \
  17427. }
  17428. #define READ_UTF16LE(zIn, c){ \
  17429. c = (*zIn++); \
  17430. c += ((*zIn++)<<8); \
  17431. if( c>=0xD800 && c<0xE000 ){ \
  17432. int c2 = (*zIn++); \
  17433. c2 += ((*zIn++)<<8); \
  17434. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  17435. if( (c & 0xFFFF0000)==0 ) c = 0xFFFD; \
  17436. } \
  17437. }
  17438. #define READ_UTF16BE(zIn, c){ \
  17439. c = ((*zIn++)<<8); \
  17440. c += (*zIn++); \
  17441. if( c>=0xD800 && c<0xE000 ){ \
  17442. int c2 = ((*zIn++)<<8); \
  17443. c2 += (*zIn++); \
  17444. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  17445. if( (c & 0xFFFF0000)==0 ) c = 0xFFFD; \
  17446. } \
  17447. }
  17448. /*
  17449. ** Translate a single UTF-8 character. Return the unicode value.
  17450. **
  17451. ** During translation, assume that the byte that zTerm points
  17452. ** is a 0x00.
  17453. **
  17454. ** Write a pointer to the next unread byte back into *pzNext.
  17455. **
  17456. ** Notes On Invalid UTF-8:
  17457. **
  17458. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  17459. ** be encoded as a multi-byte character. Any multi-byte character that
  17460. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  17461. **
  17462. ** * This routine never allows a UTF16 surrogate value to be encoded.
  17463. ** If a multi-byte character attempts to encode a value between
  17464. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  17465. **
  17466. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  17467. ** byte of a character are interpreted as single-byte characters
  17468. ** and rendered as themselves even though they are technically
  17469. ** invalid characters.
  17470. **
  17471. ** * This routine accepts an infinite number of different UTF8 encodings
  17472. ** for unicode values 0x80 and greater. It do not change over-length
  17473. ** encodings to 0xfffd as some systems recommend.
  17474. */
  17475. #define READ_UTF8(zIn, zTerm, c) \
  17476. c = *(zIn++); \
  17477. if( c>=0xc0 ){ \
  17478. c = sqlite3Utf8Trans1[c-0xc0]; \
  17479. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  17480. c = (c<<6) + (0x3f & *(zIn++)); \
  17481. } \
  17482. if( c<0x80 \
  17483. || (c&0xFFFFF800)==0xD800 \
  17484. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  17485. }
  17486. SQLITE_PRIVATE int sqlite3Utf8Read(
  17487. const unsigned char *z, /* First byte of UTF-8 character */
  17488. const unsigned char *zTerm, /* Pretend this byte is 0x00 */
  17489. const unsigned char **pzNext /* Write first byte past UTF-8 char here */
  17490. ){
  17491. int c;
  17492. READ_UTF8(z, zTerm, c);
  17493. *pzNext = z;
  17494. return c;
  17495. }
  17496. /*
  17497. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  17498. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  17499. */
  17500. /* #define TRANSLATE_TRACE 1 */
  17501. #ifndef SQLITE_OMIT_UTF16
  17502. /*
  17503. ** This routine transforms the internal text encoding used by pMem to
  17504. ** desiredEnc. It is an error if the string is already of the desired
  17505. ** encoding, or if *pMem does not contain a string value.
  17506. */
  17507. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  17508. int len; /* Maximum length of output string in bytes */
  17509. unsigned char *zOut; /* Output buffer */
  17510. unsigned char *zIn; /* Input iterator */
  17511. unsigned char *zTerm; /* End of input */
  17512. unsigned char *z; /* Output iterator */
  17513. unsigned int c;
  17514. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  17515. assert( pMem->flags&MEM_Str );
  17516. assert( pMem->enc!=desiredEnc );
  17517. assert( pMem->enc!=0 );
  17518. assert( pMem->n>=0 );
  17519. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  17520. {
  17521. char zBuf[100];
  17522. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  17523. fprintf(stderr, "INPUT: %s\n", zBuf);
  17524. }
  17525. #endif
  17526. /* If the translation is between UTF-16 little and big endian, then
  17527. ** all that is required is to swap the byte order. This case is handled
  17528. ** differently from the others.
  17529. */
  17530. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  17531. u8 temp;
  17532. int rc;
  17533. rc = sqlite3VdbeMemMakeWriteable(pMem);
  17534. if( rc!=SQLITE_OK ){
  17535. assert( rc==SQLITE_NOMEM );
  17536. return SQLITE_NOMEM;
  17537. }
  17538. zIn = (u8*)pMem->z;
  17539. zTerm = &zIn[pMem->n&~1];
  17540. while( zIn<zTerm ){
  17541. temp = *zIn;
  17542. *zIn = *(zIn+1);
  17543. zIn++;
  17544. *zIn++ = temp;
  17545. }
  17546. pMem->enc = desiredEnc;
  17547. goto translate_out;
  17548. }
  17549. /* Set len to the maximum number of bytes required in the output buffer. */
  17550. if( desiredEnc==SQLITE_UTF8 ){
  17551. /* When converting from UTF-16, the maximum growth results from
  17552. ** translating a 2-byte character to a 4-byte UTF-8 character.
  17553. ** A single byte is required for the output string
  17554. ** nul-terminator.
  17555. */
  17556. pMem->n &= ~1;
  17557. len = pMem->n * 2 + 1;
  17558. }else{
  17559. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  17560. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  17561. ** character. Two bytes are required in the output buffer for the
  17562. ** nul-terminator.
  17563. */
  17564. len = pMem->n * 2 + 2;
  17565. }
  17566. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  17567. ** byte past the end.
  17568. **
  17569. ** Variable zOut is set to point at the output buffer, space obtained
  17570. ** from sqlite3_malloc().
  17571. */
  17572. zIn = (u8*)pMem->z;
  17573. zTerm = &zIn[pMem->n];
  17574. zOut = sqlite3DbMallocRaw(pMem->db, len);
  17575. if( !zOut ){
  17576. return SQLITE_NOMEM;
  17577. }
  17578. z = zOut;
  17579. if( pMem->enc==SQLITE_UTF8 ){
  17580. if( desiredEnc==SQLITE_UTF16LE ){
  17581. /* UTF-8 -> UTF-16 Little-endian */
  17582. while( zIn<zTerm ){
  17583. /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
  17584. READ_UTF8(zIn, zTerm, c);
  17585. WRITE_UTF16LE(z, c);
  17586. }
  17587. }else{
  17588. assert( desiredEnc==SQLITE_UTF16BE );
  17589. /* UTF-8 -> UTF-16 Big-endian */
  17590. while( zIn<zTerm ){
  17591. /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
  17592. READ_UTF8(zIn, zTerm, c);
  17593. WRITE_UTF16BE(z, c);
  17594. }
  17595. }
  17596. pMem->n = (int)(z - zOut);
  17597. *z++ = 0;
  17598. }else{
  17599. assert( desiredEnc==SQLITE_UTF8 );
  17600. if( pMem->enc==SQLITE_UTF16LE ){
  17601. /* UTF-16 Little-endian -> UTF-8 */
  17602. while( zIn<zTerm ){
  17603. READ_UTF16LE(zIn, c);
  17604. WRITE_UTF8(z, c);
  17605. }
  17606. }else{
  17607. /* UTF-16 Big-endian -> UTF-8 */
  17608. while( zIn<zTerm ){
  17609. READ_UTF16BE(zIn, c);
  17610. WRITE_UTF8(z, c);
  17611. }
  17612. }
  17613. pMem->n = (int)(z - zOut);
  17614. }
  17615. *z = 0;
  17616. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  17617. sqlite3VdbeMemRelease(pMem);
  17618. pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  17619. pMem->enc = desiredEnc;
  17620. pMem->flags |= (MEM_Term|MEM_Dyn);
  17621. pMem->z = (char*)zOut;
  17622. pMem->zMalloc = pMem->z;
  17623. translate_out:
  17624. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  17625. {
  17626. char zBuf[100];
  17627. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  17628. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  17629. }
  17630. #endif
  17631. return SQLITE_OK;
  17632. }
  17633. /*
  17634. ** This routine checks for a byte-order mark at the beginning of the
  17635. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  17636. ** the encoding of the Mem adjusted. This routine does not do any
  17637. ** byte-swapping, it just sets Mem.enc appropriately.
  17638. **
  17639. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  17640. ** changed by this function.
  17641. */
  17642. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  17643. int rc = SQLITE_OK;
  17644. u8 bom = 0;
  17645. if( pMem->n<0 || pMem->n>1 ){
  17646. u8 b1 = *(u8 *)pMem->z;
  17647. u8 b2 = *(((u8 *)pMem->z) + 1);
  17648. if( b1==0xFE && b2==0xFF ){
  17649. bom = SQLITE_UTF16BE;
  17650. }
  17651. if( b1==0xFF && b2==0xFE ){
  17652. bom = SQLITE_UTF16LE;
  17653. }
  17654. }
  17655. if( bom ){
  17656. rc = sqlite3VdbeMemMakeWriteable(pMem);
  17657. if( rc==SQLITE_OK ){
  17658. pMem->n -= 2;
  17659. memmove(pMem->z, &pMem->z[2], pMem->n);
  17660. pMem->z[pMem->n] = '\0';
  17661. pMem->z[pMem->n+1] = '\0';
  17662. pMem->flags |= MEM_Term;
  17663. pMem->enc = bom;
  17664. }
  17665. }
  17666. return rc;
  17667. }
  17668. #endif /* SQLITE_OMIT_UTF16 */
  17669. /*
  17670. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  17671. ** return the number of unicode characters in pZ up to (but not including)
  17672. ** the first 0x00 byte. If nByte is not less than zero, return the
  17673. ** number of unicode characters in the first nByte of pZ (or up to
  17674. ** the first 0x00, whichever comes first).
  17675. */
  17676. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  17677. int r = 0;
  17678. const u8 *z = (const u8*)zIn;
  17679. const u8 *zTerm;
  17680. if( nByte>=0 ){
  17681. zTerm = &z[nByte];
  17682. }else{
  17683. zTerm = (const u8*)(-1);
  17684. }
  17685. assert( z<=zTerm );
  17686. while( *z!=0 && z<zTerm ){
  17687. SQLITE_SKIP_UTF8(z);
  17688. r++;
  17689. }
  17690. return r;
  17691. }
  17692. /* This test function is not currently used by the automated test-suite.
  17693. ** Hence it is only available in debug builds.
  17694. */
  17695. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  17696. /*
  17697. ** Translate UTF-8 to UTF-8.
  17698. **
  17699. ** This has the effect of making sure that the string is well-formed
  17700. ** UTF-8. Miscoded characters are removed.
  17701. **
  17702. ** The translation is done in-place (since it is impossible for the
  17703. ** correct UTF-8 encoding to be longer than a malformed encoding).
  17704. */
  17705. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  17706. unsigned char *zOut = zIn;
  17707. unsigned char *zStart = zIn;
  17708. unsigned char *zTerm = &zIn[sqlite3Strlen30((char *)zIn)];
  17709. u32 c;
  17710. while( zIn[0] ){
  17711. c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
  17712. if( c!=0xfffd ){
  17713. WRITE_UTF8(zOut, c);
  17714. }
  17715. }
  17716. *zOut = 0;
  17717. return zOut - zStart;
  17718. }
  17719. #endif
  17720. #ifndef SQLITE_OMIT_UTF16
  17721. /*
  17722. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  17723. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  17724. ** be freed by the calling function.
  17725. **
  17726. ** NULL is returned if there is an allocation error.
  17727. */
  17728. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
  17729. Mem m;
  17730. memset(&m, 0, sizeof(m));
  17731. m.db = db;
  17732. sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  17733. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  17734. if( db->mallocFailed ){
  17735. sqlite3VdbeMemRelease(&m);
  17736. m.z = 0;
  17737. }
  17738. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  17739. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  17740. return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
  17741. }
  17742. /*
  17743. ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
  17744. ** return the number of bytes up to (but not including), the first pair
  17745. ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
  17746. ** then return the number of bytes in the first nChar unicode characters
  17747. ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
  17748. */
  17749. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  17750. unsigned int c = 1;
  17751. char const *z = zIn;
  17752. int n = 0;
  17753. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  17754. /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
  17755. ** and in other parts of this file means that at one branch will
  17756. ** not be covered by coverage testing on any single host. But coverage
  17757. ** will be complete if the tests are run on both a little-endian and
  17758. ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
  17759. ** macros are constant at compile time the compiler can determine
  17760. ** which branch will be followed. It is therefore assumed that no runtime
  17761. ** penalty is paid for this "if" statement.
  17762. */
  17763. while( c && ((nChar<0) || n<nChar) ){
  17764. READ_UTF16BE(z, c);
  17765. n++;
  17766. }
  17767. }else{
  17768. while( c && ((nChar<0) || n<nChar) ){
  17769. READ_UTF16LE(z, c);
  17770. n++;
  17771. }
  17772. }
  17773. return (int)(z-(char const *)zIn)-((c==0)?2:0);
  17774. }
  17775. #if defined(SQLITE_TEST)
  17776. /*
  17777. ** This routine is called from the TCL test function "translate_selftest".
  17778. ** It checks that the primitives for serializing and deserializing
  17779. ** characters in each encoding are inverses of each other.
  17780. */
  17781. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  17782. unsigned int i, t;
  17783. unsigned char zBuf[20];
  17784. unsigned char *z;
  17785. unsigned char *zTerm;
  17786. int n;
  17787. unsigned int c;
  17788. for(i=0; i<0x00110000; i++){
  17789. z = zBuf;
  17790. WRITE_UTF8(z, i);
  17791. n = (int)(z-zBuf);
  17792. assert( n>0 && n<=4 );
  17793. z[0] = 0;
  17794. zTerm = z;
  17795. z = zBuf;
  17796. c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
  17797. t = i;
  17798. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  17799. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  17800. assert( c==t );
  17801. assert( (z-zBuf)==n );
  17802. }
  17803. for(i=0; i<0x00110000; i++){
  17804. if( i>=0xD800 && i<0xE000 ) continue;
  17805. z = zBuf;
  17806. WRITE_UTF16LE(z, i);
  17807. n = (int)(z-zBuf);
  17808. assert( n>0 && n<=4 );
  17809. z[0] = 0;
  17810. z = zBuf;
  17811. READ_UTF16LE(z, c);
  17812. assert( c==i );
  17813. assert( (z-zBuf)==n );
  17814. }
  17815. for(i=0; i<0x00110000; i++){
  17816. if( i>=0xD800 && i<0xE000 ) continue;
  17817. z = zBuf;
  17818. WRITE_UTF16BE(z, i);
  17819. n = (int)(z-zBuf);
  17820. assert( n>0 && n<=4 );
  17821. z[0] = 0;
  17822. z = zBuf;
  17823. READ_UTF16BE(z, c);
  17824. assert( c==i );
  17825. assert( (z-zBuf)==n );
  17826. }
  17827. }
  17828. #endif /* SQLITE_TEST */
  17829. #endif /* SQLITE_OMIT_UTF16 */
  17830. /************** End of utf.c *************************************************/
  17831. /************** Begin file util.c ********************************************/
  17832. /*
  17833. ** 2001 September 15
  17834. **
  17835. ** The author disclaims copyright to this source code. In place of
  17836. ** a legal notice, here is a blessing:
  17837. **
  17838. ** May you do good and not evil.
  17839. ** May you find forgiveness for yourself and forgive others.
  17840. ** May you share freely, never taking more than you give.
  17841. **
  17842. *************************************************************************
  17843. ** Utility functions used throughout sqlite.
  17844. **
  17845. ** This file contains functions for allocating memory, comparing
  17846. ** strings, and stuff like that.
  17847. **
  17848. ** $Id: util.c,v 1.246 2009/01/10 16:15:22 drh Exp $
  17849. */
  17850. /*
  17851. ** Routine needed to support the testcase() macro.
  17852. */
  17853. #ifdef SQLITE_COVERAGE_TEST
  17854. SQLITE_PRIVATE void sqlite3Coverage(int x){
  17855. static int dummy = 0;
  17856. dummy += x;
  17857. }
  17858. #endif
  17859. /*
  17860. ** Routine needed to support the ALWAYS() and NEVER() macros.
  17861. **
  17862. ** The argument to ALWAYS() should always be true and the argument
  17863. ** to NEVER() should always be false. If either is not the case
  17864. ** then this routine is called in order to throw an error.
  17865. **
  17866. ** This routine only exists if assert() is operational. It always
  17867. ** throws an assert on its first invocation. The variable has a long
  17868. ** name to help the assert() message be more readable. The variable
  17869. ** is used to prevent a too-clever optimizer from optimizing out the
  17870. ** entire call.
  17871. */
  17872. #ifndef NDEBUG
  17873. SQLITE_PRIVATE int sqlite3Assert(void){
  17874. static volatile int ALWAYS_was_false_or_NEVER_was_true = 0;
  17875. assert( ALWAYS_was_false_or_NEVER_was_true ); /* Always fails */
  17876. return ALWAYS_was_false_or_NEVER_was_true++; /* Not Reached */
  17877. }
  17878. #endif
  17879. /*
  17880. ** Return true if the floating point value is Not a Number (NaN).
  17881. */
  17882. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  17883. /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
  17884. ** On the other hand, the use of -ffast-math comes with the following
  17885. ** warning:
  17886. **
  17887. ** This option [-ffast-math] should never be turned on by any
  17888. ** -O option since it can result in incorrect output for programs
  17889. ** which depend on an exact implementation of IEEE or ISO
  17890. ** rules/specifications for math functions.
  17891. **
  17892. ** Under MSVC, this NaN test may fail if compiled with a floating-
  17893. ** point precision mode other than /fp:precise. From the MSDN
  17894. ** documentation:
  17895. **
  17896. ** The compiler [with /fp:precise] will properly handle comparisons
  17897. ** involving NaN. For example, x != x evaluates to true if x is NaN
  17898. ** ...
  17899. */
  17900. #ifdef __FAST_MATH__
  17901. # error SQLite will not work correctly with the -ffast-math option of GCC.
  17902. #endif
  17903. volatile double y = x;
  17904. volatile double z = y;
  17905. return y!=z;
  17906. }
  17907. /*
  17908. ** Compute a string length that is limited to what can be stored in
  17909. ** lower 30 bits of a 32-bit signed integer.
  17910. */
  17911. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  17912. const char *z2 = z;
  17913. while( *z2 ){ z2++; }
  17914. return 0x3fffffff & (int)(z2 - z);
  17915. }
  17916. /*
  17917. ** Return the length of a string, except do not allow the string length
  17918. ** to exceed the SQLITE_LIMIT_LENGTH setting.
  17919. */
  17920. SQLITE_PRIVATE int sqlite3Strlen(sqlite3 *db, const char *z){
  17921. const char *z2 = z;
  17922. int len;
  17923. int x;
  17924. while( *z2 ){ z2++; }
  17925. x = (int)(z2 - z);
  17926. len = 0x7fffffff & x;
  17927. if( len!=x || len > db->aLimit[SQLITE_LIMIT_LENGTH] ){
  17928. return db->aLimit[SQLITE_LIMIT_LENGTH];
  17929. }else{
  17930. return len;
  17931. }
  17932. }
  17933. /*
  17934. ** Set the most recent error code and error string for the sqlite
  17935. ** handle "db". The error code is set to "err_code".
  17936. **
  17937. ** If it is not NULL, string zFormat specifies the format of the
  17938. ** error string in the style of the printf functions: The following
  17939. ** format characters are allowed:
  17940. **
  17941. ** %s Insert a string
  17942. ** %z A string that should be freed after use
  17943. ** %d Insert an integer
  17944. ** %T Insert a token
  17945. ** %S Insert the first element of a SrcList
  17946. **
  17947. ** zFormat and any string tokens that follow it are assumed to be
  17948. ** encoded in UTF-8.
  17949. **
  17950. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  17951. ** should be called with err_code set to SQLITE_OK and zFormat set
  17952. ** to NULL.
  17953. */
  17954. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  17955. if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
  17956. db->errCode = err_code;
  17957. if( zFormat ){
  17958. char *z;
  17959. va_list ap;
  17960. va_start(ap, zFormat);
  17961. z = sqlite3VMPrintf(db, zFormat, ap);
  17962. va_end(ap);
  17963. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  17964. }else{
  17965. sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  17966. }
  17967. }
  17968. }
  17969. /*
  17970. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  17971. ** The following formatting characters are allowed:
  17972. **
  17973. ** %s Insert a string
  17974. ** %z A string that should be freed after use
  17975. ** %d Insert an integer
  17976. ** %T Insert a token
  17977. ** %S Insert the first element of a SrcList
  17978. **
  17979. ** This function should be used to report any error that occurs whilst
  17980. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  17981. ** last thing the sqlite3_prepare() function does is copy the error
  17982. ** stored by this function into the database handle using sqlite3Error().
  17983. ** Function sqlite3Error() should be used during statement execution
  17984. ** (sqlite3_step() etc.).
  17985. */
  17986. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  17987. va_list ap;
  17988. sqlite3 *db = pParse->db;
  17989. pParse->nErr++;
  17990. sqlite3DbFree(db, pParse->zErrMsg);
  17991. va_start(ap, zFormat);
  17992. pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
  17993. va_end(ap);
  17994. if( pParse->rc==SQLITE_OK ){
  17995. pParse->rc = SQLITE_ERROR;
  17996. }
  17997. }
  17998. /*
  17999. ** Clear the error message in pParse, if any
  18000. */
  18001. SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
  18002. sqlite3DbFree(pParse->db, pParse->zErrMsg);
  18003. pParse->zErrMsg = 0;
  18004. pParse->nErr = 0;
  18005. }
  18006. /*
  18007. ** Convert an SQL-style quoted string into a normal string by removing
  18008. ** the quote characters. The conversion is done in-place. If the
  18009. ** input does not begin with a quote character, then this routine
  18010. ** is a no-op.
  18011. **
  18012. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  18013. ** brackets from around identifers. For example: "[a-b-c]" becomes
  18014. ** "a-b-c".
  18015. */
  18016. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  18017. char quote;
  18018. int i, j;
  18019. if( z==0 ) return;
  18020. quote = z[0];
  18021. switch( quote ){
  18022. case '\'': break;
  18023. case '"': break;
  18024. case '`': break; /* For MySQL compatibility */
  18025. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  18026. default: return;
  18027. }
  18028. for(i=1, j=0; z[i]; i++){
  18029. if( z[i]==quote ){
  18030. if( z[i+1]==quote ){
  18031. z[j++] = quote;
  18032. i++;
  18033. }else{
  18034. z[j++] = 0;
  18035. break;
  18036. }
  18037. }else{
  18038. z[j++] = z[i];
  18039. }
  18040. }
  18041. }
  18042. /* Convenient short-hand */
  18043. #define UpperToLower sqlite3UpperToLower
  18044. /*
  18045. ** Some systems have stricmp(). Others have strcasecmp(). Because
  18046. ** there is no consistency, we will define our own.
  18047. */
  18048. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  18049. register unsigned char *a, *b;
  18050. a = (unsigned char *)zLeft;
  18051. b = (unsigned char *)zRight;
  18052. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  18053. return UpperToLower[*a] - UpperToLower[*b];
  18054. }
  18055. SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
  18056. register unsigned char *a, *b;
  18057. a = (unsigned char *)zLeft;
  18058. b = (unsigned char *)zRight;
  18059. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  18060. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  18061. }
  18062. /*
  18063. ** Return TRUE if z is a pure numeric string. Return FALSE if the
  18064. ** string contains any character which is not part of a number. If
  18065. ** the string is numeric and contains the '.' character, set *realnum
  18066. ** to TRUE (otherwise FALSE).
  18067. **
  18068. ** An empty string is considered non-numeric.
  18069. */
  18070. SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
  18071. int incr = (enc==SQLITE_UTF8?1:2);
  18072. if( enc==SQLITE_UTF16BE ) z++;
  18073. if( *z=='-' || *z=='+' ) z += incr;
  18074. if( !isdigit(*(u8*)z) ){
  18075. return 0;
  18076. }
  18077. z += incr;
  18078. if( realnum ) *realnum = 0;
  18079. while( isdigit(*(u8*)z) ){ z += incr; }
  18080. if( *z=='.' ){
  18081. z += incr;
  18082. if( !isdigit(*(u8*)z) ) return 0;
  18083. while( isdigit(*(u8*)z) ){ z += incr; }
  18084. if( realnum ) *realnum = 1;
  18085. }
  18086. if( *z=='e' || *z=='E' ){
  18087. z += incr;
  18088. if( *z=='+' || *z=='-' ) z += incr;
  18089. if( !isdigit(*(u8*)z) ) return 0;
  18090. while( isdigit(*(u8*)z) ){ z += incr; }
  18091. if( realnum ) *realnum = 1;
  18092. }
  18093. return *z==0;
  18094. }
  18095. /*
  18096. ** The string z[] is an ascii representation of a real number.
  18097. ** Convert this string to a double.
  18098. **
  18099. ** This routine assumes that z[] really is a valid number. If it
  18100. ** is not, the result is undefined.
  18101. **
  18102. ** This routine is used instead of the library atof() function because
  18103. ** the library atof() might want to use "," as the decimal point instead
  18104. ** of "." depending on how locale is set. But that would cause problems
  18105. ** for SQL. So this routine always uses "." regardless of locale.
  18106. */
  18107. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
  18108. #ifndef SQLITE_OMIT_FLOATING_POINT
  18109. int sign = 1;
  18110. const char *zBegin = z;
  18111. LONGDOUBLE_TYPE v1 = 0.0;
  18112. int nSignificant = 0;
  18113. while( isspace(*(u8*)z) ) z++;
  18114. if( *z=='-' ){
  18115. sign = -1;
  18116. z++;
  18117. }else if( *z=='+' ){
  18118. z++;
  18119. }
  18120. while( z[0]=='0' ){
  18121. z++;
  18122. }
  18123. while( isdigit(*(u8*)z) ){
  18124. v1 = v1*10.0 + (*z - '0');
  18125. z++;
  18126. nSignificant++;
  18127. }
  18128. if( *z=='.' ){
  18129. LONGDOUBLE_TYPE divisor = 1.0;
  18130. z++;
  18131. if( nSignificant==0 ){
  18132. while( z[0]=='0' ){
  18133. divisor *= 10.0;
  18134. z++;
  18135. }
  18136. }
  18137. while( isdigit(*(u8*)z) ){
  18138. if( nSignificant<18 ){
  18139. v1 = v1*10.0 + (*z - '0');
  18140. divisor *= 10.0;
  18141. nSignificant++;
  18142. }
  18143. z++;
  18144. }
  18145. v1 /= divisor;
  18146. }
  18147. if( *z=='e' || *z=='E' ){
  18148. int esign = 1;
  18149. int eval = 0;
  18150. LONGDOUBLE_TYPE scale = 1.0;
  18151. z++;
  18152. if( *z=='-' ){
  18153. esign = -1;
  18154. z++;
  18155. }else if( *z=='+' ){
  18156. z++;
  18157. }
  18158. while( isdigit(*(u8*)z) ){
  18159. eval = eval*10 + *z - '0';
  18160. z++;
  18161. }
  18162. while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
  18163. while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
  18164. while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
  18165. while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
  18166. if( esign<0 ){
  18167. v1 /= scale;
  18168. }else{
  18169. v1 *= scale;
  18170. }
  18171. }
  18172. *pResult = (double)(sign<0 ? -v1 : v1);
  18173. return (int)(z - zBegin);
  18174. #else
  18175. return sqlite3Atoi64(z, pResult);
  18176. #endif /* SQLITE_OMIT_FLOATING_POINT */
  18177. }
  18178. /*
  18179. ** Compare the 19-character string zNum against the text representation
  18180. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  18181. ** if zNum is less than, equal to, or greater than the string.
  18182. **
  18183. ** Unlike memcmp() this routine is guaranteed to return the difference
  18184. ** in the values of the last digit if the only difference is in the
  18185. ** last digit. So, for example,
  18186. **
  18187. ** compare2pow63("9223372036854775800")
  18188. **
  18189. ** will return -8.
  18190. */
  18191. static int compare2pow63(const char *zNum){
  18192. int c;
  18193. c = memcmp(zNum,"922337203685477580",18);
  18194. if( c==0 ){
  18195. c = zNum[18] - '8';
  18196. }
  18197. return c;
  18198. }
  18199. /*
  18200. ** Return TRUE if zNum is a 64-bit signed integer and write
  18201. ** the value of the integer into *pNum. If zNum is not an integer
  18202. ** or is an integer that is too large to be expressed with 64 bits,
  18203. ** then return false.
  18204. **
  18205. ** When this routine was originally written it dealt with only
  18206. ** 32-bit numbers. At that time, it was much faster than the
  18207. ** atoi() library routine in RedHat 7.2.
  18208. */
  18209. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
  18210. i64 v = 0;
  18211. int neg;
  18212. int i, c;
  18213. const char *zStart;
  18214. while( isspace(*(u8*)zNum) ) zNum++;
  18215. if( *zNum=='-' ){
  18216. neg = 1;
  18217. zNum++;
  18218. }else if( *zNum=='+' ){
  18219. neg = 0;
  18220. zNum++;
  18221. }else{
  18222. neg = 0;
  18223. }
  18224. zStart = zNum;
  18225. while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
  18226. for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
  18227. v = v*10 + c - '0';
  18228. }
  18229. *pNum = neg ? -v : v;
  18230. if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
  18231. /* zNum is empty or contains non-numeric text or is longer
  18232. ** than 19 digits (thus guaranting that it is too large) */
  18233. return 0;
  18234. }else if( i<19 ){
  18235. /* Less than 19 digits, so we know that it fits in 64 bits */
  18236. return 1;
  18237. }else{
  18238. /* 19-digit numbers must be no larger than 9223372036854775807 if positive
  18239. ** or 9223372036854775808 if negative. Note that 9223372036854665808
  18240. ** is 2^63. */
  18241. return compare2pow63(zNum)<neg;
  18242. }
  18243. }
  18244. /*
  18245. ** The string zNum represents an integer. There might be some other
  18246. ** information following the integer too, but that part is ignored.
  18247. ** If the integer that the prefix of zNum represents will fit in a
  18248. ** 64-bit signed integer, return TRUE. Otherwise return FALSE.
  18249. **
  18250. ** This routine returns FALSE for the string -9223372036854775808 even that
  18251. ** that number will, in theory fit in a 64-bit integer. Positive
  18252. ** 9223373036854775808 will not fit in 64 bits. So it seems safer to return
  18253. ** false.
  18254. */
  18255. SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
  18256. int i, c;
  18257. int neg = 0;
  18258. if( *zNum=='-' ){
  18259. neg = 1;
  18260. zNum++;
  18261. }else if( *zNum=='+' ){
  18262. zNum++;
  18263. }
  18264. if( negFlag ) neg = 1-neg;
  18265. while( *zNum=='0' ){
  18266. zNum++; /* Skip leading zeros. Ticket #2454 */
  18267. }
  18268. for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
  18269. if( i<19 ){
  18270. /* Guaranteed to fit if less than 19 digits */
  18271. return 1;
  18272. }else if( i>19 ){
  18273. /* Guaranteed to be too big if greater than 19 digits */
  18274. return 0;
  18275. }else{
  18276. /* Compare against 2^63. */
  18277. return compare2pow63(zNum)<neg;
  18278. }
  18279. }
  18280. /*
  18281. ** If zNum represents an integer that will fit in 32-bits, then set
  18282. ** *pValue to that integer and return true. Otherwise return false.
  18283. **
  18284. ** Any non-numeric characters that following zNum are ignored.
  18285. ** This is different from sqlite3Atoi64() which requires the
  18286. ** input number to be zero-terminated.
  18287. */
  18288. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  18289. sqlite_int64 v = 0;
  18290. int i, c;
  18291. int neg = 0;
  18292. if( zNum[0]=='-' ){
  18293. neg = 1;
  18294. zNum++;
  18295. }else if( zNum[0]=='+' ){
  18296. zNum++;
  18297. }
  18298. while( zNum[0]=='0' ) zNum++;
  18299. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  18300. v = v*10 + c;
  18301. }
  18302. /* The longest decimal representation of a 32 bit integer is 10 digits:
  18303. **
  18304. ** 1234567890
  18305. ** 2^31 -> 2147483648
  18306. */
  18307. if( i>10 ){
  18308. return 0;
  18309. }
  18310. if( v-neg>2147483647 ){
  18311. return 0;
  18312. }
  18313. if( neg ){
  18314. v = -v;
  18315. }
  18316. *pValue = (int)v;
  18317. return 1;
  18318. }
  18319. /*
  18320. ** The variable-length integer encoding is as follows:
  18321. **
  18322. ** KEY:
  18323. ** A = 0xxxxxxx 7 bits of data and one flag bit
  18324. ** B = 1xxxxxxx 7 bits of data and one flag bit
  18325. ** C = xxxxxxxx 8 bits of data
  18326. **
  18327. ** 7 bits - A
  18328. ** 14 bits - BA
  18329. ** 21 bits - BBA
  18330. ** 28 bits - BBBA
  18331. ** 35 bits - BBBBA
  18332. ** 42 bits - BBBBBA
  18333. ** 49 bits - BBBBBBA
  18334. ** 56 bits - BBBBBBBA
  18335. ** 64 bits - BBBBBBBBC
  18336. */
  18337. /*
  18338. ** Write a 64-bit variable-length integer to memory starting at p[0].
  18339. ** The length of data write will be between 1 and 9 bytes. The number
  18340. ** of bytes written is returned.
  18341. **
  18342. ** A variable-length integer consists of the lower 7 bits of each byte
  18343. ** for all bytes that have the 8th bit set and one byte with the 8th
  18344. ** bit clear. Except, if we get to the 9th byte, it stores the full
  18345. ** 8 bits and is the last byte.
  18346. */
  18347. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  18348. int i, j, n;
  18349. u8 buf[10];
  18350. if( v & (((u64)0xff000000)<<32) ){
  18351. p[8] = (u8)v;
  18352. v >>= 8;
  18353. for(i=7; i>=0; i--){
  18354. p[i] = (u8)((v & 0x7f) | 0x80);
  18355. v >>= 7;
  18356. }
  18357. return 9;
  18358. }
  18359. n = 0;
  18360. do{
  18361. buf[n++] = (u8)((v & 0x7f) | 0x80);
  18362. v >>= 7;
  18363. }while( v!=0 );
  18364. buf[0] &= 0x7f;
  18365. assert( n<=9 );
  18366. for(i=0, j=n-1; j>=0; j--, i++){
  18367. p[i] = buf[j];
  18368. }
  18369. return n;
  18370. }
  18371. /*
  18372. ** This routine is a faster version of sqlite3PutVarint() that only
  18373. ** works for 32-bit positive integers and which is optimized for
  18374. ** the common case of small integers. A MACRO version, putVarint32,
  18375. ** is provided which inlines the single-byte case. All code should use
  18376. ** the MACRO version as this function assumes the single-byte case has
  18377. ** already been handled.
  18378. */
  18379. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
  18380. #ifndef putVarint32
  18381. if( (v & ~0x7f)==0 ){
  18382. p[0] = v;
  18383. return 1;
  18384. }
  18385. #endif
  18386. if( (v & ~0x3fff)==0 ){
  18387. p[0] = (u8)((v>>7) | 0x80);
  18388. p[1] = (u8)(v & 0x7f);
  18389. return 2;
  18390. }
  18391. return sqlite3PutVarint(p, v);
  18392. }
  18393. /*
  18394. ** Read a 64-bit variable-length integer from memory starting at p[0].
  18395. ** Return the number of bytes read. The value is stored in *v.
  18396. */
  18397. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  18398. u32 a,b,s;
  18399. a = *p;
  18400. /* a: p0 (unmasked) */
  18401. if (!(a&0x80))
  18402. {
  18403. *v = a;
  18404. return 1;
  18405. }
  18406. p++;
  18407. b = *p;
  18408. /* b: p1 (unmasked) */
  18409. if (!(b&0x80))
  18410. {
  18411. a &= 0x7f;
  18412. a = a<<7;
  18413. a |= b;
  18414. *v = a;
  18415. return 2;
  18416. }
  18417. p++;
  18418. a = a<<14;
  18419. a |= *p;
  18420. /* a: p0<<14 | p2 (unmasked) */
  18421. if (!(a&0x80))
  18422. {
  18423. a &= (0x7f<<14)|(0x7f);
  18424. b &= 0x7f;
  18425. b = b<<7;
  18426. a |= b;
  18427. *v = a;
  18428. return 3;
  18429. }
  18430. /* CSE1 from below */
  18431. a &= (0x7f<<14)|(0x7f);
  18432. p++;
  18433. b = b<<14;
  18434. b |= *p;
  18435. /* b: p1<<14 | p3 (unmasked) */
  18436. if (!(b&0x80))
  18437. {
  18438. b &= (0x7f<<14)|(0x7f);
  18439. /* moved CSE1 up */
  18440. /* a &= (0x7f<<14)|(0x7f); */
  18441. a = a<<7;
  18442. a |= b;
  18443. *v = a;
  18444. return 4;
  18445. }
  18446. /* a: p0<<14 | p2 (masked) */
  18447. /* b: p1<<14 | p3 (unmasked) */
  18448. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  18449. /* moved CSE1 up */
  18450. /* a &= (0x7f<<14)|(0x7f); */
  18451. b &= (0x7f<<14)|(0x7f);
  18452. s = a;
  18453. /* s: p0<<14 | p2 (masked) */
  18454. p++;
  18455. a = a<<14;
  18456. a |= *p;
  18457. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  18458. if (!(a&0x80))
  18459. {
  18460. /* we can skip these cause they were (effectively) done above in calc'ing s */
  18461. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  18462. /* b &= (0x7f<<14)|(0x7f); */
  18463. b = b<<7;
  18464. a |= b;
  18465. s = s>>18;
  18466. *v = ((u64)s)<<32 | a;
  18467. return 5;
  18468. }
  18469. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  18470. s = s<<7;
  18471. s |= b;
  18472. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  18473. p++;
  18474. b = b<<14;
  18475. b |= *p;
  18476. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  18477. if (!(b&0x80))
  18478. {
  18479. /* we can skip this cause it was (effectively) done above in calc'ing s */
  18480. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  18481. a &= (0x7f<<14)|(0x7f);
  18482. a = a<<7;
  18483. a |= b;
  18484. s = s>>18;
  18485. *v = ((u64)s)<<32 | a;
  18486. return 6;
  18487. }
  18488. p++;
  18489. a = a<<14;
  18490. a |= *p;
  18491. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  18492. if (!(a&0x80))
  18493. {
  18494. a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
  18495. b &= (0x7f<<14)|(0x7f);
  18496. b = b<<7;
  18497. a |= b;
  18498. s = s>>11;
  18499. *v = ((u64)s)<<32 | a;
  18500. return 7;
  18501. }
  18502. /* CSE2 from below */
  18503. a &= (0x7f<<14)|(0x7f);
  18504. p++;
  18505. b = b<<14;
  18506. b |= *p;
  18507. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  18508. if (!(b&0x80))
  18509. {
  18510. b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
  18511. /* moved CSE2 up */
  18512. /* a &= (0x7f<<14)|(0x7f); */
  18513. a = a<<7;
  18514. a |= b;
  18515. s = s>>4;
  18516. *v = ((u64)s)<<32 | a;
  18517. return 8;
  18518. }
  18519. p++;
  18520. a = a<<15;
  18521. a |= *p;
  18522. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  18523. /* moved CSE2 up */
  18524. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  18525. b &= (0x7f<<14)|(0x7f);
  18526. b = b<<8;
  18527. a |= b;
  18528. s = s<<4;
  18529. b = p[-4];
  18530. b &= 0x7f;
  18531. b = b>>3;
  18532. s |= b;
  18533. *v = ((u64)s)<<32 | a;
  18534. return 9;
  18535. }
  18536. /*
  18537. ** Read a 32-bit variable-length integer from memory starting at p[0].
  18538. ** Return the number of bytes read. The value is stored in *v.
  18539. ** A MACRO version, getVarint32, is provided which inlines the
  18540. ** single-byte case. All code should use the MACRO version as
  18541. ** this function assumes the single-byte case has already been handled.
  18542. */
  18543. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  18544. u32 a,b;
  18545. a = *p;
  18546. /* a: p0 (unmasked) */
  18547. #ifndef getVarint32
  18548. if (!(a&0x80))
  18549. {
  18550. *v = a;
  18551. return 1;
  18552. }
  18553. #endif
  18554. p++;
  18555. b = *p;
  18556. /* b: p1 (unmasked) */
  18557. if (!(b&0x80))
  18558. {
  18559. a &= 0x7f;
  18560. a = a<<7;
  18561. *v = a | b;
  18562. return 2;
  18563. }
  18564. p++;
  18565. a = a<<14;
  18566. a |= *p;
  18567. /* a: p0<<14 | p2 (unmasked) */
  18568. if (!(a&0x80))
  18569. {
  18570. a &= (0x7f<<14)|(0x7f);
  18571. b &= 0x7f;
  18572. b = b<<7;
  18573. *v = a | b;
  18574. return 3;
  18575. }
  18576. p++;
  18577. b = b<<14;
  18578. b |= *p;
  18579. /* b: p1<<14 | p3 (unmasked) */
  18580. if (!(b&0x80))
  18581. {
  18582. b &= (0x7f<<14)|(0x7f);
  18583. a &= (0x7f<<14)|(0x7f);
  18584. a = a<<7;
  18585. *v = a | b;
  18586. return 4;
  18587. }
  18588. p++;
  18589. a = a<<14;
  18590. a |= *p;
  18591. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  18592. if (!(a&0x80))
  18593. {
  18594. a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
  18595. b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
  18596. b = b<<7;
  18597. *v = a | b;
  18598. return 5;
  18599. }
  18600. /* We can only reach this point when reading a corrupt database
  18601. ** file. In that case we are not in any hurry. Use the (relatively
  18602. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  18603. ** value. */
  18604. {
  18605. u64 v64;
  18606. u8 n;
  18607. p -= 4;
  18608. n = sqlite3GetVarint(p, &v64);
  18609. assert( n>5 && n<=9 );
  18610. *v = (u32)v64;
  18611. return n;
  18612. }
  18613. }
  18614. /*
  18615. ** Return the number of bytes that will be needed to store the given
  18616. ** 64-bit integer.
  18617. */
  18618. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  18619. int i = 0;
  18620. do{
  18621. i++;
  18622. v >>= 7;
  18623. }while( v!=0 && i<9 );
  18624. return i;
  18625. }
  18626. /*
  18627. ** Read or write a four-byte big-endian integer value.
  18628. */
  18629. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  18630. return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  18631. }
  18632. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  18633. p[0] = (u8)(v>>24);
  18634. p[1] = (u8)(v>>16);
  18635. p[2] = (u8)(v>>8);
  18636. p[3] = (u8)v;
  18637. }
  18638. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  18639. /*
  18640. ** Translate a single byte of Hex into an integer.
  18641. ** This routinen only works if h really is a valid hexadecimal
  18642. ** character: 0..9a..fA..F
  18643. */
  18644. static u8 hexToInt(int h){
  18645. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  18646. #ifdef SQLITE_ASCII
  18647. h += 9*(1&(h>>6));
  18648. #endif
  18649. #ifdef SQLITE_EBCDIC
  18650. h += 9*(1&~(h>>4));
  18651. #endif
  18652. return (u8)(h & 0xf);
  18653. }
  18654. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  18655. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  18656. /*
  18657. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  18658. ** value. Return a pointer to its binary value. Space to hold the
  18659. ** binary value has been obtained from malloc and must be freed by
  18660. ** the calling routine.
  18661. */
  18662. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  18663. char *zBlob;
  18664. int i;
  18665. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  18666. n--;
  18667. if( zBlob ){
  18668. for(i=0; i<n; i+=2){
  18669. zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
  18670. }
  18671. zBlob[i/2] = 0;
  18672. }
  18673. return zBlob;
  18674. }
  18675. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  18676. /*
  18677. ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
  18678. ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
  18679. ** when this routine is called.
  18680. **
  18681. ** This routine is called when entering an SQLite API. The SQLITE_MAGIC_OPEN
  18682. ** value indicates that the database connection passed into the API is
  18683. ** open and is not being used by another thread. By changing the value
  18684. ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
  18685. ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
  18686. ** when the API exits.
  18687. **
  18688. ** This routine is a attempt to detect if two threads use the
  18689. ** same sqlite* pointer at the same time. There is a race
  18690. ** condition so it is possible that the error is not detected.
  18691. ** But usually the problem will be seen. The result will be an
  18692. ** error which can be used to debug the application that is
  18693. ** using SQLite incorrectly.
  18694. **
  18695. ** Ticket #202: If db->magic is not a valid open value, take care not
  18696. ** to modify the db structure at all. It could be that db is a stale
  18697. ** pointer. In other words, it could be that there has been a prior
  18698. ** call to sqlite3_close(db) and db has been deallocated. And we do
  18699. ** not want to write into deallocated memory.
  18700. */
  18701. #ifdef SQLITE_DEBUG
  18702. SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
  18703. if( db->magic==SQLITE_MAGIC_OPEN ){
  18704. db->magic = SQLITE_MAGIC_BUSY;
  18705. assert( sqlite3_mutex_held(db->mutex) );
  18706. return 0;
  18707. }else if( db->magic==SQLITE_MAGIC_BUSY ){
  18708. db->magic = SQLITE_MAGIC_ERROR;
  18709. db->u1.isInterrupted = 1;
  18710. }
  18711. return 1;
  18712. }
  18713. #endif
  18714. /*
  18715. ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
  18716. ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
  18717. ** when this routine is called.
  18718. */
  18719. #ifdef SQLITE_DEBUG
  18720. SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
  18721. if( db->magic==SQLITE_MAGIC_BUSY ){
  18722. db->magic = SQLITE_MAGIC_OPEN;
  18723. assert( sqlite3_mutex_held(db->mutex) );
  18724. return 0;
  18725. }else{
  18726. db->magic = SQLITE_MAGIC_ERROR;
  18727. db->u1.isInterrupted = 1;
  18728. return 1;
  18729. }
  18730. }
  18731. #endif
  18732. /*
  18733. ** Check to make sure we have a valid db pointer. This test is not
  18734. ** foolproof but it does provide some measure of protection against
  18735. ** misuse of the interface such as passing in db pointers that are
  18736. ** NULL or which have been previously closed. If this routine returns
  18737. ** 1 it means that the db pointer is valid and 0 if it should not be
  18738. ** dereferenced for any reason. The calling function should invoke
  18739. ** SQLITE_MISUSE immediately.
  18740. **
  18741. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  18742. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  18743. ** open properly and is not fit for general use but which can be
  18744. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  18745. */
  18746. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  18747. u32 magic;
  18748. if( db==0 ) return 0;
  18749. magic = db->magic;
  18750. if( magic!=SQLITE_MAGIC_OPEN &&
  18751. magic!=SQLITE_MAGIC_BUSY ) return 0;
  18752. return 1;
  18753. }
  18754. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  18755. u32 magic;
  18756. if( db==0 ) return 0;
  18757. magic = db->magic;
  18758. if( magic!=SQLITE_MAGIC_SICK &&
  18759. magic!=SQLITE_MAGIC_OPEN &&
  18760. magic!=SQLITE_MAGIC_BUSY ) return 0;
  18761. return 1;
  18762. }
  18763. /************** End of util.c ************************************************/
  18764. /************** Begin file hash.c ********************************************/
  18765. /*
  18766. ** 2001 September 22
  18767. **
  18768. ** The author disclaims copyright to this source code. In place of
  18769. ** a legal notice, here is a blessing:
  18770. **
  18771. ** May you do good and not evil.
  18772. ** May you find forgiveness for yourself and forgive others.
  18773. ** May you share freely, never taking more than you give.
  18774. **
  18775. *************************************************************************
  18776. ** This is the implementation of generic hash-tables
  18777. ** used in SQLite.
  18778. **
  18779. ** $Id: hash.c,v 1.33 2009/01/09 01:12:28 drh Exp $
  18780. */
  18781. /* Turn bulk memory into a hash table object by initializing the
  18782. ** fields of the Hash structure.
  18783. **
  18784. ** "pNew" is a pointer to the hash table that is to be initialized.
  18785. ** "copyKey" is true if the hash table should make its own private
  18786. ** copy of keys and false if it should just use the supplied pointer.
  18787. */
  18788. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int copyKey){
  18789. assert( pNew!=0 );
  18790. pNew->copyKey = copyKey!=0;
  18791. pNew->first = 0;
  18792. pNew->count = 0;
  18793. pNew->htsize = 0;
  18794. pNew->ht = 0;
  18795. }
  18796. /* Remove all entries from a hash table. Reclaim all memory.
  18797. ** Call this routine to delete a hash table or to reset a hash table
  18798. ** to the empty state.
  18799. */
  18800. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  18801. HashElem *elem; /* For looping over all elements of the table */
  18802. assert( pH!=0 );
  18803. elem = pH->first;
  18804. pH->first = 0;
  18805. sqlite3_free(pH->ht);
  18806. pH->ht = 0;
  18807. pH->htsize = 0;
  18808. while( elem ){
  18809. HashElem *next_elem = elem->next;
  18810. if( pH->copyKey ){
  18811. sqlite3_free(elem->pKey);
  18812. }
  18813. sqlite3_free(elem);
  18814. elem = next_elem;
  18815. }
  18816. pH->count = 0;
  18817. }
  18818. /*
  18819. ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
  18820. */
  18821. static int strHash(const void *pKey, int nKey){
  18822. const char *z = (const char *)pKey;
  18823. int h = 0;
  18824. if( nKey<=0 ) nKey = sqlite3Strlen30(z);
  18825. while( nKey > 0 ){
  18826. h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
  18827. nKey--;
  18828. }
  18829. return h & 0x7fffffff;
  18830. }
  18831. static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  18832. if( n1!=n2 ) return 1;
  18833. return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
  18834. }
  18835. /* Link an element into the hash table
  18836. */
  18837. static void insertElement(
  18838. Hash *pH, /* The complete hash table */
  18839. struct _ht *pEntry, /* The entry into which pNew is inserted */
  18840. HashElem *pNew /* The element to be inserted */
  18841. ){
  18842. HashElem *pHead; /* First element already in pEntry */
  18843. pHead = pEntry->chain;
  18844. if( pHead ){
  18845. pNew->next = pHead;
  18846. pNew->prev = pHead->prev;
  18847. if( pHead->prev ){ pHead->prev->next = pNew; }
  18848. else { pH->first = pNew; }
  18849. pHead->prev = pNew;
  18850. }else{
  18851. pNew->next = pH->first;
  18852. if( pH->first ){ pH->first->prev = pNew; }
  18853. pNew->prev = 0;
  18854. pH->first = pNew;
  18855. }
  18856. pEntry->count++;
  18857. pEntry->chain = pNew;
  18858. }
  18859. /* Resize the hash table so that it cantains "new_size" buckets.
  18860. ** "new_size" must be a power of 2. The hash table might fail
  18861. ** to resize if sqlite3_malloc() fails.
  18862. */
  18863. static void rehash(Hash *pH, int new_size){
  18864. struct _ht *new_ht; /* The new hash table */
  18865. HashElem *elem, *next_elem; /* For looping over existing elements */
  18866. #ifdef SQLITE_MALLOC_SOFT_LIMIT
  18867. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  18868. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  18869. }
  18870. if( new_size==pH->htsize ) return;
  18871. #endif
  18872. /* There is a call to sqlite3_malloc() inside rehash(). If there is
  18873. ** already an allocation at pH->ht, then if this malloc() fails it
  18874. ** is benign (since failing to resize a hash table is a performance
  18875. ** hit only, not a fatal error).
  18876. */
  18877. if( pH->htsize>0 ) sqlite3BeginBenignMalloc();
  18878. new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
  18879. if( pH->htsize>0 ) sqlite3EndBenignMalloc();
  18880. if( new_ht==0 ) return;
  18881. sqlite3_free(pH->ht);
  18882. pH->ht = new_ht;
  18883. pH->htsize = new_size;
  18884. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  18885. int h = strHash(elem->pKey, elem->nKey) & (new_size-1);
  18886. next_elem = elem->next;
  18887. insertElement(pH, &new_ht[h], elem);
  18888. }
  18889. }
  18890. /* This function (for internal use only) locates an element in an
  18891. ** hash table that matches the given key. The hash for this key has
  18892. ** already been computed and is passed as the 4th parameter.
  18893. */
  18894. static HashElem *findElementGivenHash(
  18895. const Hash *pH, /* The pH to be searched */
  18896. const void *pKey, /* The key we are searching for */
  18897. int nKey,
  18898. int h /* The hash for this key. */
  18899. ){
  18900. HashElem *elem; /* Used to loop thru the element list */
  18901. int count; /* Number of elements left to test */
  18902. if( pH->ht ){
  18903. struct _ht *pEntry = &pH->ht[h];
  18904. elem = pEntry->chain;
  18905. count = pEntry->count;
  18906. while( count-- && elem ){
  18907. if( strCompare(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  18908. return elem;
  18909. }
  18910. elem = elem->next;
  18911. }
  18912. }
  18913. return 0;
  18914. }
  18915. /* Remove a single entry from the hash table given a pointer to that
  18916. ** element and a hash on the element's key.
  18917. */
  18918. static void removeElementGivenHash(
  18919. Hash *pH, /* The pH containing "elem" */
  18920. HashElem* elem, /* The element to be removed from the pH */
  18921. int h /* Hash value for the element */
  18922. ){
  18923. struct _ht *pEntry;
  18924. if( elem->prev ){
  18925. elem->prev->next = elem->next;
  18926. }else{
  18927. pH->first = elem->next;
  18928. }
  18929. if( elem->next ){
  18930. elem->next->prev = elem->prev;
  18931. }
  18932. pEntry = &pH->ht[h];
  18933. if( pEntry->chain==elem ){
  18934. pEntry->chain = elem->next;
  18935. }
  18936. pEntry->count--;
  18937. if( pEntry->count<=0 ){
  18938. pEntry->chain = 0;
  18939. }
  18940. if( pH->copyKey ){
  18941. sqlite3_free(elem->pKey);
  18942. }
  18943. sqlite3_free( elem );
  18944. pH->count--;
  18945. if( pH->count<=0 ){
  18946. assert( pH->first==0 );
  18947. assert( pH->count==0 );
  18948. sqlite3HashClear(pH);
  18949. }
  18950. }
  18951. /* Attempt to locate an element of the hash table pH with a key
  18952. ** that matches pKey,nKey. Return a pointer to the corresponding
  18953. ** HashElem structure for this element if it is found, or NULL
  18954. ** otherwise.
  18955. */
  18956. SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
  18957. int h; /* A hash on key */
  18958. HashElem *elem; /* The element that matches key */
  18959. if( pH==0 || pH->ht==0 ) return 0;
  18960. h = strHash(pKey,nKey);
  18961. elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
  18962. return elem;
  18963. }
  18964. /* Attempt to locate an element of the hash table pH with a key
  18965. ** that matches pKey,nKey. Return the data for this element if it is
  18966. ** found, or NULL if there is no match.
  18967. */
  18968. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
  18969. HashElem *elem; /* The element that matches key */
  18970. elem = sqlite3HashFindElem(pH, pKey, nKey);
  18971. return elem ? elem->data : 0;
  18972. }
  18973. /* Insert an element into the hash table pH. The key is pKey,nKey
  18974. ** and the data is "data".
  18975. **
  18976. ** If no element exists with a matching key, then a new
  18977. ** element is created. A copy of the key is made if the copyKey
  18978. ** flag is set. NULL is returned.
  18979. **
  18980. ** If another element already exists with the same key, then the
  18981. ** new data replaces the old data and the old data is returned.
  18982. ** The key is not copied in this instance. If a malloc fails, then
  18983. ** the new data is returned and the hash table is unchanged.
  18984. **
  18985. ** If the "data" parameter to this function is NULL, then the
  18986. ** element corresponding to "key" is removed from the hash table.
  18987. */
  18988. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
  18989. int hraw; /* Raw hash value of the key */
  18990. int h; /* the hash of the key modulo hash table size */
  18991. HashElem *elem; /* Used to loop thru the element list */
  18992. HashElem *new_elem; /* New element added to the pH */
  18993. assert( pH!=0 );
  18994. hraw = strHash(pKey, nKey);
  18995. if( pH->htsize ){
  18996. h = hraw % pH->htsize;
  18997. elem = findElementGivenHash(pH,pKey,nKey,h);
  18998. if( elem ){
  18999. void *old_data = elem->data;
  19000. if( data==0 ){
  19001. removeElementGivenHash(pH,elem,h);
  19002. }else{
  19003. elem->data = data;
  19004. if( !pH->copyKey ){
  19005. elem->pKey = (void *)pKey;
  19006. }
  19007. assert(nKey==elem->nKey);
  19008. }
  19009. return old_data;
  19010. }
  19011. }
  19012. if( data==0 ) return 0;
  19013. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  19014. if( new_elem==0 ) return data;
  19015. if( pH->copyKey && pKey!=0 ){
  19016. new_elem->pKey = sqlite3Malloc( nKey );
  19017. if( new_elem->pKey==0 ){
  19018. sqlite3_free(new_elem);
  19019. return data;
  19020. }
  19021. memcpy((void*)new_elem->pKey, pKey, nKey);
  19022. }else{
  19023. new_elem->pKey = (void*)pKey;
  19024. }
  19025. new_elem->nKey = nKey;
  19026. pH->count++;
  19027. if( pH->htsize==0 ){
  19028. rehash(pH, 128/sizeof(pH->ht[0]));
  19029. if( pH->htsize==0 ){
  19030. pH->count = 0;
  19031. if( pH->copyKey ){
  19032. sqlite3_free(new_elem->pKey);
  19033. }
  19034. sqlite3_free(new_elem);
  19035. return data;
  19036. }
  19037. }
  19038. if( pH->count > pH->htsize ){
  19039. rehash(pH,pH->htsize*2);
  19040. }
  19041. assert( pH->htsize>0 );
  19042. h = hraw % pH->htsize;
  19043. insertElement(pH, &pH->ht[h], new_elem);
  19044. new_elem->data = data;
  19045. return 0;
  19046. }
  19047. /************** End of hash.c ************************************************/
  19048. /************** Begin file opcodes.c *****************************************/
  19049. /* Automatically generated. Do not edit */
  19050. /* See the mkopcodec.awk script for details. */
  19051. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  19052. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  19053. static const char *const azName[] = { "?",
  19054. /* 1 */ "VNext",
  19055. /* 2 */ "Affinity",
  19056. /* 3 */ "Column",
  19057. /* 4 */ "SetCookie",
  19058. /* 5 */ "Seek",
  19059. /* 6 */ "Sequence",
  19060. /* 7 */ "Savepoint",
  19061. /* 8 */ "RowKey",
  19062. /* 9 */ "SCopy",
  19063. /* 10 */ "OpenWrite",
  19064. /* 11 */ "If",
  19065. /* 12 */ "VRowid",
  19066. /* 13 */ "CollSeq",
  19067. /* 14 */ "OpenRead",
  19068. /* 15 */ "Expire",
  19069. /* 16 */ "AutoCommit",
  19070. /* 17 */ "Pagecount",
  19071. /* 18 */ "IntegrityCk",
  19072. /* 19 */ "Not",
  19073. /* 20 */ "Sort",
  19074. /* 21 */ "Copy",
  19075. /* 22 */ "Trace",
  19076. /* 23 */ "Function",
  19077. /* 24 */ "IfNeg",
  19078. /* 25 */ "Noop",
  19079. /* 26 */ "Return",
  19080. /* 27 */ "NewRowid",
  19081. /* 28 */ "Variable",
  19082. /* 29 */ "String",
  19083. /* 30 */ "RealAffinity",
  19084. /* 31 */ "VRename",
  19085. /* 32 */ "ParseSchema",
  19086. /* 33 */ "VOpen",
  19087. /* 34 */ "Close",
  19088. /* 35 */ "CreateIndex",
  19089. /* 36 */ "IsUnique",
  19090. /* 37 */ "NotFound",
  19091. /* 38 */ "Int64",
  19092. /* 39 */ "MustBeInt",
  19093. /* 40 */ "Halt",
  19094. /* 41 */ "Rowid",
  19095. /* 42 */ "IdxLT",
  19096. /* 43 */ "AddImm",
  19097. /* 44 */ "Statement",
  19098. /* 45 */ "RowData",
  19099. /* 46 */ "MemMax",
  19100. /* 47 */ "NotExists",
  19101. /* 48 */ "Gosub",
  19102. /* 49 */ "Integer",
  19103. /* 50 */ "Prev",
  19104. /* 51 */ "RowSetRead",
  19105. /* 52 */ "RowSetAdd",
  19106. /* 53 */ "VColumn",
  19107. /* 54 */ "CreateTable",
  19108. /* 55 */ "Last",
  19109. /* 56 */ "SeekLe",
  19110. /* 57 */ "IncrVacuum",
  19111. /* 58 */ "IdxRowid",
  19112. /* 59 */ "ResetCount",
  19113. /* 60 */ "ContextPush",
  19114. /* 61 */ "Yield",
  19115. /* 62 */ "DropTrigger",
  19116. /* 63 */ "Or",
  19117. /* 64 */ "And",
  19118. /* 65 */ "DropIndex",
  19119. /* 66 */ "IdxGE",
  19120. /* 67 */ "IdxDelete",
  19121. /* 68 */ "IsNull",
  19122. /* 69 */ "NotNull",
  19123. /* 70 */ "Ne",
  19124. /* 71 */ "Eq",
  19125. /* 72 */ "Gt",
  19126. /* 73 */ "Le",
  19127. /* 74 */ "Lt",
  19128. /* 75 */ "Ge",
  19129. /* 76 */ "Vacuum",
  19130. /* 77 */ "BitAnd",
  19131. /* 78 */ "BitOr",
  19132. /* 79 */ "ShiftLeft",
  19133. /* 80 */ "ShiftRight",
  19134. /* 81 */ "Add",
  19135. /* 82 */ "Subtract",
  19136. /* 83 */ "Multiply",
  19137. /* 84 */ "Divide",
  19138. /* 85 */ "Remainder",
  19139. /* 86 */ "Concat",
  19140. /* 87 */ "IfNot",
  19141. /* 88 */ "DropTable",
  19142. /* 89 */ "SeekLt",
  19143. /* 90 */ "BitNot",
  19144. /* 91 */ "String8",
  19145. /* 92 */ "MakeRecord",
  19146. /* 93 */ "ResultRow",
  19147. /* 94 */ "Delete",
  19148. /* 95 */ "AggFinal",
  19149. /* 96 */ "Compare",
  19150. /* 97 */ "Goto",
  19151. /* 98 */ "TableLock",
  19152. /* 99 */ "Clear",
  19153. /* 100 */ "VerifyCookie",
  19154. /* 101 */ "AggStep",
  19155. /* 102 */ "SetNumColumns",
  19156. /* 103 */ "Transaction",
  19157. /* 104 */ "VFilter",
  19158. /* 105 */ "VDestroy",
  19159. /* 106 */ "ContextPop",
  19160. /* 107 */ "Next",
  19161. /* 108 */ "IdxInsert",
  19162. /* 109 */ "SeekGe",
  19163. /* 110 */ "Insert",
  19164. /* 111 */ "Destroy",
  19165. /* 112 */ "ReadCookie",
  19166. /* 113 */ "LoadAnalysis",
  19167. /* 114 */ "Explain",
  19168. /* 115 */ "OpenPseudo",
  19169. /* 116 */ "OpenEphemeral",
  19170. /* 117 */ "Null",
  19171. /* 118 */ "Move",
  19172. /* 119 */ "Blob",
  19173. /* 120 */ "Rewind",
  19174. /* 121 */ "SeekGt",
  19175. /* 122 */ "VBegin",
  19176. /* 123 */ "VUpdate",
  19177. /* 124 */ "IfZero",
  19178. /* 125 */ "VCreate",
  19179. /* 126 */ "Found",
  19180. /* 127 */ "IfPos",
  19181. /* 128 */ "NullRow",
  19182. /* 129 */ "Real",
  19183. /* 130 */ "Jump",
  19184. /* 131 */ "Permutation",
  19185. /* 132 */ "NotUsed_132",
  19186. /* 133 */ "NotUsed_133",
  19187. /* 134 */ "NotUsed_134",
  19188. /* 135 */ "NotUsed_135",
  19189. /* 136 */ "NotUsed_136",
  19190. /* 137 */ "NotUsed_137",
  19191. /* 138 */ "NotUsed_138",
  19192. /* 139 */ "NotUsed_139",
  19193. /* 140 */ "NotUsed_140",
  19194. /* 141 */ "ToText",
  19195. /* 142 */ "ToBlob",
  19196. /* 143 */ "ToNumeric",
  19197. /* 144 */ "ToInt",
  19198. /* 145 */ "ToReal",
  19199. };
  19200. return azName[i];
  19201. }
  19202. #endif
  19203. /************** End of opcodes.c *********************************************/
  19204. /************** Begin file os_os2.c ******************************************/
  19205. /*
  19206. ** 2006 Feb 14
  19207. **
  19208. ** The author disclaims copyright to this source code. In place of
  19209. ** a legal notice, here is a blessing:
  19210. **
  19211. ** May you do good and not evil.
  19212. ** May you find forgiveness for yourself and forgive others.
  19213. ** May you share freely, never taking more than you give.
  19214. **
  19215. ******************************************************************************
  19216. **
  19217. ** This file contains code that is specific to OS/2.
  19218. **
  19219. ** $Id: os_os2.c,v 1.63 2008/12/10 19:26:24 drh Exp $
  19220. */
  19221. #if SQLITE_OS_OS2
  19222. /*
  19223. ** A Note About Memory Allocation:
  19224. **
  19225. ** This driver uses malloc()/free() directly rather than going through
  19226. ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
  19227. ** are designed for use on embedded systems where memory is scarce and
  19228. ** malloc failures happen frequently. OS/2 does not typically run on
  19229. ** embedded systems, and when it does the developers normally have bigger
  19230. ** problems to worry about than running out of memory. So there is not
  19231. ** a compelling need to use the wrappers.
  19232. **
  19233. ** But there is a good reason to not use the wrappers. If we use the
  19234. ** wrappers then we will get simulated malloc() failures within this
  19235. ** driver. And that causes all kinds of problems for our tests. We
  19236. ** could enhance SQLite to deal with simulated malloc failures within
  19237. ** the OS driver, but the code to deal with those failure would not
  19238. ** be exercised on Linux (which does not need to malloc() in the driver)
  19239. ** and so we would have difficulty writing coverage tests for that
  19240. ** code. Better to leave the code out, we think.
  19241. **
  19242. ** The point of this discussion is as follows: When creating a new
  19243. ** OS layer for an embedded system, if you use this file as an example,
  19244. ** avoid the use of malloc()/free(). Those routines work ok on OS/2
  19245. ** desktops but not so well in embedded systems.
  19246. */
  19247. /*
  19248. ** Macros used to determine whether or not to use threads.
  19249. */
  19250. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
  19251. # define SQLITE_OS2_THREADS 1
  19252. #endif
  19253. /*
  19254. ** Include code that is common to all os_*.c files
  19255. */
  19256. /************** Include os_common.h in the middle of os_os2.c ****************/
  19257. /************** Begin file os_common.h ***************************************/
  19258. /*
  19259. ** 2004 May 22
  19260. **
  19261. ** The author disclaims copyright to this source code. In place of
  19262. ** a legal notice, here is a blessing:
  19263. **
  19264. ** May you do good and not evil.
  19265. ** May you find forgiveness for yourself and forgive others.
  19266. ** May you share freely, never taking more than you give.
  19267. **
  19268. ******************************************************************************
  19269. **
  19270. ** This file contains macros and a little bit of code that is common to
  19271. ** all of the platform-specific files (os_*.c) and is #included into those
  19272. ** files.
  19273. **
  19274. ** This file should be #included by the os_*.c files only. It is not a
  19275. ** general purpose header file.
  19276. **
  19277. ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
  19278. */
  19279. #ifndef _OS_COMMON_H_
  19280. #define _OS_COMMON_H_
  19281. /*
  19282. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  19283. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  19284. ** switch. The following code should catch this problem at compile-time.
  19285. */
  19286. #ifdef MEMORY_DEBUG
  19287. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  19288. #endif
  19289. /*
  19290. * When testing, this global variable stores the location of the
  19291. * pending-byte in the database file.
  19292. */
  19293. #ifdef SQLITE_TEST
  19294. SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
  19295. #endif
  19296. #ifdef SQLITE_DEBUG
  19297. SQLITE_PRIVATE int sqlite3OSTrace = 0;
  19298. #define OSTRACE1(X) if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
  19299. #define OSTRACE2(X,Y) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
  19300. #define OSTRACE3(X,Y,Z) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
  19301. #define OSTRACE4(X,Y,Z,A) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
  19302. #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
  19303. #define OSTRACE6(X,Y,Z,A,B,C) \
  19304. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
  19305. #define OSTRACE7(X,Y,Z,A,B,C,D) \
  19306. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
  19307. #else
  19308. #define OSTRACE1(X)
  19309. #define OSTRACE2(X,Y)
  19310. #define OSTRACE3(X,Y,Z)
  19311. #define OSTRACE4(X,Y,Z,A)
  19312. #define OSTRACE5(X,Y,Z,A,B)
  19313. #define OSTRACE6(X,Y,Z,A,B,C)
  19314. #define OSTRACE7(X,Y,Z,A,B,C,D)
  19315. #endif
  19316. /*
  19317. ** Macros for performance tracing. Normally turned off. Only works
  19318. ** on i486 hardware.
  19319. */
  19320. #ifdef SQLITE_PERFORMANCE_TRACE
  19321. /*
  19322. ** hwtime.h contains inline assembler code for implementing
  19323. ** high-performance timing routines.
  19324. */
  19325. /************** Include hwtime.h in the middle of os_common.h ****************/
  19326. /************** Begin file hwtime.h ******************************************/
  19327. /*
  19328. ** 2008 May 27
  19329. **
  19330. ** The author disclaims copyright to this source code. In place of
  19331. ** a legal notice, here is a blessing:
  19332. **
  19333. ** May you do good and not evil.
  19334. ** May you find forgiveness for yourself and forgive others.
  19335. ** May you share freely, never taking more than you give.
  19336. **
  19337. ******************************************************************************
  19338. **
  19339. ** This file contains inline asm code for retrieving "high-performance"
  19340. ** counters for x86 class CPUs.
  19341. **
  19342. ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
  19343. */
  19344. #ifndef _HWTIME_H_
  19345. #define _HWTIME_H_
  19346. /*
  19347. ** The following routine only works on pentium-class (or newer) processors.
  19348. ** It uses the RDTSC opcode to read the cycle count value out of the
  19349. ** processor and returns that value. This can be used for high-res
  19350. ** profiling.
  19351. */
  19352. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  19353. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  19354. #if defined(__GNUC__)
  19355. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19356. unsigned int lo, hi;
  19357. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  19358. return (sqlite_uint64)hi << 32 | lo;
  19359. }
  19360. #elif defined(_MSC_VER)
  19361. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  19362. __asm {
  19363. rdtsc
  19364. ret ; return value at EDX:EAX
  19365. }
  19366. }
  19367. #endif
  19368. #elif (defined(__GNUC__) && defined(__x86_64__))
  19369. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19370. unsigned long val;
  19371. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  19372. return val;
  19373. }
  19374. #elif (defined(__GNUC__) && defined(__ppc__))
  19375. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19376. unsigned long long retval;
  19377. unsigned long junk;
  19378. __asm__ __volatile__ ("\n\
  19379. 1: mftbu %1\n\
  19380. mftb %L0\n\
  19381. mftbu %0\n\
  19382. cmpw %0,%1\n\
  19383. bne 1b"
  19384. : "=r" (retval), "=r" (junk));
  19385. return retval;
  19386. }
  19387. #else
  19388. #error Need implementation of sqlite3Hwtime() for your platform.
  19389. /*
  19390. ** To compile without implementing sqlite3Hwtime() for your platform,
  19391. ** you can remove the above #error and use the following
  19392. ** stub function. You will lose timing support for many
  19393. ** of the debugging and testing utilities, but it should at
  19394. ** least compile and run.
  19395. */
  19396. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  19397. #endif
  19398. #endif /* !defined(_HWTIME_H_) */
  19399. /************** End of hwtime.h **********************************************/
  19400. /************** Continuing where we left off in os_common.h ******************/
  19401. static sqlite_uint64 g_start;
  19402. static sqlite_uint64 g_elapsed;
  19403. #define TIMER_START g_start=sqlite3Hwtime()
  19404. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  19405. #define TIMER_ELAPSED g_elapsed
  19406. #else
  19407. #define TIMER_START
  19408. #define TIMER_END
  19409. #define TIMER_ELAPSED ((sqlite_uint64)0)
  19410. #endif
  19411. /*
  19412. ** If we compile with the SQLITE_TEST macro set, then the following block
  19413. ** of code will give us the ability to simulate a disk I/O error. This
  19414. ** is used for testing the I/O recovery logic.
  19415. */
  19416. #ifdef SQLITE_TEST
  19417. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  19418. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  19419. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  19420. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  19421. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  19422. SQLITE_API int sqlite3_diskfull_pending = 0;
  19423. SQLITE_API int sqlite3_diskfull = 0;
  19424. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  19425. #define SimulateIOError(CODE) \
  19426. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  19427. || sqlite3_io_error_pending-- == 1 ) \
  19428. { local_ioerr(); CODE; }
  19429. static void local_ioerr(){
  19430. IOTRACE(("IOERR\n"));
  19431. sqlite3_io_error_hit++;
  19432. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  19433. }
  19434. #define SimulateDiskfullError(CODE) \
  19435. if( sqlite3_diskfull_pending ){ \
  19436. if( sqlite3_diskfull_pending == 1 ){ \
  19437. local_ioerr(); \
  19438. sqlite3_diskfull = 1; \
  19439. sqlite3_io_error_hit = 1; \
  19440. CODE; \
  19441. }else{ \
  19442. sqlite3_diskfull_pending--; \
  19443. } \
  19444. }
  19445. #else
  19446. #define SimulateIOErrorBenign(X)
  19447. #define SimulateIOError(A)
  19448. #define SimulateDiskfullError(A)
  19449. #endif
  19450. /*
  19451. ** When testing, keep a count of the number of open files.
  19452. */
  19453. #ifdef SQLITE_TEST
  19454. SQLITE_API int sqlite3_open_file_count = 0;
  19455. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  19456. #else
  19457. #define OpenCounter(X)
  19458. #endif
  19459. #endif /* !defined(_OS_COMMON_H_) */
  19460. /************** End of os_common.h *******************************************/
  19461. /************** Continuing where we left off in os_os2.c *********************/
  19462. /*
  19463. ** The os2File structure is subclass of sqlite3_file specific for the OS/2
  19464. ** protability layer.
  19465. */
  19466. typedef struct os2File os2File;
  19467. struct os2File {
  19468. const sqlite3_io_methods *pMethod; /* Always the first entry */
  19469. HFILE h; /* Handle for accessing the file */
  19470. char* pathToDel; /* Name of file to delete on close, NULL if not */
  19471. unsigned char locktype; /* Type of lock currently held on this file */
  19472. };
  19473. #define LOCK_TIMEOUT 10L /* the default locking timeout */
  19474. /*****************************************************************************
  19475. ** The next group of routines implement the I/O methods specified
  19476. ** by the sqlite3_io_methods object.
  19477. ******************************************************************************/
  19478. /*
  19479. ** Close a file.
  19480. */
  19481. static int os2Close( sqlite3_file *id ){
  19482. APIRET rc = NO_ERROR;
  19483. os2File *pFile;
  19484. if( id && (pFile = (os2File*)id) != 0 ){
  19485. OSTRACE2( "CLOSE %d\n", pFile->h );
  19486. rc = DosClose( pFile->h );
  19487. pFile->locktype = NO_LOCK;
  19488. if( pFile->pathToDel != NULL ){
  19489. rc = DosForceDelete( (PSZ)pFile->pathToDel );
  19490. free( pFile->pathToDel );
  19491. pFile->pathToDel = NULL;
  19492. }
  19493. id = 0;
  19494. OpenCounter( -1 );
  19495. }
  19496. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  19497. }
  19498. /*
  19499. ** Read data from a file into a buffer. Return SQLITE_OK if all
  19500. ** bytes were read successfully and SQLITE_IOERR if anything goes
  19501. ** wrong.
  19502. */
  19503. static int os2Read(
  19504. sqlite3_file *id, /* File to read from */
  19505. void *pBuf, /* Write content into this buffer */
  19506. int amt, /* Number of bytes to read */
  19507. sqlite3_int64 offset /* Begin reading at this offset */
  19508. ){
  19509. ULONG fileLocation = 0L;
  19510. ULONG got;
  19511. os2File *pFile = (os2File*)id;
  19512. assert( id!=0 );
  19513. SimulateIOError( return SQLITE_IOERR_READ );
  19514. OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
  19515. if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
  19516. return SQLITE_IOERR;
  19517. }
  19518. if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
  19519. return SQLITE_IOERR_READ;
  19520. }
  19521. if( got == (ULONG)amt )
  19522. return SQLITE_OK;
  19523. else {
  19524. /* Unread portions of the input buffer must be zero-filled */
  19525. memset(&((char*)pBuf)[got], 0, amt-got);
  19526. return SQLITE_IOERR_SHORT_READ;
  19527. }
  19528. }
  19529. /*
  19530. ** Write data from a buffer into a file. Return SQLITE_OK on success
  19531. ** or some other error code on failure.
  19532. */
  19533. static int os2Write(
  19534. sqlite3_file *id, /* File to write into */
  19535. const void *pBuf, /* The bytes to be written */
  19536. int amt, /* Number of bytes to write */
  19537. sqlite3_int64 offset /* Offset into the file to begin writing at */
  19538. ){
  19539. ULONG fileLocation = 0L;
  19540. APIRET rc = NO_ERROR;
  19541. ULONG wrote;
  19542. os2File *pFile = (os2File*)id;
  19543. assert( id!=0 );
  19544. SimulateIOError( return SQLITE_IOERR_WRITE );
  19545. SimulateDiskfullError( return SQLITE_FULL );
  19546. OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
  19547. if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
  19548. return SQLITE_IOERR;
  19549. }
  19550. assert( amt>0 );
  19551. while( amt > 0 &&
  19552. ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
  19553. wrote > 0
  19554. ){
  19555. amt -= wrote;
  19556. pBuf = &((char*)pBuf)[wrote];
  19557. }
  19558. return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
  19559. }
  19560. /*
  19561. ** Truncate an open file to a specified size
  19562. */
  19563. static int os2Truncate( sqlite3_file *id, i64 nByte ){
  19564. APIRET rc = NO_ERROR;
  19565. os2File *pFile = (os2File*)id;
  19566. OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
  19567. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  19568. rc = DosSetFileSize( pFile->h, nByte );
  19569. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
  19570. }
  19571. #ifdef SQLITE_TEST
  19572. /*
  19573. ** Count the number of fullsyncs and normal syncs. This is used to test
  19574. ** that syncs and fullsyncs are occuring at the right times.
  19575. */
  19576. SQLITE_API int sqlite3_sync_count = 0;
  19577. SQLITE_API int sqlite3_fullsync_count = 0;
  19578. #endif
  19579. /*
  19580. ** Make sure all writes to a particular file are committed to disk.
  19581. */
  19582. static int os2Sync( sqlite3_file *id, int flags ){
  19583. os2File *pFile = (os2File*)id;
  19584. OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
  19585. #ifdef SQLITE_TEST
  19586. if( flags & SQLITE_SYNC_FULL){
  19587. sqlite3_fullsync_count++;
  19588. }
  19589. sqlite3_sync_count++;
  19590. #endif
  19591. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  19592. ** no-op
  19593. */
  19594. #ifdef SQLITE_NO_SYNC
  19595. UNUSED_PARAMETER(pFile);
  19596. return SQLITE_OK;
  19597. #else
  19598. return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  19599. #endif
  19600. }
  19601. /*
  19602. ** Determine the current size of a file in bytes
  19603. */
  19604. static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
  19605. APIRET rc = NO_ERROR;
  19606. FILESTATUS3 fsts3FileInfo;
  19607. memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
  19608. assert( id!=0 );
  19609. SimulateIOError( return SQLITE_IOERR_FSTAT );
  19610. rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
  19611. if( rc == NO_ERROR ){
  19612. *pSize = fsts3FileInfo.cbFile;
  19613. return SQLITE_OK;
  19614. }else{
  19615. return SQLITE_IOERR_FSTAT;
  19616. }
  19617. }
  19618. /*
  19619. ** Acquire a reader lock.
  19620. */
  19621. static int getReadLock( os2File *pFile ){
  19622. FILELOCK LockArea,
  19623. UnlockArea;
  19624. APIRET res;
  19625. memset(&LockArea, 0, sizeof(LockArea));
  19626. memset(&UnlockArea, 0, sizeof(UnlockArea));
  19627. LockArea.lOffset = SHARED_FIRST;
  19628. LockArea.lRange = SHARED_SIZE;
  19629. UnlockArea.lOffset = 0L;
  19630. UnlockArea.lRange = 0L;
  19631. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
  19632. OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
  19633. return res;
  19634. }
  19635. /*
  19636. ** Undo a readlock
  19637. */
  19638. static int unlockReadLock( os2File *id ){
  19639. FILELOCK LockArea,
  19640. UnlockArea;
  19641. APIRET res;
  19642. memset(&LockArea, 0, sizeof(LockArea));
  19643. memset(&UnlockArea, 0, sizeof(UnlockArea));
  19644. LockArea.lOffset = 0L;
  19645. LockArea.lRange = 0L;
  19646. UnlockArea.lOffset = SHARED_FIRST;
  19647. UnlockArea.lRange = SHARED_SIZE;
  19648. res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
  19649. OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
  19650. return res;
  19651. }
  19652. /*
  19653. ** Lock the file with the lock specified by parameter locktype - one
  19654. ** of the following:
  19655. **
  19656. ** (1) SHARED_LOCK
  19657. ** (2) RESERVED_LOCK
  19658. ** (3) PENDING_LOCK
  19659. ** (4) EXCLUSIVE_LOCK
  19660. **
  19661. ** Sometimes when requesting one lock state, additional lock states
  19662. ** are inserted in between. The locking might fail on one of the later
  19663. ** transitions leaving the lock state different from what it started but
  19664. ** still short of its goal. The following chart shows the allowed
  19665. ** transitions and the inserted intermediate states:
  19666. **
  19667. ** UNLOCKED -> SHARED
  19668. ** SHARED -> RESERVED
  19669. ** SHARED -> (PENDING) -> EXCLUSIVE
  19670. ** RESERVED -> (PENDING) -> EXCLUSIVE
  19671. ** PENDING -> EXCLUSIVE
  19672. **
  19673. ** This routine will only increase a lock. The os2Unlock() routine
  19674. ** erases all locks at once and returns us immediately to locking level 0.
  19675. ** It is not possible to lower the locking level one step at a time. You
  19676. ** must go straight to locking level 0.
  19677. */
  19678. static int os2Lock( sqlite3_file *id, int locktype ){
  19679. int rc = SQLITE_OK; /* Return code from subroutines */
  19680. APIRET res = NO_ERROR; /* Result of an OS/2 lock call */
  19681. int newLocktype; /* Set pFile->locktype to this value before exiting */
  19682. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  19683. FILELOCK LockArea,
  19684. UnlockArea;
  19685. os2File *pFile = (os2File*)id;
  19686. memset(&LockArea, 0, sizeof(LockArea));
  19687. memset(&UnlockArea, 0, sizeof(UnlockArea));
  19688. assert( pFile!=0 );
  19689. OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
  19690. /* If there is already a lock of this type or more restrictive on the
  19691. ** os2File, do nothing. Don't use the end_lock: exit path, as
  19692. ** sqlite3_mutex_enter() hasn't been called yet.
  19693. */
  19694. if( pFile->locktype>=locktype ){
  19695. OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
  19696. return SQLITE_OK;
  19697. }
  19698. /* Make sure the locking sequence is correct
  19699. */
  19700. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  19701. assert( locktype!=PENDING_LOCK );
  19702. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  19703. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  19704. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  19705. ** the PENDING_LOCK byte is temporary.
  19706. */
  19707. newLocktype = pFile->locktype;
  19708. if( pFile->locktype==NO_LOCK
  19709. || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
  19710. ){
  19711. LockArea.lOffset = PENDING_BYTE;
  19712. LockArea.lRange = 1L;
  19713. UnlockArea.lOffset = 0L;
  19714. UnlockArea.lRange = 0L;
  19715. /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
  19716. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
  19717. if( res == NO_ERROR ){
  19718. gotPendingLock = 1;
  19719. OSTRACE3( "LOCK %d pending lock boolean set. res=%d\n", pFile->h, res );
  19720. }
  19721. }
  19722. /* Acquire a shared lock
  19723. */
  19724. if( locktype==SHARED_LOCK && res == NO_ERROR ){
  19725. assert( pFile->locktype==NO_LOCK );
  19726. res = getReadLock(pFile);
  19727. if( res == NO_ERROR ){
  19728. newLocktype = SHARED_LOCK;
  19729. }
  19730. OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
  19731. }
  19732. /* Acquire a RESERVED lock
  19733. */
  19734. if( locktype==RESERVED_LOCK && res == NO_ERROR ){
  19735. assert( pFile->locktype==SHARED_LOCK );
  19736. LockArea.lOffset = RESERVED_BYTE;
  19737. LockArea.lRange = 1L;
  19738. UnlockArea.lOffset = 0L;
  19739. UnlockArea.lRange = 0L;
  19740. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  19741. if( res == NO_ERROR ){
  19742. newLocktype = RESERVED_LOCK;
  19743. }
  19744. OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
  19745. }
  19746. /* Acquire a PENDING lock
  19747. */
  19748. if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
  19749. newLocktype = PENDING_LOCK;
  19750. gotPendingLock = 0;
  19751. OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
  19752. }
  19753. /* Acquire an EXCLUSIVE lock
  19754. */
  19755. if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
  19756. assert( pFile->locktype>=SHARED_LOCK );
  19757. res = unlockReadLock(pFile);
  19758. OSTRACE2( "unreadlock = %d\n", res );
  19759. LockArea.lOffset = SHARED_FIRST;
  19760. LockArea.lRange = SHARED_SIZE;
  19761. UnlockArea.lOffset = 0L;
  19762. UnlockArea.lRange = 0L;
  19763. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  19764. if( res == NO_ERROR ){
  19765. newLocktype = EXCLUSIVE_LOCK;
  19766. }else{
  19767. OSTRACE2( "OS/2 error-code = %d\n", res );
  19768. getReadLock(pFile);
  19769. }
  19770. OSTRACE3( "LOCK %d acquire exclusive lock. res=%d\n", pFile->h, res );
  19771. }
  19772. /* If we are holding a PENDING lock that ought to be released, then
  19773. ** release it now.
  19774. */
  19775. if( gotPendingLock && locktype==SHARED_LOCK ){
  19776. int r;
  19777. LockArea.lOffset = 0L;
  19778. LockArea.lRange = 0L;
  19779. UnlockArea.lOffset = PENDING_BYTE;
  19780. UnlockArea.lRange = 1L;
  19781. r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  19782. OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
  19783. }
  19784. /* Update the state of the lock has held in the file descriptor then
  19785. ** return the appropriate result code.
  19786. */
  19787. if( res == NO_ERROR ){
  19788. rc = SQLITE_OK;
  19789. }else{
  19790. OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
  19791. locktype, newLocktype );
  19792. rc = SQLITE_BUSY;
  19793. }
  19794. pFile->locktype = newLocktype;
  19795. OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
  19796. return rc;
  19797. }
  19798. /*
  19799. ** This routine checks if there is a RESERVED lock held on the specified
  19800. ** file by this or any other process. If such a lock is held, return
  19801. ** non-zero, otherwise zero.
  19802. */
  19803. static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
  19804. int r = 0;
  19805. os2File *pFile = (os2File*)id;
  19806. assert( pFile!=0 );
  19807. if( pFile->locktype>=RESERVED_LOCK ){
  19808. r = 1;
  19809. OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
  19810. }else{
  19811. FILELOCK LockArea,
  19812. UnlockArea;
  19813. APIRET rc = NO_ERROR;
  19814. memset(&LockArea, 0, sizeof(LockArea));
  19815. memset(&UnlockArea, 0, sizeof(UnlockArea));
  19816. LockArea.lOffset = RESERVED_BYTE;
  19817. LockArea.lRange = 1L;
  19818. UnlockArea.lOffset = 0L;
  19819. UnlockArea.lRange = 0L;
  19820. rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  19821. OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
  19822. if( rc == NO_ERROR ){
  19823. APIRET rcu = NO_ERROR; /* return code for unlocking */
  19824. LockArea.lOffset = 0L;
  19825. LockArea.lRange = 0L;
  19826. UnlockArea.lOffset = RESERVED_BYTE;
  19827. UnlockArea.lRange = 1L;
  19828. rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  19829. OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
  19830. }
  19831. r = !(rc == NO_ERROR);
  19832. OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
  19833. }
  19834. *pOut = r;
  19835. return SQLITE_OK;
  19836. }
  19837. /*
  19838. ** Lower the locking level on file descriptor id to locktype. locktype
  19839. ** must be either NO_LOCK or SHARED_LOCK.
  19840. **
  19841. ** If the locking level of the file descriptor is already at or below
  19842. ** the requested locking level, this routine is a no-op.
  19843. **
  19844. ** It is not possible for this routine to fail if the second argument
  19845. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  19846. ** might return SQLITE_IOERR;
  19847. */
  19848. static int os2Unlock( sqlite3_file *id, int locktype ){
  19849. int type;
  19850. os2File *pFile = (os2File*)id;
  19851. APIRET rc = SQLITE_OK;
  19852. APIRET res = NO_ERROR;
  19853. FILELOCK LockArea,
  19854. UnlockArea;
  19855. memset(&LockArea, 0, sizeof(LockArea));
  19856. memset(&UnlockArea, 0, sizeof(UnlockArea));
  19857. assert( pFile!=0 );
  19858. assert( locktype<=SHARED_LOCK );
  19859. OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
  19860. type = pFile->locktype;
  19861. if( type>=EXCLUSIVE_LOCK ){
  19862. LockArea.lOffset = 0L;
  19863. LockArea.lRange = 0L;
  19864. UnlockArea.lOffset = SHARED_FIRST;
  19865. UnlockArea.lRange = SHARED_SIZE;
  19866. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  19867. OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
  19868. if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
  19869. /* This should never happen. We should always be able to
  19870. ** reacquire the read lock */
  19871. OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
  19872. rc = SQLITE_IOERR_UNLOCK;
  19873. }
  19874. }
  19875. if( type>=RESERVED_LOCK ){
  19876. LockArea.lOffset = 0L;
  19877. LockArea.lRange = 0L;
  19878. UnlockArea.lOffset = RESERVED_BYTE;
  19879. UnlockArea.lRange = 1L;
  19880. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  19881. OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
  19882. }
  19883. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  19884. res = unlockReadLock(pFile);
  19885. OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
  19886. }
  19887. if( type>=PENDING_LOCK ){
  19888. LockArea.lOffset = 0L;
  19889. LockArea.lRange = 0L;
  19890. UnlockArea.lOffset = PENDING_BYTE;
  19891. UnlockArea.lRange = 1L;
  19892. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  19893. OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
  19894. }
  19895. pFile->locktype = locktype;
  19896. OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
  19897. return rc;
  19898. }
  19899. /*
  19900. ** Control and query of the open file handle.
  19901. */
  19902. static int os2FileControl(sqlite3_file *id, int op, void *pArg){
  19903. switch( op ){
  19904. case SQLITE_FCNTL_LOCKSTATE: {
  19905. *(int*)pArg = ((os2File*)id)->locktype;
  19906. OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
  19907. return SQLITE_OK;
  19908. }
  19909. }
  19910. return SQLITE_ERROR;
  19911. }
  19912. /*
  19913. ** Return the sector size in bytes of the underlying block device for
  19914. ** the specified file. This is almost always 512 bytes, but may be
  19915. ** larger for some devices.
  19916. **
  19917. ** SQLite code assumes this function cannot fail. It also assumes that
  19918. ** if two files are created in the same file-system directory (i.e.
  19919. ** a database and its journal file) that the sector size will be the
  19920. ** same for both.
  19921. */
  19922. static int os2SectorSize(sqlite3_file *id){
  19923. return SQLITE_DEFAULT_SECTOR_SIZE;
  19924. }
  19925. /*
  19926. ** Return a vector of device characteristics.
  19927. */
  19928. static int os2DeviceCharacteristics(sqlite3_file *id){
  19929. return 0;
  19930. }
  19931. /*
  19932. ** Character set conversion objects used by conversion routines.
  19933. */
  19934. static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
  19935. static UconvObject uclCp = NULL; /* convert between local codepage and UCS-2 */
  19936. /*
  19937. ** Helper function to initialize the conversion objects from and to UTF-8.
  19938. */
  19939. static void initUconvObjects( void ){
  19940. if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
  19941. ucUtf8 = NULL;
  19942. if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
  19943. uclCp = NULL;
  19944. }
  19945. /*
  19946. ** Helper function to free the conversion objects from and to UTF-8.
  19947. */
  19948. static void freeUconvObjects( void ){
  19949. if ( ucUtf8 )
  19950. UniFreeUconvObject( ucUtf8 );
  19951. if ( uclCp )
  19952. UniFreeUconvObject( uclCp );
  19953. ucUtf8 = NULL;
  19954. uclCp = NULL;
  19955. }
  19956. /*
  19957. ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
  19958. ** The two-step process: first convert the incoming UTF-8 string
  19959. ** into UCS-2 and then from UCS-2 to the current codepage.
  19960. ** The returned char pointer has to be freed.
  19961. */
  19962. static char *convertUtf8PathToCp( const char *in ){
  19963. UniChar tempPath[CCHMAXPATH];
  19964. char *out = (char *)calloc( CCHMAXPATH, 1 );
  19965. if( !out )
  19966. return NULL;
  19967. if( !ucUtf8 || !uclCp )
  19968. initUconvObjects();
  19969. /* determine string for the conversion of UTF-8 which is CP1208 */
  19970. if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
  19971. return out; /* if conversion fails, return the empty string */
  19972. /* conversion for current codepage which can be used for paths */
  19973. UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
  19974. return out;
  19975. }
  19976. /*
  19977. ** Helper function to convert filenames from local codepage to UTF-8.
  19978. ** The two-step process: first convert the incoming codepage-specific
  19979. ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
  19980. ** The returned char pointer has to be freed.
  19981. **
  19982. ** This function is non-static to be able to use this in shell.c and
  19983. ** similar applications that take command line arguments.
  19984. */
  19985. char *convertCpPathToUtf8( const char *in ){
  19986. UniChar tempPath[CCHMAXPATH];
  19987. char *out = (char *)calloc( CCHMAXPATH, 1 );
  19988. if( !out )
  19989. return NULL;
  19990. if( !ucUtf8 || !uclCp )
  19991. initUconvObjects();
  19992. /* conversion for current codepage which can be used for paths */
  19993. if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
  19994. return out; /* if conversion fails, return the empty string */
  19995. /* determine string for the conversion of UTF-8 which is CP1208 */
  19996. UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
  19997. return out;
  19998. }
  19999. /*
  20000. ** This vector defines all the methods that can operate on an
  20001. ** sqlite3_file for os2.
  20002. */
  20003. static const sqlite3_io_methods os2IoMethod = {
  20004. 1, /* iVersion */
  20005. os2Close,
  20006. os2Read,
  20007. os2Write,
  20008. os2Truncate,
  20009. os2Sync,
  20010. os2FileSize,
  20011. os2Lock,
  20012. os2Unlock,
  20013. os2CheckReservedLock,
  20014. os2FileControl,
  20015. os2SectorSize,
  20016. os2DeviceCharacteristics
  20017. };
  20018. /***************************************************************************
  20019. ** Here ends the I/O methods that form the sqlite3_io_methods object.
  20020. **
  20021. ** The next block of code implements the VFS methods.
  20022. ****************************************************************************/
  20023. /*
  20024. ** Create a temporary file name in zBuf. zBuf must be big enough to
  20025. ** hold at pVfs->mxPathname characters.
  20026. */
  20027. static int getTempname(int nBuf, char *zBuf ){
  20028. static const unsigned char zChars[] =
  20029. "abcdefghijklmnopqrstuvwxyz"
  20030. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  20031. "0123456789";
  20032. int i, j;
  20033. char zTempPathBuf[3];
  20034. PSZ zTempPath = (PSZ)&zTempPathBuf;
  20035. if( sqlite3_temp_directory ){
  20036. zTempPath = sqlite3_temp_directory;
  20037. }else{
  20038. if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
  20039. if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
  20040. if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
  20041. ULONG ulDriveNum = 0, ulDriveMap = 0;
  20042. DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
  20043. sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
  20044. }
  20045. }
  20046. }
  20047. }
  20048. /* Strip off a trailing slashes or backslashes, otherwise we would get *
  20049. * multiple (back)slashes which causes DosOpen() to fail. *
  20050. * Trailing spaces are not allowed, either. */
  20051. j = sqlite3Strlen30(zTempPath);
  20052. while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
  20053. || zTempPath[j-1] == ' ' ) ){
  20054. j--;
  20055. }
  20056. zTempPath[j] = '\0';
  20057. if( !sqlite3_temp_directory ){
  20058. char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
  20059. sqlite3_snprintf( nBuf-30, zBuf,
  20060. "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
  20061. free( zTempPathUTF );
  20062. }else{
  20063. sqlite3_snprintf( nBuf-30, zBuf,
  20064. "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
  20065. }
  20066. j = sqlite3Strlen30( zBuf );
  20067. sqlite3_randomness( 20, &zBuf[j] );
  20068. for( i = 0; i < 20; i++, j++ ){
  20069. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  20070. }
  20071. zBuf[j] = 0;
  20072. OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
  20073. return SQLITE_OK;
  20074. }
  20075. /*
  20076. ** Turn a relative pathname into a full pathname. Write the full
  20077. ** pathname into zFull[]. zFull[] will be at least pVfs->mxPathname
  20078. ** bytes in size.
  20079. */
  20080. static int os2FullPathname(
  20081. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  20082. const char *zRelative, /* Possibly relative input path */
  20083. int nFull, /* Size of output buffer in bytes */
  20084. char *zFull /* Output buffer */
  20085. ){
  20086. char *zRelativeCp = convertUtf8PathToCp( zRelative );
  20087. char zFullCp[CCHMAXPATH] = "\0";
  20088. char *zFullUTF;
  20089. APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
  20090. CCHMAXPATH );
  20091. free( zRelativeCp );
  20092. zFullUTF = convertCpPathToUtf8( zFullCp );
  20093. sqlite3_snprintf( nFull, zFull, zFullUTF );
  20094. free( zFullUTF );
  20095. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  20096. }
  20097. /*
  20098. ** Open a file.
  20099. */
  20100. static int os2Open(
  20101. sqlite3_vfs *pVfs, /* Not used */
  20102. const char *zName, /* Name of the file */
  20103. sqlite3_file *id, /* Write the SQLite file handle here */
  20104. int flags, /* Open mode flags */
  20105. int *pOutFlags /* Status return flags */
  20106. ){
  20107. HFILE h;
  20108. ULONG ulFileAttribute = FILE_NORMAL;
  20109. ULONG ulOpenFlags = 0;
  20110. ULONG ulOpenMode = 0;
  20111. os2File *pFile = (os2File*)id;
  20112. APIRET rc = NO_ERROR;
  20113. ULONG ulAction;
  20114. char *zNameCp;
  20115. char zTmpname[CCHMAXPATH+1]; /* Buffer to hold name of temp file */
  20116. /* If the second argument to this function is NULL, generate a
  20117. ** temporary file name to use
  20118. */
  20119. if( !zName ){
  20120. int rc = getTempname(CCHMAXPATH+1, zTmpname);
  20121. if( rc!=SQLITE_OK ){
  20122. return rc;
  20123. }
  20124. zName = zTmpname;
  20125. }
  20126. memset( pFile, 0, sizeof(*pFile) );
  20127. OSTRACE2( "OPEN want %d\n", flags );
  20128. if( flags & SQLITE_OPEN_READWRITE ){
  20129. ulOpenMode |= OPEN_ACCESS_READWRITE;
  20130. OSTRACE1( "OPEN read/write\n" );
  20131. }else{
  20132. ulOpenMode |= OPEN_ACCESS_READONLY;
  20133. OSTRACE1( "OPEN read only\n" );
  20134. }
  20135. if( flags & SQLITE_OPEN_CREATE ){
  20136. ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
  20137. OSTRACE1( "OPEN open new/create\n" );
  20138. }else{
  20139. ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
  20140. OSTRACE1( "OPEN open existing\n" );
  20141. }
  20142. if( flags & SQLITE_OPEN_MAIN_DB ){
  20143. ulOpenMode |= OPEN_SHARE_DENYNONE;
  20144. OSTRACE1( "OPEN share read/write\n" );
  20145. }else{
  20146. ulOpenMode |= OPEN_SHARE_DENYWRITE;
  20147. OSTRACE1( "OPEN share read only\n" );
  20148. }
  20149. if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  20150. char pathUtf8[CCHMAXPATH];
  20151. #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
  20152. ulFileAttribute = FILE_HIDDEN;
  20153. #endif
  20154. os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
  20155. pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
  20156. OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
  20157. }else{
  20158. pFile->pathToDel = NULL;
  20159. OSTRACE1( "OPEN normal file attribute\n" );
  20160. }
  20161. /* always open in random access mode for possibly better speed */
  20162. ulOpenMode |= OPEN_FLAGS_RANDOM;
  20163. ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
  20164. ulOpenMode |= OPEN_FLAGS_NOINHERIT;
  20165. zNameCp = convertUtf8PathToCp( zName );
  20166. rc = DosOpen( (PSZ)zNameCp,
  20167. &h,
  20168. &ulAction,
  20169. 0L,
  20170. ulFileAttribute,
  20171. ulOpenFlags,
  20172. ulOpenMode,
  20173. (PEAOP2)NULL );
  20174. free( zNameCp );
  20175. if( rc != NO_ERROR ){
  20176. OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
  20177. rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
  20178. if( pFile->pathToDel )
  20179. free( pFile->pathToDel );
  20180. pFile->pathToDel = NULL;
  20181. if( flags & SQLITE_OPEN_READWRITE ){
  20182. OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
  20183. return os2Open( pVfs, zName, id,
  20184. ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
  20185. pOutFlags );
  20186. }else{
  20187. return SQLITE_CANTOPEN;
  20188. }
  20189. }
  20190. if( pOutFlags ){
  20191. *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
  20192. }
  20193. pFile->pMethod = &os2IoMethod;
  20194. pFile->h = h;
  20195. OpenCounter(+1);
  20196. OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
  20197. return SQLITE_OK;
  20198. }
  20199. /*
  20200. ** Delete the named file.
  20201. */
  20202. static int os2Delete(
  20203. sqlite3_vfs *pVfs, /* Not used on os2 */
  20204. const char *zFilename, /* Name of file to delete */
  20205. int syncDir /* Not used on os2 */
  20206. ){
  20207. APIRET rc = NO_ERROR;
  20208. char *zFilenameCp = convertUtf8PathToCp( zFilename );
  20209. SimulateIOError( return SQLITE_IOERR_DELETE );
  20210. rc = DosDelete( (PSZ)zFilenameCp );
  20211. free( zFilenameCp );
  20212. OSTRACE2( "DELETE \"%s\"\n", zFilename );
  20213. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
  20214. }
  20215. /*
  20216. ** Check the existance and status of a file.
  20217. */
  20218. static int os2Access(
  20219. sqlite3_vfs *pVfs, /* Not used on os2 */
  20220. const char *zFilename, /* Name of file to check */
  20221. int flags, /* Type of test to make on this file */
  20222. int *pOut /* Write results here */
  20223. ){
  20224. FILESTATUS3 fsts3ConfigInfo;
  20225. APIRET rc = NO_ERROR;
  20226. char *zFilenameCp = convertUtf8PathToCp( zFilename );
  20227. memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
  20228. rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
  20229. &fsts3ConfigInfo, sizeof(FILESTATUS3) );
  20230. free( zFilenameCp );
  20231. OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
  20232. fsts3ConfigInfo.attrFile, flags, rc );
  20233. switch( flags ){
  20234. case SQLITE_ACCESS_READ:
  20235. case SQLITE_ACCESS_EXISTS:
  20236. rc = (rc == NO_ERROR);
  20237. OSTRACE3( "ACCESS %s access of read and exists rc=%d\n", zFilename, rc );
  20238. break;
  20239. case SQLITE_ACCESS_READWRITE:
  20240. rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
  20241. OSTRACE3( "ACCESS %s access of read/write rc=%d\n", zFilename, rc );
  20242. break;
  20243. default:
  20244. assert( !"Invalid flags argument" );
  20245. }
  20246. *pOut = rc;
  20247. return SQLITE_OK;
  20248. }
  20249. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  20250. /*
  20251. ** Interfaces for opening a shared library, finding entry points
  20252. ** within the shared library, and closing the shared library.
  20253. */
  20254. /*
  20255. ** Interfaces for opening a shared library, finding entry points
  20256. ** within the shared library, and closing the shared library.
  20257. */
  20258. static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  20259. UCHAR loadErr[256];
  20260. HMODULE hmod;
  20261. APIRET rc;
  20262. char *zFilenameCp = convertUtf8PathToCp(zFilename);
  20263. rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
  20264. free(zFilenameCp);
  20265. return rc != NO_ERROR ? 0 : (void*)hmod;
  20266. }
  20267. /*
  20268. ** A no-op since the error code is returned on the DosLoadModule call.
  20269. ** os2Dlopen returns zero if DosLoadModule is not successful.
  20270. */
  20271. static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  20272. /* no-op */
  20273. }
  20274. static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
  20275. PFN pfn;
  20276. APIRET rc;
  20277. rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
  20278. if( rc != NO_ERROR ){
  20279. /* if the symbol itself was not found, search again for the same
  20280. * symbol with an extra underscore, that might be needed depending
  20281. * on the calling convention */
  20282. char _zSymbol[256] = "_";
  20283. strncat(_zSymbol, zSymbol, 255);
  20284. rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
  20285. }
  20286. return rc != NO_ERROR ? 0 : (void*)pfn;
  20287. }
  20288. static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
  20289. DosFreeModule((HMODULE)pHandle);
  20290. }
  20291. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  20292. #define os2DlOpen 0
  20293. #define os2DlError 0
  20294. #define os2DlSym 0
  20295. #define os2DlClose 0
  20296. #endif
  20297. /*
  20298. ** Write up to nBuf bytes of randomness into zBuf.
  20299. */
  20300. static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
  20301. int n = 0;
  20302. #if defined(SQLITE_TEST)
  20303. n = nBuf;
  20304. memset(zBuf, 0, nBuf);
  20305. #else
  20306. int sizeofULong = sizeof(ULONG);
  20307. if( (int)sizeof(DATETIME) <= nBuf - n ){
  20308. DATETIME x;
  20309. DosGetDateTime(&x);
  20310. memcpy(&zBuf[n], &x, sizeof(x));
  20311. n += sizeof(x);
  20312. }
  20313. if( sizeofULong <= nBuf - n ){
  20314. PPIB ppib;
  20315. DosGetInfoBlocks(NULL, &ppib);
  20316. memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
  20317. n += sizeofULong;
  20318. }
  20319. if( sizeofULong <= nBuf - n ){
  20320. PTIB ptib;
  20321. DosGetInfoBlocks(&ptib, NULL);
  20322. memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
  20323. n += sizeofULong;
  20324. }
  20325. /* if we still haven't filled the buffer yet the following will */
  20326. /* grab everything once instead of making several calls for a single item */
  20327. if( sizeofULong <= nBuf - n ){
  20328. ULONG ulSysInfo[QSV_MAX];
  20329. DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
  20330. memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
  20331. n += sizeofULong;
  20332. if( sizeofULong <= nBuf - n ){
  20333. memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
  20334. n += sizeofULong;
  20335. }
  20336. if( sizeofULong <= nBuf - n ){
  20337. memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
  20338. n += sizeofULong;
  20339. }
  20340. if( sizeofULong <= nBuf - n ){
  20341. memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
  20342. n += sizeofULong;
  20343. }
  20344. if( sizeofULong <= nBuf - n ){
  20345. memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
  20346. n += sizeofULong;
  20347. }
  20348. }
  20349. #endif
  20350. return n;
  20351. }
  20352. /*
  20353. ** Sleep for a little while. Return the amount of time slept.
  20354. ** The argument is the number of microseconds we want to sleep.
  20355. ** The return value is the number of microseconds of sleep actually
  20356. ** requested from the underlying operating system, a number which
  20357. ** might be greater than or equal to the argument, but not less
  20358. ** than the argument.
  20359. */
  20360. static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
  20361. DosSleep( (microsec/1000) );
  20362. return microsec;
  20363. }
  20364. /*
  20365. ** The following variable, if set to a non-zero value, becomes the result
  20366. ** returned from sqlite3OsCurrentTime(). This is used for testing.
  20367. */
  20368. #ifdef SQLITE_TEST
  20369. SQLITE_API int sqlite3_current_time = 0;
  20370. #endif
  20371. /*
  20372. ** Find the current time (in Universal Coordinated Time). Write the
  20373. ** current time and date as a Julian Day number into *prNow and
  20374. ** return 0. Return 1 if the time and date cannot be found.
  20375. */
  20376. int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
  20377. double now;
  20378. SHORT minute; /* needs to be able to cope with negative timezone offset */
  20379. USHORT second, hour,
  20380. day, month, year;
  20381. DATETIME dt;
  20382. DosGetDateTime( &dt );
  20383. second = (USHORT)dt.seconds;
  20384. minute = (SHORT)dt.minutes + dt.timezone;
  20385. hour = (USHORT)dt.hours;
  20386. day = (USHORT)dt.day;
  20387. month = (USHORT)dt.month;
  20388. year = (USHORT)dt.year;
  20389. /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
  20390. http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
  20391. /* Calculate the Julian days */
  20392. now = day - 32076 +
  20393. 1461*(year + 4800 + (month - 14)/12)/4 +
  20394. 367*(month - 2 - (month - 14)/12*12)/12 -
  20395. 3*((year + 4900 + (month - 14)/12)/100)/4;
  20396. /* Add the fractional hours, mins and seconds */
  20397. now += (hour + 12.0)/24.0;
  20398. now += minute/1440.0;
  20399. now += second/86400.0;
  20400. *prNow = now;
  20401. #ifdef SQLITE_TEST
  20402. if( sqlite3_current_time ){
  20403. *prNow = sqlite3_current_time/86400.0 + 2440587.5;
  20404. }
  20405. #endif
  20406. return 0;
  20407. }
  20408. static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  20409. return 0;
  20410. }
  20411. /*
  20412. ** Initialize and deinitialize the operating system interface.
  20413. */
  20414. SQLITE_API int sqlite3_os_init(void){
  20415. static sqlite3_vfs os2Vfs = {
  20416. 1, /* iVersion */
  20417. sizeof(os2File), /* szOsFile */
  20418. CCHMAXPATH, /* mxPathname */
  20419. 0, /* pNext */
  20420. "os2", /* zName */
  20421. 0, /* pAppData */
  20422. os2Open, /* xOpen */
  20423. os2Delete, /* xDelete */
  20424. os2Access, /* xAccess */
  20425. os2FullPathname, /* xFullPathname */
  20426. os2DlOpen, /* xDlOpen */
  20427. os2DlError, /* xDlError */
  20428. os2DlSym, /* xDlSym */
  20429. os2DlClose, /* xDlClose */
  20430. os2Randomness, /* xRandomness */
  20431. os2Sleep, /* xSleep */
  20432. os2CurrentTime, /* xCurrentTime */
  20433. os2GetLastError /* xGetLastError */
  20434. };
  20435. sqlite3_vfs_register(&os2Vfs, 1);
  20436. initUconvObjects();
  20437. return SQLITE_OK;
  20438. }
  20439. SQLITE_API int sqlite3_os_end(void){
  20440. freeUconvObjects();
  20441. return SQLITE_OK;
  20442. }
  20443. #endif /* SQLITE_OS_OS2 */
  20444. /************** End of os_os2.c **********************************************/
  20445. /************** Begin file os_unix.c *****************************************/
  20446. /*
  20447. ** 2004 May 22
  20448. **
  20449. ** The author disclaims copyright to this source code. In place of
  20450. ** a legal notice, here is a blessing:
  20451. **
  20452. ** May you do good and not evil.
  20453. ** May you find forgiveness for yourself and forgive others.
  20454. ** May you share freely, never taking more than you give.
  20455. **
  20456. ******************************************************************************
  20457. **
  20458. ** This file contains the VFS implementation for unix-like operating systems
  20459. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  20460. **
  20461. ** There are actually several different VFS implementations in this file.
  20462. ** The differences are in the way that file locking is done. The default
  20463. ** implementation uses Posix Advisory Locks. Alternative implementations
  20464. ** use flock(), dot-files, various proprietary locking schemas, or simply
  20465. ** skip locking all together.
  20466. **
  20467. ** This source file is organized into divisions where the logic for various
  20468. ** subfunctions is contained within the appropriate division. PLEASE
  20469. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  20470. ** in the correct division and should be clearly labeled.
  20471. **
  20472. ** The layout of divisions is as follows:
  20473. **
  20474. ** * General-purpose declarations and utility functions.
  20475. ** * Unique file ID logic used by VxWorks.
  20476. ** * Various locking primitive implementations (all except proxy locking):
  20477. ** + for Posix Advisory Locks
  20478. ** + for no-op locks
  20479. ** + for dot-file locks
  20480. ** + for flock() locking
  20481. ** + for named semaphore locks (VxWorks only)
  20482. ** + for AFP filesystem locks (MacOSX only)
  20483. ** * sqlite3_file methods not associated with locking.
  20484. ** * Definitions of sqlite3_io_methods objects for all locking
  20485. ** methods plus "finder" functions for each locking method.
  20486. ** * sqlite3_vfs method implementations.
  20487. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  20488. ** * Definitions of sqlite3_vfs objects for all locking methods
  20489. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  20490. **
  20491. ** $Id: os_unix.c,v 1.237 2009/01/15 04:30:03 drh Exp $
  20492. */
  20493. #if SQLITE_OS_UNIX /* This file is used on unix only */
  20494. /*
  20495. ** There are various methods for file locking used for concurrency
  20496. ** control:
  20497. **
  20498. ** 1. POSIX locking (the default),
  20499. ** 2. No locking,
  20500. ** 3. Dot-file locking,
  20501. ** 4. flock() locking,
  20502. ** 5. AFP locking (OSX only),
  20503. ** 6. Named POSIX semaphores (VXWorks only),
  20504. ** 7. proxy locking. (OSX only)
  20505. **
  20506. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  20507. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  20508. ** selection of the appropriate locking style based on the filesystem
  20509. ** where the database is located.
  20510. */
  20511. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  20512. # if defined(__APPLE__)
  20513. # define SQLITE_ENABLE_LOCKING_STYLE 1
  20514. # else
  20515. # define SQLITE_ENABLE_LOCKING_STYLE 0
  20516. # endif
  20517. #endif
  20518. /*
  20519. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  20520. ** vxworks, or 0 otherwise.
  20521. */
  20522. #ifndef OS_VXWORKS
  20523. # if defined(__RTP__) || defined(_WRS_KERNEL)
  20524. # define OS_VXWORKS 1
  20525. # else
  20526. # define OS_VXWORKS 0
  20527. # endif
  20528. #endif
  20529. /*
  20530. ** These #defines should enable >2GB file support on Posix if the
  20531. ** underlying operating system supports it. If the OS lacks
  20532. ** large file support, these should be no-ops.
  20533. **
  20534. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  20535. ** on the compiler command line. This is necessary if you are compiling
  20536. ** on a recent machine (ex: RedHat 7.2) but you want your code to work
  20537. ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
  20538. ** without this option, LFS is enable. But LFS does not exist in the kernel
  20539. ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
  20540. ** portability you should omit LFS.
  20541. **
  20542. ** The previous paragraph was written in 2005. (This paragraph is written
  20543. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  20544. ** you should probably leave LFS enabled. But some embedded platforms might
  20545. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  20546. */
  20547. #ifndef SQLITE_DISABLE_LFS
  20548. # define _LARGE_FILE 1
  20549. # ifndef _FILE_OFFSET_BITS
  20550. # define _FILE_OFFSET_BITS 64
  20551. # endif
  20552. # define _LARGEFILE_SOURCE 1
  20553. #endif
  20554. /*
  20555. ** standard include files.
  20556. */
  20557. #include <sys/types.h>
  20558. #include <sys/stat.h>
  20559. #include <fcntl.h>
  20560. #include <unistd.h>
  20561. #include <sys/time.h>
  20562. #include <errno.h>
  20563. #if SQLITE_ENABLE_LOCKING_STYLE
  20564. # include <sys/ioctl.h>
  20565. # if OS_VXWORKS
  20566. # include <semaphore.h>
  20567. # include <limits.h>
  20568. # else
  20569. # include <sys/file.h>
  20570. # include <sys/param.h>
  20571. # include <sys/mount.h>
  20572. # endif
  20573. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  20574. /*
  20575. ** If we are to be thread-safe, include the pthreads header and define
  20576. ** the SQLITE_UNIX_THREADS macro.
  20577. */
  20578. #if SQLITE_THREADSAFE
  20579. # define SQLITE_UNIX_THREADS 1
  20580. #endif
  20581. /*
  20582. ** Default permissions when creating a new file
  20583. */
  20584. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  20585. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  20586. #endif
  20587. /*
  20588. ** Default permissions when creating auto proxy dir
  20589. */
  20590. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  20591. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  20592. #endif
  20593. /*
  20594. ** Maximum supported path-length.
  20595. */
  20596. #define MAX_PATHNAME 512
  20597. /*
  20598. ** Only set the lastErrno if the error code is a real error and not
  20599. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  20600. */
  20601. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  20602. /*
  20603. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  20604. ** VFS implementations.
  20605. */
  20606. typedef struct unixFile unixFile;
  20607. struct unixFile {
  20608. sqlite3_io_methods const *pMethod; /* Always the first entry */
  20609. struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
  20610. struct unixLockInfo *pLock; /* Info about locks on this inode */
  20611. int h; /* The file descriptor */
  20612. int dirfd; /* File descriptor for the directory */
  20613. unsigned char locktype; /* The type of lock held on this fd */
  20614. int lastErrno; /* The unix errno from the last I/O error */
  20615. void *lockingContext; /* Locking style specific state */
  20616. int openFlags; /* The flags specified at open */
  20617. #if SQLITE_THREADSAFE && defined(__linux__)
  20618. pthread_t tid; /* The thread that "owns" this unixFile */
  20619. #endif
  20620. #if OS_VXWORKS
  20621. int isDelete; /* Delete on close if true */
  20622. struct vxworksFileId *pId; /* Unique file ID */
  20623. #endif
  20624. #ifndef NDEBUG
  20625. /* The next group of variables are used to track whether or not the
  20626. ** transaction counter in bytes 24-27 of database files are updated
  20627. ** whenever any part of the database changes. An assertion fault will
  20628. ** occur if a file is updated without also updating the transaction
  20629. ** counter. This test is made to avoid new problems similar to the
  20630. ** one described by ticket #3584.
  20631. */
  20632. unsigned char transCntrChng; /* True if the transaction counter changed */
  20633. unsigned char dbUpdate; /* True if any part of database file changed */
  20634. unsigned char inNormalWrite; /* True if in a normal write operation */
  20635. #endif
  20636. #ifdef SQLITE_TEST
  20637. /* In test mode, increase the size of this structure a bit so that
  20638. ** it is larger than the struct CrashFile defined in test6.c.
  20639. */
  20640. char aPadding[32];
  20641. #endif
  20642. };
  20643. /*
  20644. ** Include code that is common to all os_*.c files
  20645. */
  20646. /************** Include os_common.h in the middle of os_unix.c ***************/
  20647. /************** Begin file os_common.h ***************************************/
  20648. /*
  20649. ** 2004 May 22
  20650. **
  20651. ** The author disclaims copyright to this source code. In place of
  20652. ** a legal notice, here is a blessing:
  20653. **
  20654. ** May you do good and not evil.
  20655. ** May you find forgiveness for yourself and forgive others.
  20656. ** May you share freely, never taking more than you give.
  20657. **
  20658. ******************************************************************************
  20659. **
  20660. ** This file contains macros and a little bit of code that is common to
  20661. ** all of the platform-specific files (os_*.c) and is #included into those
  20662. ** files.
  20663. **
  20664. ** This file should be #included by the os_*.c files only. It is not a
  20665. ** general purpose header file.
  20666. **
  20667. ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
  20668. */
  20669. #ifndef _OS_COMMON_H_
  20670. #define _OS_COMMON_H_
  20671. /*
  20672. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  20673. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  20674. ** switch. The following code should catch this problem at compile-time.
  20675. */
  20676. #ifdef MEMORY_DEBUG
  20677. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  20678. #endif
  20679. /*
  20680. * When testing, this global variable stores the location of the
  20681. * pending-byte in the database file.
  20682. */
  20683. #ifdef SQLITE_TEST
  20684. SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
  20685. #endif
  20686. #ifdef SQLITE_DEBUG
  20687. SQLITE_PRIVATE int sqlite3OSTrace = 0;
  20688. #define OSTRACE1(X) if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
  20689. #define OSTRACE2(X,Y) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
  20690. #define OSTRACE3(X,Y,Z) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
  20691. #define OSTRACE4(X,Y,Z,A) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
  20692. #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
  20693. #define OSTRACE6(X,Y,Z,A,B,C) \
  20694. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
  20695. #define OSTRACE7(X,Y,Z,A,B,C,D) \
  20696. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
  20697. #else
  20698. #define OSTRACE1(X)
  20699. #define OSTRACE2(X,Y)
  20700. #define OSTRACE3(X,Y,Z)
  20701. #define OSTRACE4(X,Y,Z,A)
  20702. #define OSTRACE5(X,Y,Z,A,B)
  20703. #define OSTRACE6(X,Y,Z,A,B,C)
  20704. #define OSTRACE7(X,Y,Z,A,B,C,D)
  20705. #endif
  20706. /*
  20707. ** Macros for performance tracing. Normally turned off. Only works
  20708. ** on i486 hardware.
  20709. */
  20710. #ifdef SQLITE_PERFORMANCE_TRACE
  20711. /*
  20712. ** hwtime.h contains inline assembler code for implementing
  20713. ** high-performance timing routines.
  20714. */
  20715. /************** Include hwtime.h in the middle of os_common.h ****************/
  20716. /************** Begin file hwtime.h ******************************************/
  20717. /*
  20718. ** 2008 May 27
  20719. **
  20720. ** The author disclaims copyright to this source code. In place of
  20721. ** a legal notice, here is a blessing:
  20722. **
  20723. ** May you do good and not evil.
  20724. ** May you find forgiveness for yourself and forgive others.
  20725. ** May you share freely, never taking more than you give.
  20726. **
  20727. ******************************************************************************
  20728. **
  20729. ** This file contains inline asm code for retrieving "high-performance"
  20730. ** counters for x86 class CPUs.
  20731. **
  20732. ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
  20733. */
  20734. #ifndef _HWTIME_H_
  20735. #define _HWTIME_H_
  20736. /*
  20737. ** The following routine only works on pentium-class (or newer) processors.
  20738. ** It uses the RDTSC opcode to read the cycle count value out of the
  20739. ** processor and returns that value. This can be used for high-res
  20740. ** profiling.
  20741. */
  20742. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  20743. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  20744. #if defined(__GNUC__)
  20745. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20746. unsigned int lo, hi;
  20747. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  20748. return (sqlite_uint64)hi << 32 | lo;
  20749. }
  20750. #elif defined(_MSC_VER)
  20751. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  20752. __asm {
  20753. rdtsc
  20754. ret ; return value at EDX:EAX
  20755. }
  20756. }
  20757. #endif
  20758. #elif (defined(__GNUC__) && defined(__x86_64__))
  20759. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20760. unsigned long val;
  20761. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  20762. return val;
  20763. }
  20764. #elif (defined(__GNUC__) && defined(__ppc__))
  20765. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20766. unsigned long long retval;
  20767. unsigned long junk;
  20768. __asm__ __volatile__ ("\n\
  20769. 1: mftbu %1\n\
  20770. mftb %L0\n\
  20771. mftbu %0\n\
  20772. cmpw %0,%1\n\
  20773. bne 1b"
  20774. : "=r" (retval), "=r" (junk));
  20775. return retval;
  20776. }
  20777. #else
  20778. #error Need implementation of sqlite3Hwtime() for your platform.
  20779. /*
  20780. ** To compile without implementing sqlite3Hwtime() for your platform,
  20781. ** you can remove the above #error and use the following
  20782. ** stub function. You will lose timing support for many
  20783. ** of the debugging and testing utilities, but it should at
  20784. ** least compile and run.
  20785. */
  20786. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  20787. #endif
  20788. #endif /* !defined(_HWTIME_H_) */
  20789. /************** End of hwtime.h **********************************************/
  20790. /************** Continuing where we left off in os_common.h ******************/
  20791. static sqlite_uint64 g_start;
  20792. static sqlite_uint64 g_elapsed;
  20793. #define TIMER_START g_start=sqlite3Hwtime()
  20794. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  20795. #define TIMER_ELAPSED g_elapsed
  20796. #else
  20797. #define TIMER_START
  20798. #define TIMER_END
  20799. #define TIMER_ELAPSED ((sqlite_uint64)0)
  20800. #endif
  20801. /*
  20802. ** If we compile with the SQLITE_TEST macro set, then the following block
  20803. ** of code will give us the ability to simulate a disk I/O error. This
  20804. ** is used for testing the I/O recovery logic.
  20805. */
  20806. #ifdef SQLITE_TEST
  20807. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  20808. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  20809. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  20810. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  20811. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  20812. SQLITE_API int sqlite3_diskfull_pending = 0;
  20813. SQLITE_API int sqlite3_diskfull = 0;
  20814. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  20815. #define SimulateIOError(CODE) \
  20816. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  20817. || sqlite3_io_error_pending-- == 1 ) \
  20818. { local_ioerr(); CODE; }
  20819. static void local_ioerr(){
  20820. IOTRACE(("IOERR\n"));
  20821. sqlite3_io_error_hit++;
  20822. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  20823. }
  20824. #define SimulateDiskfullError(CODE) \
  20825. if( sqlite3_diskfull_pending ){ \
  20826. if( sqlite3_diskfull_pending == 1 ){ \
  20827. local_ioerr(); \
  20828. sqlite3_diskfull = 1; \
  20829. sqlite3_io_error_hit = 1; \
  20830. CODE; \
  20831. }else{ \
  20832. sqlite3_diskfull_pending--; \
  20833. } \
  20834. }
  20835. #else
  20836. #define SimulateIOErrorBenign(X)
  20837. #define SimulateIOError(A)
  20838. #define SimulateDiskfullError(A)
  20839. #endif
  20840. /*
  20841. ** When testing, keep a count of the number of open files.
  20842. */
  20843. #ifdef SQLITE_TEST
  20844. SQLITE_API int sqlite3_open_file_count = 0;
  20845. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  20846. #else
  20847. #define OpenCounter(X)
  20848. #endif
  20849. #endif /* !defined(_OS_COMMON_H_) */
  20850. /************** End of os_common.h *******************************************/
  20851. /************** Continuing where we left off in os_unix.c ********************/
  20852. /*
  20853. ** Define various macros that are missing from some systems.
  20854. */
  20855. #ifndef O_LARGEFILE
  20856. # define O_LARGEFILE 0
  20857. #endif
  20858. #ifdef SQLITE_DISABLE_LFS
  20859. # undef O_LARGEFILE
  20860. # define O_LARGEFILE 0
  20861. #endif
  20862. #ifndef O_NOFOLLOW
  20863. # define O_NOFOLLOW 0
  20864. #endif
  20865. #ifndef O_BINARY
  20866. # define O_BINARY 0
  20867. #endif
  20868. /*
  20869. ** The DJGPP compiler environment looks mostly like Unix, but it
  20870. ** lacks the fcntl() system call. So redefine fcntl() to be something
  20871. ** that always succeeds. This means that locking does not occur under
  20872. ** DJGPP. But it is DOS - what did you expect?
  20873. */
  20874. #ifdef __DJGPP__
  20875. # define fcntl(A,B,C) 0
  20876. #endif
  20877. /*
  20878. ** The threadid macro resolves to the thread-id or to 0. Used for
  20879. ** testing and debugging only.
  20880. */
  20881. #if SQLITE_THREADSAFE
  20882. #define threadid pthread_self()
  20883. #else
  20884. #define threadid 0
  20885. #endif
  20886. /*
  20887. ** Helper functions to obtain and relinquish the global mutex.
  20888. */
  20889. static void unixEnterMutex(void){
  20890. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  20891. }
  20892. static void unixLeaveMutex(void){
  20893. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  20894. }
  20895. #ifdef SQLITE_DEBUG
  20896. /*
  20897. ** Helper function for printing out trace information from debugging
  20898. ** binaries. This returns the string represetation of the supplied
  20899. ** integer lock-type.
  20900. */
  20901. static const char *locktypeName(int locktype){
  20902. switch( locktype ){
  20903. case NO_LOCK: return "NONE";
  20904. case SHARED_LOCK: return "SHARED";
  20905. case RESERVED_LOCK: return "RESERVED";
  20906. case PENDING_LOCK: return "PENDING";
  20907. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  20908. }
  20909. return "ERROR";
  20910. }
  20911. #endif
  20912. #ifdef SQLITE_LOCK_TRACE
  20913. /*
  20914. ** Print out information about all locking operations.
  20915. **
  20916. ** This routine is used for troubleshooting locks on multithreaded
  20917. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  20918. ** command-line option on the compiler. This code is normally
  20919. ** turned off.
  20920. */
  20921. static int lockTrace(int fd, int op, struct flock *p){
  20922. char *zOpName, *zType;
  20923. int s;
  20924. int savedErrno;
  20925. if( op==F_GETLK ){
  20926. zOpName = "GETLK";
  20927. }else if( op==F_SETLK ){
  20928. zOpName = "SETLK";
  20929. }else{
  20930. s = fcntl(fd, op, p);
  20931. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  20932. return s;
  20933. }
  20934. if( p->l_type==F_RDLCK ){
  20935. zType = "RDLCK";
  20936. }else if( p->l_type==F_WRLCK ){
  20937. zType = "WRLCK";
  20938. }else if( p->l_type==F_UNLCK ){
  20939. zType = "UNLCK";
  20940. }else{
  20941. assert( 0 );
  20942. }
  20943. assert( p->l_whence==SEEK_SET );
  20944. s = fcntl(fd, op, p);
  20945. savedErrno = errno;
  20946. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  20947. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  20948. (int)p->l_pid, s);
  20949. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  20950. struct flock l2;
  20951. l2 = *p;
  20952. fcntl(fd, F_GETLK, &l2);
  20953. if( l2.l_type==F_RDLCK ){
  20954. zType = "RDLCK";
  20955. }else if( l2.l_type==F_WRLCK ){
  20956. zType = "WRLCK";
  20957. }else if( l2.l_type==F_UNLCK ){
  20958. zType = "UNLCK";
  20959. }else{
  20960. assert( 0 );
  20961. }
  20962. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  20963. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  20964. }
  20965. errno = savedErrno;
  20966. return s;
  20967. }
  20968. #define fcntl lockTrace
  20969. #endif /* SQLITE_LOCK_TRACE */
  20970. /*
  20971. ** This routine translates a standard POSIX errno code into something
  20972. ** useful to the clients of the sqlite3 functions. Specifically, it is
  20973. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  20974. ** and a variety of "please close the file descriptor NOW" errors into
  20975. ** SQLITE_IOERR
  20976. **
  20977. ** Errors during initialization of locks, or file system support for locks,
  20978. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  20979. */
  20980. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  20981. switch (posixError) {
  20982. case 0:
  20983. return SQLITE_OK;
  20984. case EAGAIN:
  20985. case ETIMEDOUT:
  20986. case EBUSY:
  20987. case EINTR:
  20988. case ENOLCK:
  20989. /* random NFS retry error, unless during file system support
  20990. * introspection, in which it actually means what it says */
  20991. return SQLITE_BUSY;
  20992. case EACCES:
  20993. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  20994. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  20995. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  20996. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  20997. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  20998. return SQLITE_BUSY;
  20999. }
  21000. /* else fall through */
  21001. case EPERM:
  21002. return SQLITE_PERM;
  21003. case EDEADLK:
  21004. return SQLITE_IOERR_BLOCKED;
  21005. #if EOPNOTSUPP!=ENOTSUP
  21006. case EOPNOTSUPP:
  21007. /* something went terribly awry, unless during file system support
  21008. * introspection, in which it actually means what it says */
  21009. #endif
  21010. #ifdef ENOTSUP
  21011. case ENOTSUP:
  21012. /* invalid fd, unless during file system support introspection, in which
  21013. * it actually means what it says */
  21014. #endif
  21015. case EIO:
  21016. case EBADF:
  21017. case EINVAL:
  21018. case ENOTCONN:
  21019. case ENODEV:
  21020. case ENXIO:
  21021. case ENOENT:
  21022. case ESTALE:
  21023. case ENOSYS:
  21024. /* these should force the client to close the file and reconnect */
  21025. default:
  21026. return sqliteIOErr;
  21027. }
  21028. }
  21029. /******************************************************************************
  21030. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  21031. **
  21032. ** On most versions of unix, we can get a unique ID for a file by concatenating
  21033. ** the device number and the inode number. But this does not work on VxWorks.
  21034. ** On VxWorks, a unique file id must be based on the canonical filename.
  21035. **
  21036. ** A pointer to an instance of the following structure can be used as a
  21037. ** unique file ID in VxWorks. Each instance of this structure contains
  21038. ** a copy of the canonical filename. There is also a reference count.
  21039. ** The structure is reclaimed when the number of pointers to it drops to
  21040. ** zero.
  21041. **
  21042. ** There are never very many files open at one time and lookups are not
  21043. ** a performance-critical path, so it is sufficient to put these
  21044. ** structures on a linked list.
  21045. */
  21046. struct vxworksFileId {
  21047. struct vxworksFileId *pNext; /* Next in a list of them all */
  21048. int nRef; /* Number of references to this one */
  21049. int nName; /* Length of the zCanonicalName[] string */
  21050. char *zCanonicalName; /* Canonical filename */
  21051. };
  21052. #if OS_VXWORKS
  21053. /*
  21054. ** All unique filenames are held on a linked list headed by this
  21055. ** variable:
  21056. */
  21057. static struct vxworksFileId *vxworksFileList = 0;
  21058. /*
  21059. ** Simplify a filename into its canonical form
  21060. ** by making the following changes:
  21061. **
  21062. ** * removing any trailing and duplicate /
  21063. ** * convert /./ into just /
  21064. ** * convert /A/../ where A is any simple name into just /
  21065. **
  21066. ** Changes are made in-place. Return the new name length.
  21067. **
  21068. ** The original filename is in z[0..n-1]. Return the number of
  21069. ** characters in the simplified name.
  21070. */
  21071. static int vxworksSimplifyName(char *z, int n){
  21072. int i, j;
  21073. while( n>1 && z[n-1]=='/' ){ n--; }
  21074. for(i=j=0; i<n; i++){
  21075. if( z[i]=='/' ){
  21076. if( z[i+1]=='/' ) continue;
  21077. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  21078. i += 1;
  21079. continue;
  21080. }
  21081. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  21082. while( j>0 && z[j-1]!='/' ){ j--; }
  21083. if( j>0 ){ j--; }
  21084. i += 2;
  21085. continue;
  21086. }
  21087. }
  21088. z[j++] = z[i];
  21089. }
  21090. z[j] = 0;
  21091. return j;
  21092. }
  21093. /*
  21094. ** Find a unique file ID for the given absolute pathname. Return
  21095. ** a pointer to the vxworksFileId object. This pointer is the unique
  21096. ** file ID.
  21097. **
  21098. ** The nRef field of the vxworksFileId object is incremented before
  21099. ** the object is returned. A new vxworksFileId object is created
  21100. ** and added to the global list if necessary.
  21101. **
  21102. ** If a memory allocation error occurs, return NULL.
  21103. */
  21104. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  21105. struct vxworksFileId *pNew; /* search key and new file ID */
  21106. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  21107. int n; /* Length of zAbsoluteName string */
  21108. assert( zAbsoluteName[0]=='/' );
  21109. n = (int)strlen(zAbsoluteName);
  21110. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  21111. if( pNew==0 ) return 0;
  21112. pNew->zCanonicalName = (char*)&pNew[1];
  21113. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  21114. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  21115. /* Search for an existing entry that matching the canonical name.
  21116. ** If found, increment the reference count and return a pointer to
  21117. ** the existing file ID.
  21118. */
  21119. unixEnterMutex();
  21120. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  21121. if( pCandidate->nName==n
  21122. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  21123. ){
  21124. sqlite3_free(pNew);
  21125. pCandidate->nRef++;
  21126. unixLeaveMutex();
  21127. return pCandidate;
  21128. }
  21129. }
  21130. /* No match was found. We will make a new file ID */
  21131. pNew->nRef = 1;
  21132. pNew->nName = n;
  21133. pNew->pNext = vxworksFileList;
  21134. vxworksFileList = pNew;
  21135. unixLeaveMutex();
  21136. return pNew;
  21137. }
  21138. /*
  21139. ** Decrement the reference count on a vxworksFileId object. Free
  21140. ** the object when the reference count reaches zero.
  21141. */
  21142. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  21143. unixEnterMutex();
  21144. assert( pId->nRef>0 );
  21145. pId->nRef--;
  21146. if( pId->nRef==0 ){
  21147. struct vxworksFileId **pp;
  21148. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  21149. assert( *pp==pId );
  21150. *pp = pId->pNext;
  21151. sqlite3_free(pId);
  21152. }
  21153. unixLeaveMutex();
  21154. }
  21155. #endif /* OS_VXWORKS */
  21156. /*************** End of Unique File ID Utility Used By VxWorks ****************
  21157. ******************************************************************************/
  21158. /******************************************************************************
  21159. *************************** Posix Advisory Locking ****************************
  21160. **
  21161. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  21162. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  21163. ** sets or clears a lock, that operation overrides any prior locks set
  21164. ** by the same process. It does not explicitly say so, but this implies
  21165. ** that it overrides locks set by the same process using a different
  21166. ** file descriptor. Consider this test case:
  21167. **
  21168. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  21169. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  21170. **
  21171. ** Suppose ./file1 and ./file2 are really the same file (because
  21172. ** one is a hard or symbolic link to the other) then if you set
  21173. ** an exclusive lock on fd1, then try to get an exclusive lock
  21174. ** on fd2, it works. I would have expected the second lock to
  21175. ** fail since there was already a lock on the file due to fd1.
  21176. ** But not so. Since both locks came from the same process, the
  21177. ** second overrides the first, even though they were on different
  21178. ** file descriptors opened on different file names.
  21179. **
  21180. ** This means that we cannot use POSIX locks to synchronize file access
  21181. ** among competing threads of the same process. POSIX locks will work fine
  21182. ** to synchronize access for threads in separate processes, but not
  21183. ** threads within the same process.
  21184. **
  21185. ** To work around the problem, SQLite has to manage file locks internally
  21186. ** on its own. Whenever a new database is opened, we have to find the
  21187. ** specific inode of the database file (the inode is determined by the
  21188. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  21189. ** and check for locks already existing on that inode. When locks are
  21190. ** created or removed, we have to look at our own internal record of the
  21191. ** locks to see if another thread has previously set a lock on that same
  21192. ** inode.
  21193. **
  21194. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  21195. ** For VxWorks, we have to use the alternative unique ID system based on
  21196. ** canonical filename and implemented in the previous division.)
  21197. **
  21198. ** The sqlite3_file structure for POSIX is no longer just an integer file
  21199. ** descriptor. It is now a structure that holds the integer file
  21200. ** descriptor and a pointer to a structure that describes the internal
  21201. ** locks on the corresponding inode. There is one locking structure
  21202. ** per inode, so if the same inode is opened twice, both unixFile structures
  21203. ** point to the same locking structure. The locking structure keeps
  21204. ** a reference count (so we will know when to delete it) and a "cnt"
  21205. ** field that tells us its internal lock status. cnt==0 means the
  21206. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  21207. ** cnt>0 means there are cnt shared locks on the file.
  21208. **
  21209. ** Any attempt to lock or unlock a file first checks the locking
  21210. ** structure. The fcntl() system call is only invoked to set a
  21211. ** POSIX lock if the internal lock structure transitions between
  21212. ** a locked and an unlocked state.
  21213. **
  21214. ** But wait: there are yet more problems with POSIX advisory locks.
  21215. **
  21216. ** If you close a file descriptor that points to a file that has locks,
  21217. ** all locks on that file that are owned by the current process are
  21218. ** released. To work around this problem, each unixFile structure contains
  21219. ** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
  21220. ** per open inode, which means that multiple unixFile can point to a single
  21221. ** unixOpenCnt. When an attempt is made to close an unixFile, if there are
  21222. ** other unixFile open on the same inode that are holding locks, the call
  21223. ** to close() the file descriptor is deferred until all of the locks clear.
  21224. ** The unixOpenCnt structure keeps a list of file descriptors that need to
  21225. ** be closed and that list is walked (and cleared) when the last lock
  21226. ** clears.
  21227. **
  21228. ** Yet another problem: LinuxThreads do not play well with posix locks.
  21229. **
  21230. ** Many older versions of linux use the LinuxThreads library which is
  21231. ** not posix compliant. Under LinuxThreads, a lock created by thread
  21232. ** A cannot be modified or overridden by a different thread B.
  21233. ** Only thread A can modify the lock. Locking behavior is correct
  21234. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  21235. ** on linux - with NPTL a lock created by thread A can override locks
  21236. ** in thread B. But there is no way to know at compile-time which
  21237. ** threading library is being used. So there is no way to know at
  21238. ** compile-time whether or not thread A can override locks on thread B.
  21239. ** We have to do a run-time check to discover the behavior of the
  21240. ** current process.
  21241. **
  21242. ** On systems where thread A is unable to modify locks created by
  21243. ** thread B, we have to keep track of which thread created each
  21244. ** lock. Hence there is an extra field in the key to the unixLockInfo
  21245. ** structure to record this information. And on those systems it
  21246. ** is illegal to begin a transaction in one thread and finish it
  21247. ** in another. For this latter restriction, there is no work-around.
  21248. ** It is a limitation of LinuxThreads.
  21249. */
  21250. /*
  21251. ** Set or check the unixFile.tid field. This field is set when an unixFile
  21252. ** is first opened. All subsequent uses of the unixFile verify that the
  21253. ** same thread is operating on the unixFile. Some operating systems do
  21254. ** not allow locks to be overridden by other threads and that restriction
  21255. ** means that sqlite3* database handles cannot be moved from one thread
  21256. ** to another while locks are held.
  21257. **
  21258. ** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
  21259. ** another as long as we are running on a system that supports threads
  21260. ** overriding each others locks (which is now the most common behavior)
  21261. ** or if no locks are held. But the unixFile.pLock field needs to be
  21262. ** recomputed because its key includes the thread-id. See the
  21263. ** transferOwnership() function below for additional information
  21264. */
  21265. #if SQLITE_THREADSAFE && defined(__linux__)
  21266. # define SET_THREADID(X) (X)->tid = pthread_self()
  21267. # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
  21268. !pthread_equal((X)->tid, pthread_self()))
  21269. #else
  21270. # define SET_THREADID(X)
  21271. # define CHECK_THREADID(X) 0
  21272. #endif
  21273. /*
  21274. ** An instance of the following structure serves as the key used
  21275. ** to locate a particular unixOpenCnt structure given its inode. This
  21276. ** is the same as the unixLockKey except that the thread ID is omitted.
  21277. */
  21278. struct unixFileId {
  21279. dev_t dev; /* Device number */
  21280. #if OS_VXWORKS
  21281. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  21282. #else
  21283. ino_t ino; /* Inode number */
  21284. #endif
  21285. };
  21286. /*
  21287. ** An instance of the following structure serves as the key used
  21288. ** to locate a particular unixLockInfo structure given its inode.
  21289. **
  21290. ** If threads cannot override each others locks (LinuxThreads), then we
  21291. ** set the unixLockKey.tid field to the thread ID. If threads can override
  21292. ** each others locks (Posix and NPTL) then tid is always set to zero.
  21293. ** tid is omitted if we compile without threading support or on an OS
  21294. ** other than linux.
  21295. */
  21296. struct unixLockKey {
  21297. struct unixFileId fid; /* Unique identifier for the file */
  21298. #if SQLITE_THREADSAFE && defined(__linux__)
  21299. pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
  21300. #endif
  21301. };
  21302. /*
  21303. ** An instance of the following structure is allocated for each open
  21304. ** inode. Or, on LinuxThreads, there is one of these structures for
  21305. ** each inode opened by each thread.
  21306. **
  21307. ** A single inode can have multiple file descriptors, so each unixFile
  21308. ** structure contains a pointer to an instance of this object and this
  21309. ** object keeps a count of the number of unixFile pointing to it.
  21310. */
  21311. struct unixLockInfo {
  21312. struct unixLockKey lockKey; /* The lookup key */
  21313. int cnt; /* Number of SHARED locks held */
  21314. int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  21315. int nRef; /* Number of pointers to this structure */
  21316. struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
  21317. struct unixLockInfo *pPrev; /* .... doubly linked */
  21318. };
  21319. /*
  21320. ** An instance of the following structure is allocated for each open
  21321. ** inode. This structure keeps track of the number of locks on that
  21322. ** inode. If a close is attempted against an inode that is holding
  21323. ** locks, the close is deferred until all locks clear by adding the
  21324. ** file descriptor to be closed to the pending list.
  21325. **
  21326. ** TODO: Consider changing this so that there is only a single file
  21327. ** descriptor for each open file, even when it is opened multiple times.
  21328. ** The close() system call would only occur when the last database
  21329. ** using the file closes.
  21330. */
  21331. struct unixOpenCnt {
  21332. struct unixFileId fileId; /* The lookup key */
  21333. int nRef; /* Number of pointers to this structure */
  21334. int nLock; /* Number of outstanding locks */
  21335. int nPending; /* Number of pending close() operations */
  21336. int *aPending; /* Malloced space holding fd's awaiting a close() */
  21337. #if OS_VXWORKS
  21338. sem_t *pSem; /* Named POSIX semaphore */
  21339. char aSemName[MAX_PATHNAME+1]; /* Name of that semaphore */
  21340. #endif
  21341. struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
  21342. };
  21343. /*
  21344. ** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
  21345. ** tables. But the number of objects is rarely more than a dozen and
  21346. ** never exceeds a few thousand. And lookup is not on a critical
  21347. ** path so a simple linked list will suffice.
  21348. */
  21349. static struct unixLockInfo *lockList = 0;
  21350. static struct unixOpenCnt *openList = 0;
  21351. /*
  21352. ** This variable remembers whether or not threads can override each others
  21353. ** locks.
  21354. **
  21355. ** 0: No. Threads cannot override each others locks. (LinuxThreads)
  21356. ** 1: Yes. Threads can override each others locks. (Posix & NLPT)
  21357. ** -1: We don't know yet.
  21358. **
  21359. ** On some systems, we know at compile-time if threads can override each
  21360. ** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
  21361. ** will be set appropriately. On other systems, we have to check at
  21362. ** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
  21363. ** undefined.
  21364. **
  21365. ** This variable normally has file scope only. But during testing, we make
  21366. ** it a global so that the test code can change its value in order to verify
  21367. ** that the right stuff happens in either case.
  21368. */
  21369. #if SQLITE_THREADSAFE && defined(__linux__)
  21370. # ifndef SQLITE_THREAD_OVERRIDE_LOCK
  21371. # define SQLITE_THREAD_OVERRIDE_LOCK -1
  21372. # endif
  21373. # ifdef SQLITE_TEST
  21374. int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
  21375. # else
  21376. static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
  21377. # endif
  21378. #endif
  21379. /*
  21380. ** This structure holds information passed into individual test
  21381. ** threads by the testThreadLockingBehavior() routine.
  21382. */
  21383. struct threadTestData {
  21384. int fd; /* File to be locked */
  21385. struct flock lock; /* The locking operation */
  21386. int result; /* Result of the locking operation */
  21387. };
  21388. #if SQLITE_THREADSAFE && defined(__linux__)
  21389. /*
  21390. ** This function is used as the main routine for a thread launched by
  21391. ** testThreadLockingBehavior(). It tests whether the shared-lock obtained
  21392. ** by the main thread in testThreadLockingBehavior() conflicts with a
  21393. ** hypothetical write-lock obtained by this thread on the same file.
  21394. **
  21395. ** The write-lock is not actually acquired, as this is not possible if
  21396. ** the file is open in read-only mode (see ticket #3472).
  21397. */
  21398. static void *threadLockingTest(void *pArg){
  21399. struct threadTestData *pData = (struct threadTestData*)pArg;
  21400. pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
  21401. return pArg;
  21402. }
  21403. #endif /* SQLITE_THREADSAFE && defined(__linux__) */
  21404. #if SQLITE_THREADSAFE && defined(__linux__)
  21405. /*
  21406. ** This procedure attempts to determine whether or not threads
  21407. ** can override each others locks then sets the
  21408. ** threadsOverrideEachOthersLocks variable appropriately.
  21409. */
  21410. static void testThreadLockingBehavior(int fd_orig){
  21411. int fd;
  21412. int rc;
  21413. struct threadTestData d;
  21414. struct flock l;
  21415. pthread_t t;
  21416. fd = dup(fd_orig);
  21417. if( fd<0 ) return;
  21418. memset(&l, 0, sizeof(l));
  21419. l.l_type = F_RDLCK;
  21420. l.l_len = 1;
  21421. l.l_start = 0;
  21422. l.l_whence = SEEK_SET;
  21423. rc = fcntl(fd_orig, F_SETLK, &l);
  21424. if( rc!=0 ) return;
  21425. memset(&d, 0, sizeof(d));
  21426. d.fd = fd;
  21427. d.lock = l;
  21428. d.lock.l_type = F_WRLCK;
  21429. pthread_create(&t, 0, threadLockingTest, &d);
  21430. pthread_join(t, 0);
  21431. close(fd);
  21432. if( d.result!=0 ) return;
  21433. threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
  21434. }
  21435. #endif /* SQLITE_THERADSAFE && defined(__linux__) */
  21436. /*
  21437. ** Release a unixLockInfo structure previously allocated by findLockInfo().
  21438. */
  21439. static void releaseLockInfo(struct unixLockInfo *pLock){
  21440. if( pLock ){
  21441. pLock->nRef--;
  21442. if( pLock->nRef==0 ){
  21443. if( pLock->pPrev ){
  21444. assert( pLock->pPrev->pNext==pLock );
  21445. pLock->pPrev->pNext = pLock->pNext;
  21446. }else{
  21447. assert( lockList==pLock );
  21448. lockList = pLock->pNext;
  21449. }
  21450. if( pLock->pNext ){
  21451. assert( pLock->pNext->pPrev==pLock );
  21452. pLock->pNext->pPrev = pLock->pPrev;
  21453. }
  21454. sqlite3_free(pLock);
  21455. }
  21456. }
  21457. }
  21458. /*
  21459. ** Release a unixOpenCnt structure previously allocated by findLockInfo().
  21460. */
  21461. static void releaseOpenCnt(struct unixOpenCnt *pOpen){
  21462. if( pOpen ){
  21463. pOpen->nRef--;
  21464. if( pOpen->nRef==0 ){
  21465. if( pOpen->pPrev ){
  21466. assert( pOpen->pPrev->pNext==pOpen );
  21467. pOpen->pPrev->pNext = pOpen->pNext;
  21468. }else{
  21469. assert( openList==pOpen );
  21470. openList = pOpen->pNext;
  21471. }
  21472. if( pOpen->pNext ){
  21473. assert( pOpen->pNext->pPrev==pOpen );
  21474. pOpen->pNext->pPrev = pOpen->pPrev;
  21475. }
  21476. sqlite3_free(pOpen->aPending);
  21477. sqlite3_free(pOpen);
  21478. }
  21479. }
  21480. }
  21481. /*
  21482. ** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
  21483. ** describes that file descriptor. Create new ones if necessary. The
  21484. ** return values might be uninitialized if an error occurs.
  21485. **
  21486. ** Return an appropriate error code.
  21487. */
  21488. static int findLockInfo(
  21489. unixFile *pFile, /* Unix file with file desc used in the key */
  21490. struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
  21491. struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
  21492. ){
  21493. int rc; /* System call return code */
  21494. int fd; /* The file descriptor for pFile */
  21495. struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
  21496. struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
  21497. struct stat statbuf; /* Low-level file information */
  21498. struct unixLockInfo *pLock; /* Candidate unixLockInfo object */
  21499. struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
  21500. /* Get low-level information about the file that we can used to
  21501. ** create a unique name for the file.
  21502. */
  21503. fd = pFile->h;
  21504. rc = fstat(fd, &statbuf);
  21505. if( rc!=0 ){
  21506. pFile->lastErrno = errno;
  21507. #ifdef EOVERFLOW
  21508. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  21509. #endif
  21510. return SQLITE_IOERR;
  21511. }
  21512. /* On OS X on an msdos filesystem, the inode number is reported
  21513. ** incorrectly for zero-size files. See ticket #3260. To work
  21514. ** around this problem (we consider it a bug in OS X, not SQLite)
  21515. ** we always increase the file size to 1 by writing a single byte
  21516. ** prior to accessing the inode number. The one byte written is
  21517. ** an ASCII 'S' character which also happens to be the first byte
  21518. ** in the header of every SQLite database. In this way, if there
  21519. ** is a race condition such that another thread has already populated
  21520. ** the first page of the database, no damage is done.
  21521. */
  21522. if( statbuf.st_size==0 ){
  21523. write(fd, "S", 1);
  21524. rc = fstat(fd, &statbuf);
  21525. if( rc!=0 ){
  21526. pFile->lastErrno = errno;
  21527. return SQLITE_IOERR;
  21528. }
  21529. }
  21530. memset(&lockKey, 0, sizeof(lockKey));
  21531. lockKey.fid.dev = statbuf.st_dev;
  21532. #if OS_VXWORKS
  21533. lockKey.fid.pId = pFile->pId;
  21534. #else
  21535. lockKey.fid.ino = statbuf.st_ino;
  21536. #endif
  21537. #if SQLITE_THREADSAFE && defined(__linux__)
  21538. if( threadsOverrideEachOthersLocks<0 ){
  21539. testThreadLockingBehavior(fd);
  21540. }
  21541. lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
  21542. #endif
  21543. fileId = lockKey.fid;
  21544. if( ppLock!=0 ){
  21545. pLock = lockList;
  21546. while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
  21547. pLock = pLock->pNext;
  21548. }
  21549. if( pLock==0 ){
  21550. pLock = sqlite3_malloc( sizeof(*pLock) );
  21551. if( pLock==0 ){
  21552. rc = SQLITE_NOMEM;
  21553. goto exit_findlockinfo;
  21554. }
  21555. pLock->lockKey = lockKey;
  21556. pLock->nRef = 1;
  21557. pLock->cnt = 0;
  21558. pLock->locktype = 0;
  21559. pLock->pNext = lockList;
  21560. pLock->pPrev = 0;
  21561. if( lockList ) lockList->pPrev = pLock;
  21562. lockList = pLock;
  21563. }else{
  21564. pLock->nRef++;
  21565. }
  21566. *ppLock = pLock;
  21567. }
  21568. if( ppOpen!=0 ){
  21569. pOpen = openList;
  21570. while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
  21571. pOpen = pOpen->pNext;
  21572. }
  21573. if( pOpen==0 ){
  21574. pOpen = sqlite3_malloc( sizeof(*pOpen) );
  21575. if( pOpen==0 ){
  21576. releaseLockInfo(pLock);
  21577. rc = SQLITE_NOMEM;
  21578. goto exit_findlockinfo;
  21579. }
  21580. pOpen->fileId = fileId;
  21581. pOpen->nRef = 1;
  21582. pOpen->nLock = 0;
  21583. pOpen->nPending = 0;
  21584. pOpen->aPending = 0;
  21585. pOpen->pNext = openList;
  21586. pOpen->pPrev = 0;
  21587. if( openList ) openList->pPrev = pOpen;
  21588. openList = pOpen;
  21589. #if OS_VXWORKS
  21590. pOpen->pSem = NULL;
  21591. pOpen->aSemName[0] = '\0';
  21592. #endif
  21593. }else{
  21594. pOpen->nRef++;
  21595. }
  21596. *ppOpen = pOpen;
  21597. }
  21598. exit_findlockinfo:
  21599. return rc;
  21600. }
  21601. /*
  21602. ** If we are currently in a different thread than the thread that the
  21603. ** unixFile argument belongs to, then transfer ownership of the unixFile
  21604. ** over to the current thread.
  21605. **
  21606. ** A unixFile is only owned by a thread on systems that use LinuxThreads.
  21607. **
  21608. ** Ownership transfer is only allowed if the unixFile is currently unlocked.
  21609. ** If the unixFile is locked and an ownership is wrong, then return
  21610. ** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
  21611. */
  21612. #if SQLITE_THREADSAFE && defined(__linux__)
  21613. static int transferOwnership(unixFile *pFile){
  21614. int rc;
  21615. pthread_t hSelf;
  21616. if( threadsOverrideEachOthersLocks ){
  21617. /* Ownership transfers not needed on this system */
  21618. return SQLITE_OK;
  21619. }
  21620. hSelf = pthread_self();
  21621. if( pthread_equal(pFile->tid, hSelf) ){
  21622. /* We are still in the same thread */
  21623. OSTRACE1("No-transfer, same thread\n");
  21624. return SQLITE_OK;
  21625. }
  21626. if( pFile->locktype!=NO_LOCK ){
  21627. /* We cannot change ownership while we are holding a lock! */
  21628. return SQLITE_MISUSE;
  21629. }
  21630. OSTRACE4("Transfer ownership of %d from %d to %d\n",
  21631. pFile->h, pFile->tid, hSelf);
  21632. pFile->tid = hSelf;
  21633. if (pFile->pLock != NULL) {
  21634. releaseLockInfo(pFile->pLock);
  21635. rc = findLockInfo(pFile, &pFile->pLock, 0);
  21636. OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
  21637. locktypeName(pFile->locktype),
  21638. locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
  21639. return rc;
  21640. } else {
  21641. return SQLITE_OK;
  21642. }
  21643. }
  21644. #else /* if not SQLITE_THREADSAFE */
  21645. /* On single-threaded builds, ownership transfer is a no-op */
  21646. # define transferOwnership(X) SQLITE_OK
  21647. #endif /* SQLITE_THREADSAFE */
  21648. /*
  21649. ** This routine checks if there is a RESERVED lock held on the specified
  21650. ** file by this or any other process. If such a lock is held, set *pResOut
  21651. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  21652. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  21653. */
  21654. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  21655. int rc = SQLITE_OK;
  21656. int reserved = 0;
  21657. unixFile *pFile = (unixFile*)id;
  21658. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  21659. assert( pFile );
  21660. unixEnterMutex(); /* Because pFile->pLock is shared across threads */
  21661. /* Check if a thread in this process holds such a lock */
  21662. if( pFile->pLock->locktype>SHARED_LOCK ){
  21663. reserved = 1;
  21664. }
  21665. /* Otherwise see if some other process holds it.
  21666. */
  21667. if( !reserved ){
  21668. struct flock lock;
  21669. lock.l_whence = SEEK_SET;
  21670. lock.l_start = RESERVED_BYTE;
  21671. lock.l_len = 1;
  21672. lock.l_type = F_WRLCK;
  21673. if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
  21674. int tErrno = errno;
  21675. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  21676. pFile->lastErrno = tErrno;
  21677. } else if( lock.l_type!=F_UNLCK ){
  21678. reserved = 1;
  21679. }
  21680. }
  21681. unixLeaveMutex();
  21682. OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  21683. *pResOut = reserved;
  21684. return rc;
  21685. }
  21686. /*
  21687. ** Lock the file with the lock specified by parameter locktype - one
  21688. ** of the following:
  21689. **
  21690. ** (1) SHARED_LOCK
  21691. ** (2) RESERVED_LOCK
  21692. ** (3) PENDING_LOCK
  21693. ** (4) EXCLUSIVE_LOCK
  21694. **
  21695. ** Sometimes when requesting one lock state, additional lock states
  21696. ** are inserted in between. The locking might fail on one of the later
  21697. ** transitions leaving the lock state different from what it started but
  21698. ** still short of its goal. The following chart shows the allowed
  21699. ** transitions and the inserted intermediate states:
  21700. **
  21701. ** UNLOCKED -> SHARED
  21702. ** SHARED -> RESERVED
  21703. ** SHARED -> (PENDING) -> EXCLUSIVE
  21704. ** RESERVED -> (PENDING) -> EXCLUSIVE
  21705. ** PENDING -> EXCLUSIVE
  21706. **
  21707. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  21708. ** routine to lower a locking level.
  21709. */
  21710. static int unixLock(sqlite3_file *id, int locktype){
  21711. /* The following describes the implementation of the various locks and
  21712. ** lock transitions in terms of the POSIX advisory shared and exclusive
  21713. ** lock primitives (called read-locks and write-locks below, to avoid
  21714. ** confusion with SQLite lock names). The algorithms are complicated
  21715. ** slightly in order to be compatible with windows systems simultaneously
  21716. ** accessing the same database file, in case that is ever required.
  21717. **
  21718. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  21719. ** byte', each single bytes at well known offsets, and the 'shared byte
  21720. ** range', a range of 510 bytes at a well known offset.
  21721. **
  21722. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  21723. ** byte'. If this is successful, a random byte from the 'shared byte
  21724. ** range' is read-locked and the lock on the 'pending byte' released.
  21725. **
  21726. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  21727. ** A RESERVED lock is implemented by grabbing a write-lock on the
  21728. ** 'reserved byte'.
  21729. **
  21730. ** A process may only obtain a PENDING lock after it has obtained a
  21731. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  21732. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  21733. ** obtained, but existing SHARED locks are allowed to persist. A process
  21734. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  21735. ** This property is used by the algorithm for rolling back a journal file
  21736. ** after a crash.
  21737. **
  21738. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  21739. ** implemented by obtaining a write-lock on the entire 'shared byte
  21740. ** range'. Since all other locks require a read-lock on one of the bytes
  21741. ** within this range, this ensures that no other locks are held on the
  21742. ** database.
  21743. **
  21744. ** The reason a single byte cannot be used instead of the 'shared byte
  21745. ** range' is that some versions of windows do not support read-locks. By
  21746. ** locking a random byte from a range, concurrent SHARED locks may exist
  21747. ** even if the locking primitive used is always a write-lock.
  21748. */
  21749. int rc = SQLITE_OK;
  21750. unixFile *pFile = (unixFile*)id;
  21751. struct unixLockInfo *pLock = pFile->pLock;
  21752. struct flock lock;
  21753. int s;
  21754. assert( pFile );
  21755. OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
  21756. locktypeName(locktype), locktypeName(pFile->locktype),
  21757. locktypeName(pLock->locktype), pLock->cnt , getpid());
  21758. /* If there is already a lock of this type or more restrictive on the
  21759. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  21760. ** unixEnterMutex() hasn't been called yet.
  21761. */
  21762. if( pFile->locktype>=locktype ){
  21763. OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
  21764. locktypeName(locktype));
  21765. return SQLITE_OK;
  21766. }
  21767. /* Make sure the locking sequence is correct
  21768. */
  21769. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  21770. assert( locktype!=PENDING_LOCK );
  21771. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  21772. /* This mutex is needed because pFile->pLock is shared across threads
  21773. */
  21774. unixEnterMutex();
  21775. /* Make sure the current thread owns the pFile.
  21776. */
  21777. rc = transferOwnership(pFile);
  21778. if( rc!=SQLITE_OK ){
  21779. unixLeaveMutex();
  21780. return rc;
  21781. }
  21782. pLock = pFile->pLock;
  21783. /* If some thread using this PID has a lock via a different unixFile*
  21784. ** handle that precludes the requested lock, return BUSY.
  21785. */
  21786. if( (pFile->locktype!=pLock->locktype &&
  21787. (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
  21788. ){
  21789. rc = SQLITE_BUSY;
  21790. goto end_lock;
  21791. }
  21792. /* If a SHARED lock is requested, and some thread using this PID already
  21793. ** has a SHARED or RESERVED lock, then increment reference counts and
  21794. ** return SQLITE_OK.
  21795. */
  21796. if( locktype==SHARED_LOCK &&
  21797. (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
  21798. assert( locktype==SHARED_LOCK );
  21799. assert( pFile->locktype==0 );
  21800. assert( pLock->cnt>0 );
  21801. pFile->locktype = SHARED_LOCK;
  21802. pLock->cnt++;
  21803. pFile->pOpen->nLock++;
  21804. goto end_lock;
  21805. }
  21806. lock.l_len = 1L;
  21807. lock.l_whence = SEEK_SET;
  21808. /* A PENDING lock is needed before acquiring a SHARED lock and before
  21809. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  21810. ** be released.
  21811. */
  21812. if( locktype==SHARED_LOCK
  21813. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  21814. ){
  21815. lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
  21816. lock.l_start = PENDING_BYTE;
  21817. s = fcntl(pFile->h, F_SETLK, &lock);
  21818. if( s==(-1) ){
  21819. int tErrno = errno;
  21820. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  21821. if( IS_LOCK_ERROR(rc) ){
  21822. pFile->lastErrno = tErrno;
  21823. }
  21824. goto end_lock;
  21825. }
  21826. }
  21827. /* If control gets to this point, then actually go ahead and make
  21828. ** operating system calls for the specified lock.
  21829. */
  21830. if( locktype==SHARED_LOCK ){
  21831. int tErrno = 0;
  21832. assert( pLock->cnt==0 );
  21833. assert( pLock->locktype==0 );
  21834. /* Now get the read-lock */
  21835. lock.l_start = SHARED_FIRST;
  21836. lock.l_len = SHARED_SIZE;
  21837. if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
  21838. tErrno = errno;
  21839. }
  21840. /* Drop the temporary PENDING lock */
  21841. lock.l_start = PENDING_BYTE;
  21842. lock.l_len = 1L;
  21843. lock.l_type = F_UNLCK;
  21844. if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
  21845. if( s != -1 ){
  21846. /* This could happen with a network mount */
  21847. tErrno = errno;
  21848. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  21849. if( IS_LOCK_ERROR(rc) ){
  21850. pFile->lastErrno = tErrno;
  21851. }
  21852. goto end_lock;
  21853. }
  21854. }
  21855. if( s==(-1) ){
  21856. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  21857. if( IS_LOCK_ERROR(rc) ){
  21858. pFile->lastErrno = tErrno;
  21859. }
  21860. }else{
  21861. pFile->locktype = SHARED_LOCK;
  21862. pFile->pOpen->nLock++;
  21863. pLock->cnt = 1;
  21864. }
  21865. }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
  21866. /* We are trying for an exclusive lock but another thread in this
  21867. ** same process is still holding a shared lock. */
  21868. rc = SQLITE_BUSY;
  21869. }else{
  21870. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  21871. ** assumed that there is a SHARED or greater lock on the file
  21872. ** already.
  21873. */
  21874. assert( 0!=pFile->locktype );
  21875. lock.l_type = F_WRLCK;
  21876. switch( locktype ){
  21877. case RESERVED_LOCK:
  21878. lock.l_start = RESERVED_BYTE;
  21879. break;
  21880. case EXCLUSIVE_LOCK:
  21881. lock.l_start = SHARED_FIRST;
  21882. lock.l_len = SHARED_SIZE;
  21883. break;
  21884. default:
  21885. assert(0);
  21886. }
  21887. s = fcntl(pFile->h, F_SETLK, &lock);
  21888. if( s==(-1) ){
  21889. int tErrno = errno;
  21890. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  21891. if( IS_LOCK_ERROR(rc) ){
  21892. pFile->lastErrno = tErrno;
  21893. }
  21894. }
  21895. }
  21896. #ifndef NDEBUG
  21897. /* Set up the transaction-counter change checking flags when
  21898. ** transitioning from a SHARED to a RESERVED lock. The change
  21899. ** from SHARED to RESERVED marks the beginning of a normal
  21900. ** write operation (not a hot journal rollback).
  21901. */
  21902. if( rc==SQLITE_OK
  21903. && pFile->locktype<=SHARED_LOCK
  21904. && locktype==RESERVED_LOCK
  21905. ){
  21906. pFile->transCntrChng = 0;
  21907. pFile->dbUpdate = 0;
  21908. pFile->inNormalWrite = 1;
  21909. }
  21910. #endif
  21911. if( rc==SQLITE_OK ){
  21912. pFile->locktype = locktype;
  21913. pLock->locktype = locktype;
  21914. }else if( locktype==EXCLUSIVE_LOCK ){
  21915. pFile->locktype = PENDING_LOCK;
  21916. pLock->locktype = PENDING_LOCK;
  21917. }
  21918. end_lock:
  21919. unixLeaveMutex();
  21920. OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
  21921. rc==SQLITE_OK ? "ok" : "failed");
  21922. return rc;
  21923. }
  21924. /*
  21925. ** Lower the locking level on file descriptor pFile to locktype. locktype
  21926. ** must be either NO_LOCK or SHARED_LOCK.
  21927. **
  21928. ** If the locking level of the file descriptor is already at or below
  21929. ** the requested locking level, this routine is a no-op.
  21930. */
  21931. static int unixUnlock(sqlite3_file *id, int locktype){
  21932. struct unixLockInfo *pLock;
  21933. struct flock lock;
  21934. int rc = SQLITE_OK;
  21935. unixFile *pFile = (unixFile*)id;
  21936. int h;
  21937. assert( pFile );
  21938. OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
  21939. pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
  21940. assert( locktype<=SHARED_LOCK );
  21941. if( pFile->locktype<=locktype ){
  21942. return SQLITE_OK;
  21943. }
  21944. if( CHECK_THREADID(pFile) ){
  21945. return SQLITE_MISUSE;
  21946. }
  21947. unixEnterMutex();
  21948. h = pFile->h;
  21949. pLock = pFile->pLock;
  21950. assert( pLock->cnt!=0 );
  21951. if( pFile->locktype>SHARED_LOCK ){
  21952. assert( pLock->locktype==pFile->locktype );
  21953. SimulateIOErrorBenign(1);
  21954. SimulateIOError( h=(-1) )
  21955. SimulateIOErrorBenign(0);
  21956. #ifndef NDEBUG
  21957. /* When reducing a lock such that other processes can start
  21958. ** reading the database file again, make sure that the
  21959. ** transaction counter was updated if any part of the database
  21960. ** file changed. If the transaction counter is not updated,
  21961. ** other connections to the same file might not realize that
  21962. ** the file has changed and hence might not know to flush their
  21963. ** cache. The use of a stale cache can lead to database corruption.
  21964. */
  21965. assert( pFile->inNormalWrite==0
  21966. || pFile->dbUpdate==0
  21967. || pFile->transCntrChng==1 );
  21968. pFile->inNormalWrite = 0;
  21969. #endif
  21970. if( locktype==SHARED_LOCK ){
  21971. lock.l_type = F_RDLCK;
  21972. lock.l_whence = SEEK_SET;
  21973. lock.l_start = SHARED_FIRST;
  21974. lock.l_len = SHARED_SIZE;
  21975. if( fcntl(h, F_SETLK, &lock)==(-1) ){
  21976. int tErrno = errno;
  21977. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  21978. if( IS_LOCK_ERROR(rc) ){
  21979. pFile->lastErrno = tErrno;
  21980. }
  21981. goto end_unlock;
  21982. }
  21983. }
  21984. lock.l_type = F_UNLCK;
  21985. lock.l_whence = SEEK_SET;
  21986. lock.l_start = PENDING_BYTE;
  21987. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  21988. if( fcntl(h, F_SETLK, &lock)!=(-1) ){
  21989. pLock->locktype = SHARED_LOCK;
  21990. }else{
  21991. int tErrno = errno;
  21992. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  21993. if( IS_LOCK_ERROR(rc) ){
  21994. pFile->lastErrno = tErrno;
  21995. }
  21996. goto end_unlock;
  21997. }
  21998. }
  21999. if( locktype==NO_LOCK ){
  22000. struct unixOpenCnt *pOpen;
  22001. /* Decrement the shared lock counter. Release the lock using an
  22002. ** OS call only when all threads in this same process have released
  22003. ** the lock.
  22004. */
  22005. pLock->cnt--;
  22006. if( pLock->cnt==0 ){
  22007. lock.l_type = F_UNLCK;
  22008. lock.l_whence = SEEK_SET;
  22009. lock.l_start = lock.l_len = 0L;
  22010. SimulateIOErrorBenign(1);
  22011. SimulateIOError( h=(-1) )
  22012. SimulateIOErrorBenign(0);
  22013. if( fcntl(h, F_SETLK, &lock)!=(-1) ){
  22014. pLock->locktype = NO_LOCK;
  22015. }else{
  22016. int tErrno = errno;
  22017. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  22018. if( IS_LOCK_ERROR(rc) ){
  22019. pFile->lastErrno = tErrno;
  22020. }
  22021. pLock->cnt = 1;
  22022. goto end_unlock;
  22023. }
  22024. }
  22025. /* Decrement the count of locks against this same file. When the
  22026. ** count reaches zero, close any other file descriptors whose close
  22027. ** was deferred because of outstanding locks.
  22028. */
  22029. if( rc==SQLITE_OK ){
  22030. pOpen = pFile->pOpen;
  22031. pOpen->nLock--;
  22032. assert( pOpen->nLock>=0 );
  22033. if( pOpen->nLock==0 && pOpen->nPending>0 ){
  22034. int i;
  22035. for(i=0; i<pOpen->nPending; i++){
  22036. /* close pending fds, but if closing fails don't free the array
  22037. ** assign -1 to the successfully closed descriptors and record the
  22038. ** error. The next attempt to unlock will try again. */
  22039. if( pOpen->aPending[i] < 0 ) continue;
  22040. if( close(pOpen->aPending[i]) ){
  22041. pFile->lastErrno = errno;
  22042. rc = SQLITE_IOERR_CLOSE;
  22043. }else{
  22044. pOpen->aPending[i] = -1;
  22045. }
  22046. }
  22047. if( rc==SQLITE_OK ){
  22048. sqlite3_free(pOpen->aPending);
  22049. pOpen->nPending = 0;
  22050. pOpen->aPending = 0;
  22051. }
  22052. }
  22053. }
  22054. }
  22055. end_unlock:
  22056. unixLeaveMutex();
  22057. if( rc==SQLITE_OK ) pFile->locktype = locktype;
  22058. return rc;
  22059. }
  22060. /*
  22061. ** This function performs the parts of the "close file" operation
  22062. ** common to all locking schemes. It closes the directory and file
  22063. ** handles, if they are valid, and sets all fields of the unixFile
  22064. ** structure to 0.
  22065. **
  22066. ** It is *not* necessary to hold the mutex when this routine is called,
  22067. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  22068. ** vxworksReleaseFileId() routine.
  22069. */
  22070. static int closeUnixFile(sqlite3_file *id){
  22071. unixFile *pFile = (unixFile*)id;
  22072. if( pFile ){
  22073. if( pFile->dirfd>=0 ){
  22074. int err = close(pFile->dirfd);
  22075. if( err ){
  22076. pFile->lastErrno = errno;
  22077. return SQLITE_IOERR_DIR_CLOSE;
  22078. }else{
  22079. pFile->dirfd=-1;
  22080. }
  22081. }
  22082. if( pFile->h>=0 ){
  22083. int err = close(pFile->h);
  22084. if( err ){
  22085. pFile->lastErrno = errno;
  22086. return SQLITE_IOERR_CLOSE;
  22087. }
  22088. }
  22089. #if OS_VXWORKS
  22090. if( pFile->pId ){
  22091. if( pFile->isDelete ){
  22092. unlink(pFile->pId->zCanonicalName);
  22093. }
  22094. vxworksReleaseFileId(pFile->pId);
  22095. pFile->pId = 0;
  22096. }
  22097. #endif
  22098. OSTRACE2("CLOSE %-3d\n", pFile->h);
  22099. OpenCounter(-1);
  22100. memset(pFile, 0, sizeof(unixFile));
  22101. }
  22102. return SQLITE_OK;
  22103. }
  22104. /*
  22105. ** Close a file.
  22106. */
  22107. static int unixClose(sqlite3_file *id){
  22108. int rc = SQLITE_OK;
  22109. if( id ){
  22110. unixFile *pFile = (unixFile *)id;
  22111. unixUnlock(id, NO_LOCK);
  22112. unixEnterMutex();
  22113. if( pFile->pOpen && pFile->pOpen->nLock ){
  22114. /* If there are outstanding locks, do not actually close the file just
  22115. ** yet because that would clear those locks. Instead, add the file
  22116. ** descriptor to pOpen->aPending. It will be automatically closed when
  22117. ** the last lock is cleared.
  22118. */
  22119. int *aNew;
  22120. struct unixOpenCnt *pOpen = pFile->pOpen;
  22121. aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
  22122. if( aNew==0 ){
  22123. /* If a malloc fails, just leak the file descriptor */
  22124. }else{
  22125. pOpen->aPending = aNew;
  22126. pOpen->aPending[pOpen->nPending] = pFile->h;
  22127. pOpen->nPending++;
  22128. pFile->h = -1;
  22129. }
  22130. }
  22131. releaseLockInfo(pFile->pLock);
  22132. releaseOpenCnt(pFile->pOpen);
  22133. rc = closeUnixFile(id);
  22134. unixLeaveMutex();
  22135. }
  22136. return rc;
  22137. }
  22138. /************** End of the posix advisory lock implementation *****************
  22139. ******************************************************************************/
  22140. /******************************************************************************
  22141. ****************************** No-op Locking **********************************
  22142. **
  22143. ** Of the various locking implementations available, this is by far the
  22144. ** simplest: locking is ignored. No attempt is made to lock the database
  22145. ** file for reading or writing.
  22146. **
  22147. ** This locking mode is appropriate for use on read-only databases
  22148. ** (ex: databases that are burned into CD-ROM, for example.) It can
  22149. ** also be used if the application employs some external mechanism to
  22150. ** prevent simultaneous access of the same database by two or more
  22151. ** database connections. But there is a serious risk of database
  22152. ** corruption if this locking mode is used in situations where multiple
  22153. ** database connections are accessing the same database file at the same
  22154. ** time and one or more of those connections are writing.
  22155. */
  22156. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  22157. UNUSED_PARAMETER(NotUsed);
  22158. *pResOut = 0;
  22159. return SQLITE_OK;
  22160. }
  22161. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  22162. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  22163. return SQLITE_OK;
  22164. }
  22165. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  22166. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  22167. return SQLITE_OK;
  22168. }
  22169. /*
  22170. ** Close the file.
  22171. */
  22172. static int nolockClose(sqlite3_file *id) {
  22173. return closeUnixFile(id);
  22174. }
  22175. /******************* End of the no-op lock implementation *********************
  22176. ******************************************************************************/
  22177. /******************************************************************************
  22178. ************************* Begin dot-file Locking ******************************
  22179. **
  22180. ** The dotfile locking implementation uses the existing of separate lock
  22181. ** files in order to control access to the database. This works on just
  22182. ** about every filesystem imaginable. But there are serious downsides:
  22183. **
  22184. ** (1) There is zero concurrency. A single reader blocks all other
  22185. ** connections from reading or writing the database.
  22186. **
  22187. ** (2) An application crash or power loss can leave stale lock files
  22188. ** sitting around that need to be cleared manually.
  22189. **
  22190. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  22191. ** other locking strategy is available.
  22192. **
  22193. ** Dotfile locking works by creating a file in the same directory as the
  22194. ** database and with the same name but with a ".lock" extension added.
  22195. ** The existance of a lock file implies an EXCLUSIVE lock. All other lock
  22196. ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  22197. */
  22198. /*
  22199. ** The file suffix added to the data base filename in order to create the
  22200. ** lock file.
  22201. */
  22202. #define DOTLOCK_SUFFIX ".lock"
  22203. /*
  22204. ** This routine checks if there is a RESERVED lock held on the specified
  22205. ** file by this or any other process. If such a lock is held, set *pResOut
  22206. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  22207. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  22208. **
  22209. ** In dotfile locking, either a lock exists or it does not. So in this
  22210. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  22211. ** is held on the file and false if the file is unlocked.
  22212. */
  22213. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  22214. int rc = SQLITE_OK;
  22215. int reserved = 0;
  22216. unixFile *pFile = (unixFile*)id;
  22217. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  22218. assert( pFile );
  22219. /* Check if a thread in this process holds such a lock */
  22220. if( pFile->locktype>SHARED_LOCK ){
  22221. /* Either this connection or some other connection in the same process
  22222. ** holds a lock on the file. No need to check further. */
  22223. reserved = 1;
  22224. }else{
  22225. /* The lock is held if and only if the lockfile exists */
  22226. const char *zLockFile = (const char*)pFile->lockingContext;
  22227. reserved = access(zLockFile, 0)==0;
  22228. }
  22229. OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  22230. *pResOut = reserved;
  22231. return rc;
  22232. }
  22233. /*
  22234. ** Lock the file with the lock specified by parameter locktype - one
  22235. ** of the following:
  22236. **
  22237. ** (1) SHARED_LOCK
  22238. ** (2) RESERVED_LOCK
  22239. ** (3) PENDING_LOCK
  22240. ** (4) EXCLUSIVE_LOCK
  22241. **
  22242. ** Sometimes when requesting one lock state, additional lock states
  22243. ** are inserted in between. The locking might fail on one of the later
  22244. ** transitions leaving the lock state different from what it started but
  22245. ** still short of its goal. The following chart shows the allowed
  22246. ** transitions and the inserted intermediate states:
  22247. **
  22248. ** UNLOCKED -> SHARED
  22249. ** SHARED -> RESERVED
  22250. ** SHARED -> (PENDING) -> EXCLUSIVE
  22251. ** RESERVED -> (PENDING) -> EXCLUSIVE
  22252. ** PENDING -> EXCLUSIVE
  22253. **
  22254. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  22255. ** routine to lower a locking level.
  22256. **
  22257. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  22258. ** But we track the other locking levels internally.
  22259. */
  22260. static int dotlockLock(sqlite3_file *id, int locktype) {
  22261. unixFile *pFile = (unixFile*)id;
  22262. int fd;
  22263. char *zLockFile = (char *)pFile->lockingContext;
  22264. int rc = SQLITE_OK;
  22265. /* If we have any lock, then the lock file already exists. All we have
  22266. ** to do is adjust our internal record of the lock level.
  22267. */
  22268. if( pFile->locktype > NO_LOCK ){
  22269. pFile->locktype = locktype;
  22270. #if !OS_VXWORKS
  22271. /* Always update the timestamp on the old file */
  22272. utimes(zLockFile, NULL);
  22273. #endif
  22274. return SQLITE_OK;
  22275. }
  22276. /* grab an exclusive lock */
  22277. fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
  22278. if( fd<0 ){
  22279. /* failed to open/create the file, someone else may have stolen the lock */
  22280. int tErrno = errno;
  22281. if( EEXIST == tErrno ){
  22282. rc = SQLITE_BUSY;
  22283. } else {
  22284. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  22285. if( IS_LOCK_ERROR(rc) ){
  22286. pFile->lastErrno = tErrno;
  22287. }
  22288. }
  22289. return rc;
  22290. }
  22291. if( close(fd) ){
  22292. pFile->lastErrno = errno;
  22293. rc = SQLITE_IOERR_CLOSE;
  22294. }
  22295. /* got it, set the type and return ok */
  22296. pFile->locktype = locktype;
  22297. return rc;
  22298. }
  22299. /*
  22300. ** Lower the locking level on file descriptor pFile to locktype. locktype
  22301. ** must be either NO_LOCK or SHARED_LOCK.
  22302. **
  22303. ** If the locking level of the file descriptor is already at or below
  22304. ** the requested locking level, this routine is a no-op.
  22305. **
  22306. ** When the locking level reaches NO_LOCK, delete the lock file.
  22307. */
  22308. static int dotlockUnlock(sqlite3_file *id, int locktype) {
  22309. unixFile *pFile = (unixFile*)id;
  22310. char *zLockFile = (char *)pFile->lockingContext;
  22311. assert( pFile );
  22312. OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
  22313. pFile->locktype, getpid());
  22314. assert( locktype<=SHARED_LOCK );
  22315. /* no-op if possible */
  22316. if( pFile->locktype==locktype ){
  22317. return SQLITE_OK;
  22318. }
  22319. /* To downgrade to shared, simply update our internal notion of the
  22320. ** lock state. No need to mess with the file on disk.
  22321. */
  22322. if( locktype==SHARED_LOCK ){
  22323. pFile->locktype = SHARED_LOCK;
  22324. return SQLITE_OK;
  22325. }
  22326. /* To fully unlock the database, delete the lock file */
  22327. assert( locktype==NO_LOCK );
  22328. if( unlink(zLockFile) ){
  22329. int rc, tErrno = errno;
  22330. if( ENOENT != tErrno ){
  22331. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  22332. }
  22333. if( IS_LOCK_ERROR(rc) ){
  22334. pFile->lastErrno = tErrno;
  22335. }
  22336. return rc;
  22337. }
  22338. pFile->locktype = NO_LOCK;
  22339. return SQLITE_OK;
  22340. }
  22341. /*
  22342. ** Close a file. Make sure the lock has been released before closing.
  22343. */
  22344. static int dotlockClose(sqlite3_file *id) {
  22345. int rc;
  22346. if( id ){
  22347. unixFile *pFile = (unixFile*)id;
  22348. dotlockUnlock(id, NO_LOCK);
  22349. sqlite3_free(pFile->lockingContext);
  22350. }
  22351. rc = closeUnixFile(id);
  22352. return rc;
  22353. }
  22354. /****************** End of the dot-file lock implementation *******************
  22355. ******************************************************************************/
  22356. /******************************************************************************
  22357. ************************** Begin flock Locking ********************************
  22358. **
  22359. ** Use the flock() system call to do file locking.
  22360. **
  22361. ** flock() locking is like dot-file locking in that the various
  22362. ** fine-grain locking levels supported by SQLite are collapsed into
  22363. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  22364. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  22365. ** still works when you do this, but concurrency is reduced since
  22366. ** only a single process can be reading the database at a time.
  22367. **
  22368. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  22369. ** compiling for VXWORKS.
  22370. */
  22371. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  22372. /*
  22373. ** This routine checks if there is a RESERVED lock held on the specified
  22374. ** file by this or any other process. If such a lock is held, set *pResOut
  22375. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  22376. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  22377. */
  22378. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  22379. int rc = SQLITE_OK;
  22380. int reserved = 0;
  22381. unixFile *pFile = (unixFile*)id;
  22382. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  22383. assert( pFile );
  22384. /* Check if a thread in this process holds such a lock */
  22385. if( pFile->locktype>SHARED_LOCK ){
  22386. reserved = 1;
  22387. }
  22388. /* Otherwise see if some other process holds it. */
  22389. if( !reserved ){
  22390. /* attempt to get the lock */
  22391. int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
  22392. if( !lrc ){
  22393. /* got the lock, unlock it */
  22394. lrc = flock(pFile->h, LOCK_UN);
  22395. if ( lrc ) {
  22396. int tErrno = errno;
  22397. /* unlock failed with an error */
  22398. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  22399. if( IS_LOCK_ERROR(lrc) ){
  22400. pFile->lastErrno = tErrno;
  22401. rc = lrc;
  22402. }
  22403. }
  22404. } else {
  22405. int tErrno = errno;
  22406. reserved = 1;
  22407. /* someone else might have it reserved */
  22408. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  22409. if( IS_LOCK_ERROR(lrc) ){
  22410. pFile->lastErrno = tErrno;
  22411. rc = lrc;
  22412. }
  22413. }
  22414. }
  22415. OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  22416. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  22417. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  22418. rc = SQLITE_OK;
  22419. reserved=1;
  22420. }
  22421. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  22422. *pResOut = reserved;
  22423. return rc;
  22424. }
  22425. /*
  22426. ** Lock the file with the lock specified by parameter locktype - one
  22427. ** of the following:
  22428. **
  22429. ** (1) SHARED_LOCK
  22430. ** (2) RESERVED_LOCK
  22431. ** (3) PENDING_LOCK
  22432. ** (4) EXCLUSIVE_LOCK
  22433. **
  22434. ** Sometimes when requesting one lock state, additional lock states
  22435. ** are inserted in between. The locking might fail on one of the later
  22436. ** transitions leaving the lock state different from what it started but
  22437. ** still short of its goal. The following chart shows the allowed
  22438. ** transitions and the inserted intermediate states:
  22439. **
  22440. ** UNLOCKED -> SHARED
  22441. ** SHARED -> RESERVED
  22442. ** SHARED -> (PENDING) -> EXCLUSIVE
  22443. ** RESERVED -> (PENDING) -> EXCLUSIVE
  22444. ** PENDING -> EXCLUSIVE
  22445. **
  22446. ** flock() only really support EXCLUSIVE locks. We track intermediate
  22447. ** lock states in the sqlite3_file structure, but all locks SHARED or
  22448. ** above are really EXCLUSIVE locks and exclude all other processes from
  22449. ** access the file.
  22450. **
  22451. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  22452. ** routine to lower a locking level.
  22453. */
  22454. static int flockLock(sqlite3_file *id, int locktype) {
  22455. int rc = SQLITE_OK;
  22456. unixFile *pFile = (unixFile*)id;
  22457. assert( pFile );
  22458. /* if we already have a lock, it is exclusive.
  22459. ** Just adjust level and punt on outta here. */
  22460. if (pFile->locktype > NO_LOCK) {
  22461. pFile->locktype = locktype;
  22462. return SQLITE_OK;
  22463. }
  22464. /* grab an exclusive lock */
  22465. if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
  22466. int tErrno = errno;
  22467. /* didn't get, must be busy */
  22468. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  22469. if( IS_LOCK_ERROR(rc) ){
  22470. pFile->lastErrno = tErrno;
  22471. }
  22472. } else {
  22473. /* got it, set the type and return ok */
  22474. pFile->locktype = locktype;
  22475. }
  22476. OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
  22477. rc==SQLITE_OK ? "ok" : "failed");
  22478. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  22479. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  22480. rc = SQLITE_BUSY;
  22481. }
  22482. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  22483. return rc;
  22484. }
  22485. /*
  22486. ** Lower the locking level on file descriptor pFile to locktype. locktype
  22487. ** must be either NO_LOCK or SHARED_LOCK.
  22488. **
  22489. ** If the locking level of the file descriptor is already at or below
  22490. ** the requested locking level, this routine is a no-op.
  22491. */
  22492. static int flockUnlock(sqlite3_file *id, int locktype) {
  22493. unixFile *pFile = (unixFile*)id;
  22494. assert( pFile );
  22495. OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
  22496. pFile->locktype, getpid());
  22497. assert( locktype<=SHARED_LOCK );
  22498. /* no-op if possible */
  22499. if( pFile->locktype==locktype ){
  22500. return SQLITE_OK;
  22501. }
  22502. /* shared can just be set because we always have an exclusive */
  22503. if (locktype==SHARED_LOCK) {
  22504. pFile->locktype = locktype;
  22505. return SQLITE_OK;
  22506. }
  22507. /* no, really, unlock. */
  22508. int rc = flock(pFile->h, LOCK_UN);
  22509. if (rc) {
  22510. int r, tErrno = errno;
  22511. r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  22512. if( IS_LOCK_ERROR(r) ){
  22513. pFile->lastErrno = tErrno;
  22514. }
  22515. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  22516. if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
  22517. r = SQLITE_BUSY;
  22518. }
  22519. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  22520. return r;
  22521. } else {
  22522. pFile->locktype = NO_LOCK;
  22523. return SQLITE_OK;
  22524. }
  22525. }
  22526. /*
  22527. ** Close a file.
  22528. */
  22529. static int flockClose(sqlite3_file *id) {
  22530. if( id ){
  22531. flockUnlock(id, NO_LOCK);
  22532. }
  22533. return closeUnixFile(id);
  22534. }
  22535. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  22536. /******************* End of the flock lock implementation *********************
  22537. ******************************************************************************/
  22538. /******************************************************************************
  22539. ************************ Begin Named Semaphore Locking ************************
  22540. **
  22541. ** Named semaphore locking is only supported on VxWorks.
  22542. **
  22543. ** Semaphore locking is like dot-lock and flock in that it really only
  22544. ** supports EXCLUSIVE locking. Only a single process can read or write
  22545. ** the database file at a time. This reduces potential concurrency, but
  22546. ** makes the lock implementation much easier.
  22547. */
  22548. #if OS_VXWORKS
  22549. /*
  22550. ** This routine checks if there is a RESERVED lock held on the specified
  22551. ** file by this or any other process. If such a lock is held, set *pResOut
  22552. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  22553. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  22554. */
  22555. static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  22556. int rc = SQLITE_OK;
  22557. int reserved = 0;
  22558. unixFile *pFile = (unixFile*)id;
  22559. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  22560. assert( pFile );
  22561. /* Check if a thread in this process holds such a lock */
  22562. if( pFile->locktype>SHARED_LOCK ){
  22563. reserved = 1;
  22564. }
  22565. /* Otherwise see if some other process holds it. */
  22566. if( !reserved ){
  22567. sem_t *pSem = pFile->pOpen->pSem;
  22568. struct stat statBuf;
  22569. if( sem_trywait(pSem)==-1 ){
  22570. int tErrno = errno;
  22571. if( EAGAIN != tErrno ){
  22572. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  22573. pFile->lastErrno = tErrno;
  22574. } else {
  22575. /* someone else has the lock when we are in NO_LOCK */
  22576. reserved = (pFile->locktype < SHARED_LOCK);
  22577. }
  22578. }else{
  22579. /* we could have it if we want it */
  22580. sem_post(pSem);
  22581. }
  22582. }
  22583. OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  22584. *pResOut = reserved;
  22585. return rc;
  22586. }
  22587. /*
  22588. ** Lock the file with the lock specified by parameter locktype - one
  22589. ** of the following:
  22590. **
  22591. ** (1) SHARED_LOCK
  22592. ** (2) RESERVED_LOCK
  22593. ** (3) PENDING_LOCK
  22594. ** (4) EXCLUSIVE_LOCK
  22595. **
  22596. ** Sometimes when requesting one lock state, additional lock states
  22597. ** are inserted in between. The locking might fail on one of the later
  22598. ** transitions leaving the lock state different from what it started but
  22599. ** still short of its goal. The following chart shows the allowed
  22600. ** transitions and the inserted intermediate states:
  22601. **
  22602. ** UNLOCKED -> SHARED
  22603. ** SHARED -> RESERVED
  22604. ** SHARED -> (PENDING) -> EXCLUSIVE
  22605. ** RESERVED -> (PENDING) -> EXCLUSIVE
  22606. ** PENDING -> EXCLUSIVE
  22607. **
  22608. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  22609. ** lock states in the sqlite3_file structure, but all locks SHARED or
  22610. ** above are really EXCLUSIVE locks and exclude all other processes from
  22611. ** access the file.
  22612. **
  22613. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  22614. ** routine to lower a locking level.
  22615. */
  22616. static int semLock(sqlite3_file *id, int locktype) {
  22617. unixFile *pFile = (unixFile*)id;
  22618. int fd;
  22619. sem_t *pSem = pFile->pOpen->pSem;
  22620. int rc = SQLITE_OK;
  22621. /* if we already have a lock, it is exclusive.
  22622. ** Just adjust level and punt on outta here. */
  22623. if (pFile->locktype > NO_LOCK) {
  22624. pFile->locktype = locktype;
  22625. rc = SQLITE_OK;
  22626. goto sem_end_lock;
  22627. }
  22628. /* lock semaphore now but bail out when already locked. */
  22629. if( sem_trywait(pSem)==-1 ){
  22630. rc = SQLITE_BUSY;
  22631. goto sem_end_lock;
  22632. }
  22633. /* got it, set the type and return ok */
  22634. pFile->locktype = locktype;
  22635. sem_end_lock:
  22636. return rc;
  22637. }
  22638. /*
  22639. ** Lower the locking level on file descriptor pFile to locktype. locktype
  22640. ** must be either NO_LOCK or SHARED_LOCK.
  22641. **
  22642. ** If the locking level of the file descriptor is already at or below
  22643. ** the requested locking level, this routine is a no-op.
  22644. */
  22645. static int semUnlock(sqlite3_file *id, int locktype) {
  22646. unixFile *pFile = (unixFile*)id;
  22647. sem_t *pSem = pFile->pOpen->pSem;
  22648. assert( pFile );
  22649. assert( pSem );
  22650. OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
  22651. pFile->locktype, getpid());
  22652. assert( locktype<=SHARED_LOCK );
  22653. /* no-op if possible */
  22654. if( pFile->locktype==locktype ){
  22655. return SQLITE_OK;
  22656. }
  22657. /* shared can just be set because we always have an exclusive */
  22658. if (locktype==SHARED_LOCK) {
  22659. pFile->locktype = locktype;
  22660. return SQLITE_OK;
  22661. }
  22662. /* no, really unlock. */
  22663. if ( sem_post(pSem)==-1 ) {
  22664. int rc, tErrno = errno;
  22665. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  22666. if( IS_LOCK_ERROR(rc) ){
  22667. pFile->lastErrno = tErrno;
  22668. }
  22669. return rc;
  22670. }
  22671. pFile->locktype = NO_LOCK;
  22672. return SQLITE_OK;
  22673. }
  22674. /*
  22675. ** Close a file.
  22676. */
  22677. static int semClose(sqlite3_file *id) {
  22678. if( id ){
  22679. unixFile *pFile = (unixFile*)id;
  22680. semUnlock(id, NO_LOCK);
  22681. assert( pFile );
  22682. unixEnterMutex();
  22683. releaseLockInfo(pFile->pLock);
  22684. releaseOpenCnt(pFile->pOpen);
  22685. closeUnixFile(id);
  22686. unixLeaveMutex();
  22687. }
  22688. return SQLITE_OK;
  22689. }
  22690. #endif /* OS_VXWORKS */
  22691. /*
  22692. ** Named semaphore locking is only available on VxWorks.
  22693. **
  22694. *************** End of the named semaphore lock implementation ****************
  22695. ******************************************************************************/
  22696. /******************************************************************************
  22697. *************************** Begin AFP Locking *********************************
  22698. **
  22699. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  22700. ** on Apple Macintosh computers - both OS9 and OSX.
  22701. **
  22702. ** Third-party implementations of AFP are available. But this code here
  22703. ** only works on OSX.
  22704. */
  22705. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  22706. /*
  22707. ** The afpLockingContext structure contains all afp lock specific state
  22708. */
  22709. typedef struct afpLockingContext afpLockingContext;
  22710. struct afpLockingContext {
  22711. unsigned long long sharedByte;
  22712. const char *dbPath; /* Name of the open file */
  22713. };
  22714. struct ByteRangeLockPB2
  22715. {
  22716. unsigned long long offset; /* offset to first byte to lock */
  22717. unsigned long long length; /* nbr of bytes to lock */
  22718. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  22719. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  22720. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  22721. int fd; /* file desc to assoc this lock with */
  22722. };
  22723. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  22724. /*
  22725. ** This is a utility for setting or clearing a bit-range lock on an
  22726. ** AFP filesystem.
  22727. **
  22728. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  22729. */
  22730. static int afpSetLock(
  22731. const char *path, /* Name of the file to be locked or unlocked */
  22732. unixFile *pFile, /* Open file descriptor on path */
  22733. unsigned long long offset, /* First byte to be locked */
  22734. unsigned long long length, /* Number of bytes to lock */
  22735. int setLockFlag /* True to set lock. False to clear lock */
  22736. ){
  22737. struct ByteRangeLockPB2 pb;
  22738. int err;
  22739. pb.unLockFlag = setLockFlag ? 0 : 1;
  22740. pb.startEndFlag = 0;
  22741. pb.offset = offset;
  22742. pb.length = length;
  22743. pb.fd = pFile->h;
  22744. OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  22745. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  22746. offset, length);
  22747. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  22748. if ( err==-1 ) {
  22749. int rc;
  22750. int tErrno = errno;
  22751. OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  22752. path, tErrno, strerror(tErrno));
  22753. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  22754. rc = SQLITE_BUSY;
  22755. #else
  22756. rc = sqliteErrorFromPosixError(tErrno,
  22757. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  22758. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  22759. if( IS_LOCK_ERROR(rc) ){
  22760. pFile->lastErrno = tErrno;
  22761. }
  22762. return rc;
  22763. } else {
  22764. return SQLITE_OK;
  22765. }
  22766. }
  22767. /*
  22768. ** This routine checks if there is a RESERVED lock held on the specified
  22769. ** file by this or any other process. If such a lock is held, set *pResOut
  22770. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  22771. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  22772. */
  22773. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  22774. int rc = SQLITE_OK;
  22775. int reserved = 0;
  22776. unixFile *pFile = (unixFile*)id;
  22777. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  22778. assert( pFile );
  22779. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  22780. /* Check if a thread in this process holds such a lock */
  22781. if( pFile->locktype>SHARED_LOCK ){
  22782. reserved = 1;
  22783. }
  22784. /* Otherwise see if some other process holds it.
  22785. */
  22786. if( !reserved ){
  22787. /* lock the RESERVED byte */
  22788. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  22789. if( SQLITE_OK==lrc ){
  22790. /* if we succeeded in taking the reserved lock, unlock it to restore
  22791. ** the original state */
  22792. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  22793. } else {
  22794. /* if we failed to get the lock then someone else must have it */
  22795. reserved = 1;
  22796. }
  22797. if( IS_LOCK_ERROR(lrc) ){
  22798. rc=lrc;
  22799. }
  22800. }
  22801. OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  22802. *pResOut = reserved;
  22803. return rc;
  22804. }
  22805. /*
  22806. ** Lock the file with the lock specified by parameter locktype - one
  22807. ** of the following:
  22808. **
  22809. ** (1) SHARED_LOCK
  22810. ** (2) RESERVED_LOCK
  22811. ** (3) PENDING_LOCK
  22812. ** (4) EXCLUSIVE_LOCK
  22813. **
  22814. ** Sometimes when requesting one lock state, additional lock states
  22815. ** are inserted in between. The locking might fail on one of the later
  22816. ** transitions leaving the lock state different from what it started but
  22817. ** still short of its goal. The following chart shows the allowed
  22818. ** transitions and the inserted intermediate states:
  22819. **
  22820. ** UNLOCKED -> SHARED
  22821. ** SHARED -> RESERVED
  22822. ** SHARED -> (PENDING) -> EXCLUSIVE
  22823. ** RESERVED -> (PENDING) -> EXCLUSIVE
  22824. ** PENDING -> EXCLUSIVE
  22825. **
  22826. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  22827. ** routine to lower a locking level.
  22828. */
  22829. static int afpLock(sqlite3_file *id, int locktype){
  22830. int rc = SQLITE_OK;
  22831. unixFile *pFile = (unixFile*)id;
  22832. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  22833. assert( pFile );
  22834. OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
  22835. locktypeName(locktype), locktypeName(pFile->locktype), getpid());
  22836. /* If there is already a lock of this type or more restrictive on the
  22837. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  22838. ** unixEnterMutex() hasn't been called yet.
  22839. */
  22840. if( pFile->locktype>=locktype ){
  22841. OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
  22842. locktypeName(locktype));
  22843. return SQLITE_OK;
  22844. }
  22845. /* Make sure the locking sequence is correct
  22846. */
  22847. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  22848. assert( locktype!=PENDING_LOCK );
  22849. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  22850. /* This mutex is needed because pFile->pLock is shared across threads
  22851. */
  22852. unixEnterMutex();
  22853. /* Make sure the current thread owns the pFile.
  22854. */
  22855. rc = transferOwnership(pFile);
  22856. if( rc!=SQLITE_OK ){
  22857. unixLeaveMutex();
  22858. return rc;
  22859. }
  22860. /* A PENDING lock is needed before acquiring a SHARED lock and before
  22861. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  22862. ** be released.
  22863. */
  22864. if( locktype==SHARED_LOCK
  22865. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  22866. ){
  22867. int failed;
  22868. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  22869. if (failed) {
  22870. rc = failed;
  22871. goto afp_end_lock;
  22872. }
  22873. }
  22874. /* If control gets to this point, then actually go ahead and make
  22875. ** operating system calls for the specified lock.
  22876. */
  22877. if( locktype==SHARED_LOCK ){
  22878. int lk, lrc1, lrc2, lrc1Errno;
  22879. /* Now get the read-lock SHARED_LOCK */
  22880. /* note that the quality of the randomness doesn't matter that much */
  22881. lk = random();
  22882. context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
  22883. lrc1 = afpSetLock(context->dbPath, pFile,
  22884. SHARED_FIRST+context->sharedByte, 1, 1);
  22885. if( IS_LOCK_ERROR(lrc1) ){
  22886. lrc1Errno = pFile->lastErrno;
  22887. }
  22888. /* Drop the temporary PENDING lock */
  22889. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  22890. if( IS_LOCK_ERROR(lrc1) ) {
  22891. pFile->lastErrno = lrc1Errno;
  22892. rc = lrc1;
  22893. goto afp_end_lock;
  22894. } else if( IS_LOCK_ERROR(lrc2) ){
  22895. rc = lrc2;
  22896. goto afp_end_lock;
  22897. } else if( lrc1 != SQLITE_OK ) {
  22898. rc = lrc1;
  22899. } else {
  22900. pFile->locktype = SHARED_LOCK;
  22901. pFile->pOpen->nLock++;
  22902. }
  22903. }else{
  22904. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  22905. ** assumed that there is a SHARED or greater lock on the file
  22906. ** already.
  22907. */
  22908. int failed = 0;
  22909. assert( 0!=pFile->locktype );
  22910. if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
  22911. /* Acquire a RESERVED lock */
  22912. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  22913. }
  22914. if (!failed && locktype == EXCLUSIVE_LOCK) {
  22915. /* Acquire an EXCLUSIVE lock */
  22916. /* Remove the shared lock before trying the range. we'll need to
  22917. ** reestablish the shared lock if we can't get the afpUnlock
  22918. */
  22919. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  22920. context->sharedByte, 1, 0)) ){
  22921. int failed2 = SQLITE_OK;
  22922. /* now attemmpt to get the exclusive lock range */
  22923. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  22924. SHARED_SIZE, 1);
  22925. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  22926. SHARED_FIRST + context->sharedByte, 1, 1)) ){
  22927. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  22928. ** a critical I/O error
  22929. */
  22930. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  22931. SQLITE_IOERR_LOCK;
  22932. goto afp_end_lock;
  22933. }
  22934. }else{
  22935. rc = failed;
  22936. }
  22937. }
  22938. if( failed ){
  22939. rc = failed;
  22940. }
  22941. }
  22942. if( rc==SQLITE_OK ){
  22943. pFile->locktype = locktype;
  22944. }else if( locktype==EXCLUSIVE_LOCK ){
  22945. pFile->locktype = PENDING_LOCK;
  22946. }
  22947. afp_end_lock:
  22948. unixLeaveMutex();
  22949. OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
  22950. rc==SQLITE_OK ? "ok" : "failed");
  22951. return rc;
  22952. }
  22953. /*
  22954. ** Lower the locking level on file descriptor pFile to locktype. locktype
  22955. ** must be either NO_LOCK or SHARED_LOCK.
  22956. **
  22957. ** If the locking level of the file descriptor is already at or below
  22958. ** the requested locking level, this routine is a no-op.
  22959. */
  22960. static int afpUnlock(sqlite3_file *id, int locktype) {
  22961. int rc = SQLITE_OK;
  22962. unixFile *pFile = (unixFile*)id;
  22963. afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
  22964. assert( pFile );
  22965. OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
  22966. pFile->locktype, getpid());
  22967. assert( locktype<=SHARED_LOCK );
  22968. if( pFile->locktype<=locktype ){
  22969. return SQLITE_OK;
  22970. }
  22971. if( CHECK_THREADID(pFile) ){
  22972. return SQLITE_MISUSE;
  22973. }
  22974. unixEnterMutex();
  22975. if( pFile->locktype>SHARED_LOCK ){
  22976. if( pFile->locktype==EXCLUSIVE_LOCK ){
  22977. rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  22978. if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
  22979. /* only re-establish the shared lock if necessary */
  22980. int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
  22981. rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
  22982. }
  22983. }
  22984. if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
  22985. rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
  22986. }
  22987. if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
  22988. rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
  22989. }
  22990. }else if( locktype==NO_LOCK ){
  22991. /* clear the shared lock */
  22992. int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
  22993. rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
  22994. }
  22995. if( rc==SQLITE_OK ){
  22996. if( locktype==NO_LOCK ){
  22997. struct unixOpenCnt *pOpen = pFile->pOpen;
  22998. pOpen->nLock--;
  22999. assert( pOpen->nLock>=0 );
  23000. if( pOpen->nLock==0 && pOpen->nPending>0 ){
  23001. int i;
  23002. for(i=0; i<pOpen->nPending; i++){
  23003. if( pOpen->aPending[i] < 0 ) continue;
  23004. if( close(pOpen->aPending[i]) ){
  23005. pFile->lastErrno = errno;
  23006. rc = SQLITE_IOERR_CLOSE;
  23007. }else{
  23008. pOpen->aPending[i] = -1;
  23009. }
  23010. }
  23011. if( rc==SQLITE_OK ){
  23012. sqlite3_free(pOpen->aPending);
  23013. pOpen->nPending = 0;
  23014. pOpen->aPending = 0;
  23015. }
  23016. }
  23017. }
  23018. }
  23019. unixLeaveMutex();
  23020. if( rc==SQLITE_OK ) pFile->locktype = locktype;
  23021. return rc;
  23022. }
  23023. /*
  23024. ** Close a file & cleanup AFP specific locking context
  23025. */
  23026. static int afpClose(sqlite3_file *id) {
  23027. if( id ){
  23028. unixFile *pFile = (unixFile*)id;
  23029. afpUnlock(id, NO_LOCK);
  23030. unixEnterMutex();
  23031. if( pFile->pOpen && pFile->pOpen->nLock ){
  23032. /* If there are outstanding locks, do not actually close the file just
  23033. ** yet because that would clear those locks. Instead, add the file
  23034. ** descriptor to pOpen->aPending. It will be automatically closed when
  23035. ** the last lock is cleared.
  23036. */
  23037. int *aNew;
  23038. struct unixOpenCnt *pOpen = pFile->pOpen;
  23039. aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
  23040. if( aNew==0 ){
  23041. /* If a malloc fails, just leak the file descriptor */
  23042. }else{
  23043. pOpen->aPending = aNew;
  23044. pOpen->aPending[pOpen->nPending] = pFile->h;
  23045. pOpen->nPending++;
  23046. pFile->h = -1;
  23047. }
  23048. }
  23049. releaseOpenCnt(pFile->pOpen);
  23050. sqlite3_free(pFile->lockingContext);
  23051. closeUnixFile(id);
  23052. unixLeaveMutex();
  23053. }
  23054. return SQLITE_OK;
  23055. }
  23056. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  23057. /*
  23058. ** The code above is the AFP lock implementation. The code is specific
  23059. ** to MacOSX and does not work on other unix platforms. No alternative
  23060. ** is available. If you don't compile for a mac, then the "unix-afp"
  23061. ** VFS is not available.
  23062. **
  23063. ********************* End of the AFP lock implementation **********************
  23064. ******************************************************************************/
  23065. /******************************************************************************
  23066. **************** Non-locking sqlite3_file methods *****************************
  23067. **
  23068. ** The next division contains implementations for all methods of the
  23069. ** sqlite3_file object other than the locking methods. The locking
  23070. ** methods were defined in divisions above (one locking method per
  23071. ** division). Those methods that are common to all locking modes
  23072. ** are gather together into this division.
  23073. */
  23074. /*
  23075. ** Seek to the offset passed as the second argument, then read cnt
  23076. ** bytes into pBuf. Return the number of bytes actually read.
  23077. **
  23078. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  23079. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  23080. ** one system to another. Since SQLite does not define USE_PREAD
  23081. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  23082. ** See tickets #2741 and #2681.
  23083. **
  23084. ** To avoid stomping the errno value on a failed read the lastErrno value
  23085. ** is set before returning.
  23086. */
  23087. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  23088. int got;
  23089. i64 newOffset;
  23090. TIMER_START;
  23091. #if defined(USE_PREAD)
  23092. got = pread(id->h, pBuf, cnt, offset);
  23093. SimulateIOError( got = -1 );
  23094. #elif defined(USE_PREAD64)
  23095. got = pread64(id->h, pBuf, cnt, offset);
  23096. SimulateIOError( got = -1 );
  23097. #else
  23098. newOffset = lseek(id->h, offset, SEEK_SET);
  23099. SimulateIOError( newOffset-- );
  23100. if( newOffset!=offset ){
  23101. if( newOffset == -1 ){
  23102. ((unixFile*)id)->lastErrno = errno;
  23103. }else{
  23104. ((unixFile*)id)->lastErrno = 0;
  23105. }
  23106. return -1;
  23107. }
  23108. got = read(id->h, pBuf, cnt);
  23109. #endif
  23110. TIMER_END;
  23111. if( got<0 ){
  23112. ((unixFile*)id)->lastErrno = errno;
  23113. }
  23114. OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
  23115. return got;
  23116. }
  23117. /*
  23118. ** Read data from a file into a buffer. Return SQLITE_OK if all
  23119. ** bytes were read successfully and SQLITE_IOERR if anything goes
  23120. ** wrong.
  23121. */
  23122. static int unixRead(
  23123. sqlite3_file *id,
  23124. void *pBuf,
  23125. int amt,
  23126. sqlite3_int64 offset
  23127. ){
  23128. int got;
  23129. assert( id );
  23130. got = seekAndRead((unixFile*)id, offset, pBuf, amt);
  23131. if( got==amt ){
  23132. return SQLITE_OK;
  23133. }else if( got<0 ){
  23134. /* lastErrno set by seekAndRead */
  23135. return SQLITE_IOERR_READ;
  23136. }else{
  23137. ((unixFile*)id)->lastErrno = 0; /* not a system error */
  23138. /* Unread parts of the buffer must be zero-filled */
  23139. memset(&((char*)pBuf)[got], 0, amt-got);
  23140. return SQLITE_IOERR_SHORT_READ;
  23141. }
  23142. }
  23143. /*
  23144. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  23145. ** Return the number of bytes actually read. Update the offset.
  23146. **
  23147. ** To avoid stomping the errno value on a failed write the lastErrno value
  23148. ** is set before returning.
  23149. */
  23150. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  23151. int got;
  23152. i64 newOffset;
  23153. TIMER_START;
  23154. #if defined(USE_PREAD)
  23155. got = pwrite(id->h, pBuf, cnt, offset);
  23156. #elif defined(USE_PREAD64)
  23157. got = pwrite64(id->h, pBuf, cnt, offset);
  23158. #else
  23159. newOffset = lseek(id->h, offset, SEEK_SET);
  23160. if( newOffset!=offset ){
  23161. if( newOffset == -1 ){
  23162. ((unixFile*)id)->lastErrno = errno;
  23163. }else{
  23164. ((unixFile*)id)->lastErrno = 0;
  23165. }
  23166. return -1;
  23167. }
  23168. got = write(id->h, pBuf, cnt);
  23169. #endif
  23170. TIMER_END;
  23171. if( got<0 ){
  23172. ((unixFile*)id)->lastErrno = errno;
  23173. }
  23174. OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
  23175. return got;
  23176. }
  23177. /*
  23178. ** Write data from a buffer into a file. Return SQLITE_OK on success
  23179. ** or some other error code on failure.
  23180. */
  23181. static int unixWrite(
  23182. sqlite3_file *id,
  23183. const void *pBuf,
  23184. int amt,
  23185. sqlite3_int64 offset
  23186. ){
  23187. int wrote = 0;
  23188. assert( id );
  23189. assert( amt>0 );
  23190. #ifndef NDEBUG
  23191. /* If we are doing a normal write to a database file (as opposed to
  23192. ** doing a hot-journal rollback or a write to some file other than a
  23193. ** normal database file) then record the fact that the database
  23194. ** has changed. If the transaction counter is modified, record that
  23195. ** fact too.
  23196. */
  23197. if( ((unixFile*)id)->inNormalWrite ){
  23198. unixFile *pFile = (unixFile*)id;
  23199. pFile->dbUpdate = 1; /* The database has been modified */
  23200. if( offset<=24 && offset+amt>=27 ){
  23201. char oldCntr[4];
  23202. SimulateIOErrorBenign(1);
  23203. seekAndRead(pFile, 24, oldCntr, 4);
  23204. SimulateIOErrorBenign(0);
  23205. if( memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  23206. pFile->transCntrChng = 1; /* The transaction counter has changed */
  23207. }
  23208. }
  23209. }
  23210. #endif
  23211. while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
  23212. amt -= wrote;
  23213. offset += wrote;
  23214. pBuf = &((char*)pBuf)[wrote];
  23215. }
  23216. SimulateIOError(( wrote=(-1), amt=1 ));
  23217. SimulateDiskfullError(( wrote=0, amt=1 ));
  23218. if( amt>0 ){
  23219. if( wrote<0 ){
  23220. /* lastErrno set by seekAndWrite */
  23221. return SQLITE_IOERR_WRITE;
  23222. }else{
  23223. ((unixFile*)id)->lastErrno = 0; /* not a system error */
  23224. return SQLITE_FULL;
  23225. }
  23226. }
  23227. return SQLITE_OK;
  23228. }
  23229. #ifdef SQLITE_TEST
  23230. /*
  23231. ** Count the number of fullsyncs and normal syncs. This is used to test
  23232. ** that syncs and fullsyncs are occurring at the right times.
  23233. */
  23234. SQLITE_API int sqlite3_sync_count = 0;
  23235. SQLITE_API int sqlite3_fullsync_count = 0;
  23236. #endif
  23237. /*
  23238. ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
  23239. ** Otherwise use fsync() in its place.
  23240. */
  23241. #ifndef HAVE_FDATASYNC
  23242. # define fdatasync fsync
  23243. #endif
  23244. /*
  23245. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  23246. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  23247. ** only available on Mac OS X. But that could change.
  23248. */
  23249. #ifdef F_FULLFSYNC
  23250. # define HAVE_FULLFSYNC 1
  23251. #else
  23252. # define HAVE_FULLFSYNC 0
  23253. #endif
  23254. /*
  23255. ** The fsync() system call does not work as advertised on many
  23256. ** unix systems. The following procedure is an attempt to make
  23257. ** it work better.
  23258. **
  23259. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  23260. ** for testing when we want to run through the test suite quickly.
  23261. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  23262. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  23263. ** or power failure will likely corrupt the database file.
  23264. */
  23265. static int full_fsync(int fd, int fullSync, int dataOnly){
  23266. int rc;
  23267. /* The following "ifdef/elif/else/" block has the same structure as
  23268. ** the one below. It is replicated here solely to avoid cluttering
  23269. ** up the real code with the UNUSED_PARAMETER() macros.
  23270. */
  23271. #ifdef SQLITE_NO_SYNC
  23272. UNUSED_PARAMETER(fd);
  23273. UNUSED_PARAMETER(fullSync);
  23274. UNUSED_PARAMETER(dataOnly);
  23275. #elif HAVE_FULLFSYNC
  23276. UNUSED_PARAMETER(dataOnly);
  23277. #else
  23278. UNUSED_PARAMETER(fullSync);
  23279. #endif
  23280. /* Record the number of times that we do a normal fsync() and
  23281. ** FULLSYNC. This is used during testing to verify that this procedure
  23282. ** gets called with the correct arguments.
  23283. */
  23284. #ifdef SQLITE_TEST
  23285. if( fullSync ) sqlite3_fullsync_count++;
  23286. sqlite3_sync_count++;
  23287. #endif
  23288. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  23289. ** no-op
  23290. */
  23291. #ifdef SQLITE_NO_SYNC
  23292. rc = SQLITE_OK;
  23293. #elif HAVE_FULLFSYNC
  23294. if( fullSync ){
  23295. rc = fcntl(fd, F_FULLFSYNC, 0);
  23296. }else{
  23297. rc = 1;
  23298. }
  23299. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  23300. ** It shouldn't be possible for fullfsync to fail on the local
  23301. ** file system (on OSX), so failure indicates that FULLFSYNC
  23302. ** isn't supported for this file system. So, attempt an fsync
  23303. ** and (for now) ignore the overhead of a superfluous fcntl call.
  23304. ** It'd be better to detect fullfsync support once and avoid
  23305. ** the fcntl call every time sync is called.
  23306. */
  23307. if( rc ) rc = fsync(fd);
  23308. #else
  23309. if( dataOnly ){
  23310. rc = fdatasync(fd);
  23311. #if OS_VXWORKS
  23312. if( rc==-1 && errno==ENOTSUP ){
  23313. rc = fsync(fd);
  23314. }
  23315. #endif
  23316. }else{
  23317. rc = fsync(fd);
  23318. }
  23319. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  23320. if( OS_VXWORKS && rc!= -1 ){
  23321. rc = 0;
  23322. }
  23323. return rc;
  23324. }
  23325. /*
  23326. ** Make sure all writes to a particular file are committed to disk.
  23327. **
  23328. ** If dataOnly==0 then both the file itself and its metadata (file
  23329. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  23330. ** file data is synced.
  23331. **
  23332. ** Under Unix, also make sure that the directory entry for the file
  23333. ** has been created by fsync-ing the directory that contains the file.
  23334. ** If we do not do this and we encounter a power failure, the directory
  23335. ** entry for the journal might not exist after we reboot. The next
  23336. ** SQLite to access the file will not know that the journal exists (because
  23337. ** the directory entry for the journal was never created) and the transaction
  23338. ** will not roll back - possibly leading to database corruption.
  23339. */
  23340. static int unixSync(sqlite3_file *id, int flags){
  23341. int rc;
  23342. unixFile *pFile = (unixFile*)id;
  23343. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  23344. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  23345. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  23346. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  23347. || (flags&0x0F)==SQLITE_SYNC_FULL
  23348. );
  23349. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  23350. ** line is to test that doing so does not cause any problems.
  23351. */
  23352. SimulateDiskfullError( return SQLITE_FULL );
  23353. assert( pFile );
  23354. OSTRACE2("SYNC %-3d\n", pFile->h);
  23355. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  23356. SimulateIOError( rc=1 );
  23357. if( rc ){
  23358. pFile->lastErrno = errno;
  23359. return SQLITE_IOERR_FSYNC;
  23360. }
  23361. if( pFile->dirfd>=0 ){
  23362. int err;
  23363. OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
  23364. HAVE_FULLFSYNC, isFullsync);
  23365. #ifndef SQLITE_DISABLE_DIRSYNC
  23366. /* The directory sync is only attempted if full_fsync is
  23367. ** turned off or unavailable. If a full_fsync occurred above,
  23368. ** then the directory sync is superfluous.
  23369. */
  23370. if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
  23371. /*
  23372. ** We have received multiple reports of fsync() returning
  23373. ** errors when applied to directories on certain file systems.
  23374. ** A failed directory sync is not a big deal. So it seems
  23375. ** better to ignore the error. Ticket #1657
  23376. */
  23377. /* pFile->lastErrno = errno; */
  23378. /* return SQLITE_IOERR; */
  23379. }
  23380. #endif
  23381. err = close(pFile->dirfd); /* Only need to sync once, so close the */
  23382. if( err==0 ){ /* directory when we are done */
  23383. pFile->dirfd = -1;
  23384. }else{
  23385. pFile->lastErrno = errno;
  23386. rc = SQLITE_IOERR_DIR_CLOSE;
  23387. }
  23388. }
  23389. return rc;
  23390. }
  23391. /*
  23392. ** Truncate an open file to a specified size
  23393. */
  23394. static int unixTruncate(sqlite3_file *id, i64 nByte){
  23395. int rc;
  23396. assert( id );
  23397. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  23398. rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
  23399. if( rc ){
  23400. ((unixFile*)id)->lastErrno = errno;
  23401. return SQLITE_IOERR_TRUNCATE;
  23402. }else{
  23403. return SQLITE_OK;
  23404. }
  23405. }
  23406. /*
  23407. ** Determine the current size of a file in bytes
  23408. */
  23409. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  23410. int rc;
  23411. struct stat buf;
  23412. assert( id );
  23413. rc = fstat(((unixFile*)id)->h, &buf);
  23414. SimulateIOError( rc=1 );
  23415. if( rc!=0 ){
  23416. ((unixFile*)id)->lastErrno = errno;
  23417. return SQLITE_IOERR_FSTAT;
  23418. }
  23419. *pSize = buf.st_size;
  23420. /* When opening a zero-size database, the findLockInfo() procedure
  23421. ** writes a single byte into that file in order to work around a bug
  23422. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  23423. ** layers, we need to report this file size as zero even though it is
  23424. ** really 1. Ticket #3260.
  23425. */
  23426. if( *pSize==1 ) *pSize = 0;
  23427. return SQLITE_OK;
  23428. }
  23429. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  23430. /*
  23431. ** Handler for proxy-locking file-control verbs. Defined below in the
  23432. ** proxying locking division.
  23433. */
  23434. static int proxyFileControl(sqlite3_file*,int,void*);
  23435. #endif
  23436. /*
  23437. ** Information and control of an open file handle.
  23438. */
  23439. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  23440. switch( op ){
  23441. case SQLITE_FCNTL_LOCKSTATE: {
  23442. *(int*)pArg = ((unixFile*)id)->locktype;
  23443. return SQLITE_OK;
  23444. }
  23445. case SQLITE_LAST_ERRNO: {
  23446. *(int*)pArg = ((unixFile*)id)->lastErrno;
  23447. return SQLITE_OK;
  23448. }
  23449. #ifndef NDEBUG
  23450. /* The pager calls this method to signal that it has done
  23451. ** a rollback and that the database is therefore unchanged and
  23452. ** it hence it is OK for the transaction change counter to be
  23453. ** unchanged.
  23454. */
  23455. case SQLITE_FCNTL_DB_UNCHANGED: {
  23456. ((unixFile*)id)->dbUpdate = 0;
  23457. return SQLITE_OK;
  23458. }
  23459. #endif
  23460. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  23461. case SQLITE_SET_LOCKPROXYFILE:
  23462. case SQLITE_GET_LOCKPROXYFILE: {
  23463. return proxyFileControl(id,op,pArg);
  23464. }
  23465. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  23466. }
  23467. return SQLITE_ERROR;
  23468. }
  23469. /*
  23470. ** Return the sector size in bytes of the underlying block device for
  23471. ** the specified file. This is almost always 512 bytes, but may be
  23472. ** larger for some devices.
  23473. **
  23474. ** SQLite code assumes this function cannot fail. It also assumes that
  23475. ** if two files are created in the same file-system directory (i.e.
  23476. ** a database and its journal file) that the sector size will be the
  23477. ** same for both.
  23478. */
  23479. static int unixSectorSize(sqlite3_file *NotUsed){
  23480. UNUSED_PARAMETER(NotUsed);
  23481. return SQLITE_DEFAULT_SECTOR_SIZE;
  23482. }
  23483. /*
  23484. ** Return the device characteristics for the file. This is always 0 for unix.
  23485. */
  23486. static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
  23487. UNUSED_PARAMETER(NotUsed);
  23488. return 0;
  23489. }
  23490. /*
  23491. ** Here ends the implementation of all sqlite3_file methods.
  23492. **
  23493. ********************** End sqlite3_file Methods *******************************
  23494. ******************************************************************************/
  23495. /*
  23496. ** This division contains definitions of sqlite3_io_methods objects that
  23497. ** implement various file locking strategies. It also contains definitions
  23498. ** of "finder" functions. A finder-function is used to locate the appropriate
  23499. ** sqlite3_io_methods object for a particular database file. The pAppData
  23500. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  23501. ** the correct finder-function for that VFS.
  23502. **
  23503. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  23504. ** object. The only interesting finder-function is autolockIoFinder, which
  23505. ** looks at the filesystem type and tries to guess the best locking
  23506. ** strategy from that.
  23507. **
  23508. ** For finder-funtion F, two objects are created:
  23509. **
  23510. ** (1) The real finder-function named "FImpt()".
  23511. **
  23512. ** (2) A constant pointer to this functio named just "F".
  23513. **
  23514. **
  23515. ** A pointer to the F pointer is used as the pAppData value for VFS
  23516. ** objects. We have to do this instead of letting pAppData point
  23517. ** directly at the finder-function since C90 rules prevent a void*
  23518. ** from be cast into a function pointer.
  23519. **
  23520. **
  23521. ** Each instance of this macro generates two objects:
  23522. **
  23523. ** * A constant sqlite3_io_methods object call METHOD that has locking
  23524. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  23525. **
  23526. ** * An I/O method finder function called FINDER that returns a pointer
  23527. ** to the METHOD object in the previous bullet.
  23528. */
  23529. #define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
  23530. static const sqlite3_io_methods METHOD = { \
  23531. 1, /* iVersion */ \
  23532. CLOSE, /* xClose */ \
  23533. unixRead, /* xRead */ \
  23534. unixWrite, /* xWrite */ \
  23535. unixTruncate, /* xTruncate */ \
  23536. unixSync, /* xSync */ \
  23537. unixFileSize, /* xFileSize */ \
  23538. LOCK, /* xLock */ \
  23539. UNLOCK, /* xUnlock */ \
  23540. CKLOCK, /* xCheckReservedLock */ \
  23541. unixFileControl, /* xFileControl */ \
  23542. unixSectorSize, /* xSectorSize */ \
  23543. unixDeviceCharacteristics /* xDeviceCapabilities */ \
  23544. }; \
  23545. static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){ \
  23546. UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
  23547. return &METHOD; \
  23548. } \
  23549. static const sqlite3_io_methods *(*const FINDER)(const char*,int) \
  23550. = FINDER##Impl;
  23551. /*
  23552. ** Here are all of the sqlite3_io_methods objects for each of the
  23553. ** locking strategies. Functions that return pointers to these methods
  23554. ** are also created.
  23555. */
  23556. IOMETHODS(
  23557. posixIoFinder, /* Finder function name */
  23558. posixIoMethods, /* sqlite3_io_methods object name */
  23559. unixClose, /* xClose method */
  23560. unixLock, /* xLock method */
  23561. unixUnlock, /* xUnlock method */
  23562. unixCheckReservedLock /* xCheckReservedLock method */
  23563. )
  23564. IOMETHODS(
  23565. nolockIoFinder, /* Finder function name */
  23566. nolockIoMethods, /* sqlite3_io_methods object name */
  23567. nolockClose, /* xClose method */
  23568. nolockLock, /* xLock method */
  23569. nolockUnlock, /* xUnlock method */
  23570. nolockCheckReservedLock /* xCheckReservedLock method */
  23571. )
  23572. IOMETHODS(
  23573. dotlockIoFinder, /* Finder function name */
  23574. dotlockIoMethods, /* sqlite3_io_methods object name */
  23575. dotlockClose, /* xClose method */
  23576. dotlockLock, /* xLock method */
  23577. dotlockUnlock, /* xUnlock method */
  23578. dotlockCheckReservedLock /* xCheckReservedLock method */
  23579. )
  23580. #if SQLITE_ENABLE_LOCKING_STYLE
  23581. IOMETHODS(
  23582. flockIoFinder, /* Finder function name */
  23583. flockIoMethods, /* sqlite3_io_methods object name */
  23584. flockClose, /* xClose method */
  23585. flockLock, /* xLock method */
  23586. flockUnlock, /* xUnlock method */
  23587. flockCheckReservedLock /* xCheckReservedLock method */
  23588. )
  23589. #endif
  23590. #if OS_VXWORKS
  23591. IOMETHODS(
  23592. semIoFinder, /* Finder function name */
  23593. semIoMethods, /* sqlite3_io_methods object name */
  23594. semClose, /* xClose method */
  23595. semLock, /* xLock method */
  23596. semUnlock, /* xUnlock method */
  23597. semCheckReservedLock /* xCheckReservedLock method */
  23598. )
  23599. #endif
  23600. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  23601. IOMETHODS(
  23602. afpIoFinder, /* Finder function name */
  23603. afpIoMethods, /* sqlite3_io_methods object name */
  23604. afpClose, /* xClose method */
  23605. afpLock, /* xLock method */
  23606. afpUnlock, /* xUnlock method */
  23607. afpCheckReservedLock /* xCheckReservedLock method */
  23608. )
  23609. #endif
  23610. /*
  23611. ** The proxy locking method is a "super-method" in the sense that it
  23612. ** opens secondary file descriptors for the conch and lock files and
  23613. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  23614. ** secondary files. For this reason, the division that implements
  23615. ** proxy locking is located much further down in the file. But we need
  23616. ** to go ahead and define the sqlite3_io_methods and finder function
  23617. ** for proxy locking here. So we forward declare the I/O methods.
  23618. */
  23619. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  23620. static int proxyClose(sqlite3_file*);
  23621. static int proxyLock(sqlite3_file*, int);
  23622. static int proxyUnlock(sqlite3_file*, int);
  23623. static int proxyCheckReservedLock(sqlite3_file*, int*);
  23624. IOMETHODS(
  23625. proxyIoFinder, /* Finder function name */
  23626. proxyIoMethods, /* sqlite3_io_methods object name */
  23627. proxyClose, /* xClose method */
  23628. proxyLock, /* xLock method */
  23629. proxyUnlock, /* xUnlock method */
  23630. proxyCheckReservedLock /* xCheckReservedLock method */
  23631. )
  23632. #endif
  23633. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  23634. /*
  23635. ** This "finder" function attempts to determine the best locking strategy
  23636. ** for the database file "filePath". It then returns the sqlite3_io_methods
  23637. ** object that implements that strategy.
  23638. **
  23639. ** This is for MacOSX only.
  23640. */
  23641. static const sqlite3_io_methods *autolockIoFinderImpl(
  23642. const char *filePath, /* name of the database file */
  23643. int fd /* file descriptor open on the database file */
  23644. ){
  23645. static const struct Mapping {
  23646. const char *zFilesystem; /* Filesystem type name */
  23647. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  23648. } aMap[] = {
  23649. { "hfs", &posixIoMethods },
  23650. { "ufs", &posixIoMethods },
  23651. { "afpfs", &afpIoMethods },
  23652. #ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
  23653. { "smbfs", &afpIoMethods },
  23654. #else
  23655. { "smbfs", &flockIoMethods },
  23656. #endif
  23657. { "webdav", &nolockIoMethods },
  23658. { 0, 0 }
  23659. };
  23660. int i;
  23661. struct statfs fsInfo;
  23662. struct flock lockInfo;
  23663. if( !filePath ){
  23664. /* If filePath==NULL that means we are dealing with a transient file
  23665. ** that does not need to be locked. */
  23666. return &nolockIoMethods;
  23667. }
  23668. if( statfs(filePath, &fsInfo) != -1 ){
  23669. if( fsInfo.f_flags & MNT_RDONLY ){
  23670. return &nolockIoMethods;
  23671. }
  23672. for(i=0; aMap[i].zFilesystem; i++){
  23673. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  23674. return aMap[i].pMethods;
  23675. }
  23676. }
  23677. }
  23678. /* Default case. Handles, amongst others, "nfs".
  23679. ** Test byte-range lock using fcntl(). If the call succeeds,
  23680. ** assume that the file-system supports POSIX style locks.
  23681. */
  23682. lockInfo.l_len = 1;
  23683. lockInfo.l_start = 0;
  23684. lockInfo.l_whence = SEEK_SET;
  23685. lockInfo.l_type = F_RDLCK;
  23686. if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
  23687. return &posixIoMethods;
  23688. }else{
  23689. return &dotlockIoMethods;
  23690. }
  23691. }
  23692. static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
  23693. = autolockIoFinderImpl;
  23694. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  23695. /*
  23696. ** An abstract type for a pointer to a IO method finder function:
  23697. */
  23698. typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
  23699. /****************************************************************************
  23700. **************************** sqlite3_vfs methods ****************************
  23701. **
  23702. ** This division contains the implementation of methods on the
  23703. ** sqlite3_vfs object.
  23704. */
  23705. /*
  23706. ** Initialize the contents of the unixFile structure pointed to by pId.
  23707. */
  23708. static int fillInUnixFile(
  23709. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  23710. int h, /* Open file descriptor of file being opened */
  23711. int dirfd, /* Directory file descriptor */
  23712. sqlite3_file *pId, /* Write to the unixFile structure here */
  23713. const char *zFilename, /* Name of the file being opened */
  23714. int noLock, /* Omit locking if true */
  23715. int isDelete /* Delete on close if true */
  23716. ){
  23717. const sqlite3_io_methods *pLockingStyle;
  23718. unixFile *pNew = (unixFile *)pId;
  23719. int rc = SQLITE_OK;
  23720. assert( pNew->pLock==NULL );
  23721. assert( pNew->pOpen==NULL );
  23722. /* Parameter isDelete is only used on vxworks.
  23723. ** Express this explicitly here to prevent compiler warnings
  23724. ** about unused parameters.
  23725. */
  23726. #if !OS_VXWORKS
  23727. UNUSED_PARAMETER(isDelete);
  23728. #endif
  23729. OSTRACE3("OPEN %-3d %s\n", h, zFilename);
  23730. pNew->h = h;
  23731. pNew->dirfd = dirfd;
  23732. SET_THREADID(pNew);
  23733. #if OS_VXWORKS
  23734. pNew->pId = vxworksFindFileId(zFilename);
  23735. if( pNew->pId==0 ){
  23736. noLock = 1;
  23737. rc = SQLITE_NOMEM;
  23738. }
  23739. #endif
  23740. if( noLock ){
  23741. pLockingStyle = &nolockIoMethods;
  23742. }else{
  23743. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
  23744. #if SQLITE_ENABLE_LOCKING_STYLE
  23745. /* Cache zFilename in the locking context (AFP and dotlock override) for
  23746. ** proxyLock activation is possible (remote proxy is based on db name)
  23747. ** zFilename remains valid until file is closed, to support */
  23748. pNew->lockingContext = (void*)zFilename;
  23749. #endif
  23750. }
  23751. if( pLockingStyle == &posixIoMethods ){
  23752. unixEnterMutex();
  23753. rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
  23754. unixLeaveMutex();
  23755. }
  23756. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  23757. else if( pLockingStyle == &afpIoMethods ){
  23758. /* AFP locking uses the file path so it needs to be included in
  23759. ** the afpLockingContext.
  23760. */
  23761. afpLockingContext *pCtx;
  23762. pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
  23763. if( pCtx==0 ){
  23764. rc = SQLITE_NOMEM;
  23765. }else{
  23766. /* NB: zFilename exists and remains valid until the file is closed
  23767. ** according to requirement F11141. So we do not need to make a
  23768. ** copy of the filename. */
  23769. pCtx->dbPath = zFilename;
  23770. srandomdev();
  23771. unixEnterMutex();
  23772. rc = findLockInfo(pNew, NULL, &pNew->pOpen);
  23773. unixLeaveMutex();
  23774. }
  23775. }
  23776. #endif
  23777. else if( pLockingStyle == &dotlockIoMethods ){
  23778. /* Dotfile locking uses the file path so it needs to be included in
  23779. ** the dotlockLockingContext
  23780. */
  23781. char *zLockFile;
  23782. int nFilename;
  23783. nFilename = (int)strlen(zFilename) + 6;
  23784. zLockFile = (char *)sqlite3_malloc(nFilename);
  23785. if( zLockFile==0 ){
  23786. rc = SQLITE_NOMEM;
  23787. }else{
  23788. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  23789. }
  23790. pNew->lockingContext = zLockFile;
  23791. }
  23792. #if OS_VXWORKS
  23793. else if( pLockingStyle == &semIoMethods ){
  23794. /* Named semaphore locking uses the file path so it needs to be
  23795. ** included in the semLockingContext
  23796. */
  23797. unixEnterMutex();
  23798. rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
  23799. if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
  23800. char *zSemName = pNew->pOpen->aSemName;
  23801. int n;
  23802. sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
  23803. pNew->pId->zCanonicalName);
  23804. for( n=0; zSemName[n]; n++ )
  23805. if( zSemName[n]=='/' ) zSemName[n] = '_';
  23806. pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  23807. if( pNew->pOpen->pSem == SEM_FAILED ){
  23808. rc = SQLITE_NOMEM;
  23809. pNew->pOpen->aSemName[0] = '\0';
  23810. }
  23811. }
  23812. unixLeaveMutex();
  23813. }
  23814. #endif
  23815. pNew->lastErrno = 0;
  23816. #if OS_VXWORKS
  23817. if( rc!=SQLITE_OK ){
  23818. unlink(zFilename);
  23819. isDelete = 0;
  23820. }
  23821. pNew->isDelete = isDelete;
  23822. #endif
  23823. if( rc!=SQLITE_OK ){
  23824. if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
  23825. close(h);
  23826. }else{
  23827. pNew->pMethod = pLockingStyle;
  23828. OpenCounter(+1);
  23829. }
  23830. return rc;
  23831. }
  23832. /*
  23833. ** Open a file descriptor to the directory containing file zFilename.
  23834. ** If successful, *pFd is set to the opened file descriptor and
  23835. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  23836. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  23837. ** value.
  23838. **
  23839. ** If SQLITE_OK is returned, the caller is responsible for closing
  23840. ** the file descriptor *pFd using close().
  23841. */
  23842. static int openDirectory(const char *zFilename, int *pFd){
  23843. int ii;
  23844. int fd = -1;
  23845. char zDirname[MAX_PATHNAME+1];
  23846. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  23847. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  23848. if( ii>0 ){
  23849. zDirname[ii] = '\0';
  23850. fd = open(zDirname, O_RDONLY|O_BINARY, 0);
  23851. if( fd>=0 ){
  23852. #ifdef FD_CLOEXEC
  23853. fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  23854. #endif
  23855. OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
  23856. }
  23857. }
  23858. *pFd = fd;
  23859. return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
  23860. }
  23861. /*
  23862. ** Create a temporary file name in zBuf. zBuf must be allocated
  23863. ** by the calling process and must be big enough to hold at least
  23864. ** pVfs->mxPathname bytes.
  23865. */
  23866. static int getTempname(int nBuf, char *zBuf){
  23867. static const char *azDirs[] = {
  23868. 0,
  23869. 0,
  23870. "/var/tmp",
  23871. "/usr/tmp",
  23872. "/tmp",
  23873. ".",
  23874. };
  23875. static const unsigned char zChars[] =
  23876. "abcdefghijklmnopqrstuvwxyz"
  23877. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  23878. "0123456789";
  23879. unsigned int i, j;
  23880. struct stat buf;
  23881. const char *zDir = ".";
  23882. /* It's odd to simulate an io-error here, but really this is just
  23883. ** using the io-error infrastructure to test that SQLite handles this
  23884. ** function failing.
  23885. */
  23886. SimulateIOError( return SQLITE_IOERR );
  23887. azDirs[0] = sqlite3_temp_directory;
  23888. if (NULL == azDirs[1]) {
  23889. azDirs[1] = getenv("TMPDIR");
  23890. }
  23891. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
  23892. if( azDirs[i]==0 ) continue;
  23893. if( stat(azDirs[i], &buf) ) continue;
  23894. if( !S_ISDIR(buf.st_mode) ) continue;
  23895. if( access(azDirs[i], 07) ) continue;
  23896. zDir = azDirs[i];
  23897. break;
  23898. }
  23899. /* Check that the output buffer is large enough for the temporary file
  23900. ** name. If it is not, return SQLITE_ERROR.
  23901. */
  23902. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
  23903. return SQLITE_ERROR;
  23904. }
  23905. do{
  23906. sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  23907. j = (int)strlen(zBuf);
  23908. sqlite3_randomness(15, &zBuf[j]);
  23909. for(i=0; i<15; i++, j++){
  23910. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  23911. }
  23912. zBuf[j] = 0;
  23913. }while( access(zBuf,0)==0 );
  23914. return SQLITE_OK;
  23915. }
  23916. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  23917. /*
  23918. ** Routine to transform a unixFile into a proxy-locking unixFile.
  23919. ** Implementation in the proxy-lock division, but used by unixOpen()
  23920. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  23921. */
  23922. static int proxyTransformUnixFile(unixFile*, const char*);
  23923. #endif
  23924. /*
  23925. ** Open the file zPath.
  23926. **
  23927. ** Previously, the SQLite OS layer used three functions in place of this
  23928. ** one:
  23929. **
  23930. ** sqlite3OsOpenReadWrite();
  23931. ** sqlite3OsOpenReadOnly();
  23932. ** sqlite3OsOpenExclusive();
  23933. **
  23934. ** These calls correspond to the following combinations of flags:
  23935. **
  23936. ** ReadWrite() -> (READWRITE | CREATE)
  23937. ** ReadOnly() -> (READONLY)
  23938. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  23939. **
  23940. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  23941. ** true, the file was configured to be automatically deleted when the
  23942. ** file handle closed. To achieve the same effect using this new
  23943. ** interface, add the DELETEONCLOSE flag to those specified above for
  23944. ** OpenExclusive().
  23945. */
  23946. static int unixOpen(
  23947. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  23948. const char *zPath, /* Pathname of file to be opened */
  23949. sqlite3_file *pFile, /* The file descriptor to be filled in */
  23950. int flags, /* Input flags to control the opening */
  23951. int *pOutFlags /* Output flags returned to SQLite core */
  23952. ){
  23953. int fd = 0; /* File descriptor returned by open() */
  23954. int dirfd = -1; /* Directory file descriptor */
  23955. int openFlags = 0; /* Flags to pass to open() */
  23956. int eType = flags&0xFFFFFF00; /* Type of file to open */
  23957. int noLock; /* True to omit locking primitives */
  23958. int rc = SQLITE_OK;
  23959. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  23960. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  23961. int isCreate = (flags & SQLITE_OPEN_CREATE);
  23962. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  23963. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  23964. /* If creating a master or main-file journal, this function will open
  23965. ** a file-descriptor on the directory too. The first time unixSync()
  23966. ** is called the directory file descriptor will be fsync()ed and close()d.
  23967. */
  23968. int isOpenDirectory = (isCreate &&
  23969. (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
  23970. );
  23971. /* If argument zPath is a NULL pointer, this function is required to open
  23972. ** a temporary file. Use this buffer to store the file name in.
  23973. */
  23974. char zTmpname[MAX_PATHNAME+1];
  23975. const char *zName = zPath;
  23976. /* Check the following statements are true:
  23977. **
  23978. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  23979. ** (b) if CREATE is set, then READWRITE must also be set, and
  23980. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  23981. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  23982. */
  23983. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  23984. assert(isCreate==0 || isReadWrite);
  23985. assert(isExclusive==0 || isCreate);
  23986. assert(isDelete==0 || isCreate);
  23987. /* The main DB, main journal, and master journal are never automatically
  23988. ** deleted
  23989. */
  23990. assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
  23991. assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
  23992. assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
  23993. /* Assert that the upper layer has set one of the "file-type" flags. */
  23994. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  23995. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  23996. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  23997. || eType==SQLITE_OPEN_TRANSIENT_DB
  23998. );
  23999. memset(pFile, 0, sizeof(unixFile));
  24000. if( !zName ){
  24001. assert(isDelete && !isOpenDirectory);
  24002. rc = getTempname(MAX_PATHNAME+1, zTmpname);
  24003. if( rc!=SQLITE_OK ){
  24004. return rc;
  24005. }
  24006. zName = zTmpname;
  24007. }
  24008. if( isReadonly ) openFlags |= O_RDONLY;
  24009. if( isReadWrite ) openFlags |= O_RDWR;
  24010. if( isCreate ) openFlags |= O_CREAT;
  24011. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  24012. openFlags |= (O_LARGEFILE|O_BINARY);
  24013. fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
  24014. OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
  24015. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  24016. /* Failed to open the file for read/write access. Try read-only. */
  24017. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  24018. flags |= SQLITE_OPEN_READONLY;
  24019. return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
  24020. }
  24021. if( fd<0 ){
  24022. return SQLITE_CANTOPEN;
  24023. }
  24024. if( isDelete ){
  24025. #if OS_VXWORKS
  24026. zPath = zName;
  24027. #else
  24028. unlink(zName);
  24029. #endif
  24030. }
  24031. #if SQLITE_ENABLE_LOCKING_STYLE
  24032. else{
  24033. ((unixFile*)pFile)->openFlags = openFlags;
  24034. }
  24035. #endif
  24036. if( pOutFlags ){
  24037. *pOutFlags = flags;
  24038. }
  24039. assert(fd!=0);
  24040. if( isOpenDirectory ){
  24041. rc = openDirectory(zPath, &dirfd);
  24042. if( rc!=SQLITE_OK ){
  24043. close(fd); /* silently leak if fail, already in error */
  24044. return rc;
  24045. }
  24046. }
  24047. #ifdef FD_CLOEXEC
  24048. fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  24049. #endif
  24050. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  24051. #if SQLITE_PREFER_PROXY_LOCKING
  24052. if( zPath!=NULL && !noLock ){
  24053. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  24054. int useProxy = 0;
  24055. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy,
  24056. ** 0 means never use proxy, NULL means use proxy for non-local files only
  24057. */
  24058. if( envforce!=NULL ){
  24059. useProxy = atoi(envforce)>0;
  24060. }else{
  24061. struct statfs fsInfo;
  24062. if( statfs(zPath, &fsInfo) == -1 ){
  24063. ((unixFile*)pFile)->lastErrno = errno;
  24064. if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
  24065. close(fd); /* silently leak if fail, in error */
  24066. return SQLITE_IOERR_ACCESS;
  24067. }
  24068. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  24069. }
  24070. if( useProxy ){
  24071. rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
  24072. if( rc==SQLITE_OK ){
  24073. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  24074. }
  24075. return rc;
  24076. }
  24077. }
  24078. #endif
  24079. return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
  24080. }
  24081. /*
  24082. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  24083. ** the directory after deleting the file.
  24084. */
  24085. static int unixDelete(
  24086. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  24087. const char *zPath, /* Name of file to be deleted */
  24088. int dirSync /* If true, fsync() directory after deleting file */
  24089. ){
  24090. int rc = SQLITE_OK;
  24091. UNUSED_PARAMETER(NotUsed);
  24092. SimulateIOError(return SQLITE_IOERR_DELETE);
  24093. unlink(zPath);
  24094. #ifndef SQLITE_DISABLE_DIRSYNC
  24095. if( dirSync ){
  24096. int fd;
  24097. rc = openDirectory(zPath, &fd);
  24098. if( rc==SQLITE_OK ){
  24099. #if OS_VXWORKS
  24100. if( fsync(fd)==-1 )
  24101. #else
  24102. if( fsync(fd) )
  24103. #endif
  24104. {
  24105. rc = SQLITE_IOERR_DIR_FSYNC;
  24106. }
  24107. if( close(fd)&&!rc ){
  24108. rc = SQLITE_IOERR_DIR_CLOSE;
  24109. }
  24110. }
  24111. }
  24112. #endif
  24113. return rc;
  24114. }
  24115. /*
  24116. ** Test the existance of or access permissions of file zPath. The
  24117. ** test performed depends on the value of flags:
  24118. **
  24119. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  24120. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  24121. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  24122. **
  24123. ** Otherwise return 0.
  24124. */
  24125. static int unixAccess(
  24126. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  24127. const char *zPath, /* Path of the file to examine */
  24128. int flags, /* What do we want to learn about the zPath file? */
  24129. int *pResOut /* Write result boolean here */
  24130. ){
  24131. int amode = 0;
  24132. UNUSED_PARAMETER(NotUsed);
  24133. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  24134. switch( flags ){
  24135. case SQLITE_ACCESS_EXISTS:
  24136. amode = F_OK;
  24137. break;
  24138. case SQLITE_ACCESS_READWRITE:
  24139. amode = W_OK|R_OK;
  24140. break;
  24141. case SQLITE_ACCESS_READ:
  24142. amode = R_OK;
  24143. break;
  24144. default:
  24145. assert(!"Invalid flags argument");
  24146. }
  24147. *pResOut = (access(zPath, amode)==0);
  24148. return SQLITE_OK;
  24149. }
  24150. /*
  24151. ** Turn a relative pathname into a full pathname. The relative path
  24152. ** is stored as a nul-terminated string in the buffer pointed to by
  24153. ** zPath.
  24154. **
  24155. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  24156. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  24157. ** this buffer before returning.
  24158. */
  24159. static int unixFullPathname(
  24160. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  24161. const char *zPath, /* Possibly relative input path */
  24162. int nOut, /* Size of output buffer in bytes */
  24163. char *zOut /* Output buffer */
  24164. ){
  24165. /* It's odd to simulate an io-error here, but really this is just
  24166. ** using the io-error infrastructure to test that SQLite handles this
  24167. ** function failing. This function could fail if, for example, the
  24168. ** current working directory has been unlinked.
  24169. */
  24170. SimulateIOError( return SQLITE_ERROR );
  24171. assert( pVfs->mxPathname==MAX_PATHNAME );
  24172. UNUSED_PARAMETER(pVfs);
  24173. zOut[nOut-1] = '\0';
  24174. if( zPath[0]=='/' ){
  24175. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  24176. }else{
  24177. int nCwd;
  24178. if( getcwd(zOut, nOut-1)==0 ){
  24179. return SQLITE_CANTOPEN;
  24180. }
  24181. nCwd = (int)strlen(zOut);
  24182. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  24183. }
  24184. return SQLITE_OK;
  24185. }
  24186. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  24187. /*
  24188. ** Interfaces for opening a shared library, finding entry points
  24189. ** within the shared library, and closing the shared library.
  24190. */
  24191. #include <dlfcn.h>
  24192. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  24193. UNUSED_PARAMETER(NotUsed);
  24194. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  24195. }
  24196. /*
  24197. ** SQLite calls this function immediately after a call to unixDlSym() or
  24198. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  24199. ** message is available, it is written to zBufOut. If no error message
  24200. ** is available, zBufOut is left unmodified and SQLite uses a default
  24201. ** error message.
  24202. */
  24203. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  24204. char *zErr;
  24205. UNUSED_PARAMETER(NotUsed);
  24206. unixEnterMutex();
  24207. zErr = dlerror();
  24208. if( zErr ){
  24209. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  24210. }
  24211. unixLeaveMutex();
  24212. }
  24213. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  24214. /*
  24215. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  24216. ** cast into a pointer to a function. And yet the library dlsym() routine
  24217. ** returns a void* which is really a pointer to a function. So how do we
  24218. ** use dlsym() with -pedantic-errors?
  24219. **
  24220. ** Variable x below is defined to be a pointer to a function taking
  24221. ** parameters void* and const char* and returning a pointer to a function.
  24222. ** We initialize x by assigning it a pointer to the dlsym() function.
  24223. ** (That assignment requires a cast.) Then we call the function that
  24224. ** x points to.
  24225. **
  24226. ** This work-around is unlikely to work correctly on any system where
  24227. ** you really cannot cast a function pointer into void*. But then, on the
  24228. ** other hand, dlsym() will not work on such a system either, so we have
  24229. ** not really lost anything.
  24230. */
  24231. void (*(*x)(void*,const char*))(void);
  24232. UNUSED_PARAMETER(NotUsed);
  24233. x = (void(*(*)(void*,const char*))(void))dlsym;
  24234. return (*x)(p, zSym);
  24235. }
  24236. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  24237. UNUSED_PARAMETER(NotUsed);
  24238. dlclose(pHandle);
  24239. }
  24240. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  24241. #define unixDlOpen 0
  24242. #define unixDlError 0
  24243. #define unixDlSym 0
  24244. #define unixDlClose 0
  24245. #endif
  24246. /*
  24247. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  24248. */
  24249. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  24250. UNUSED_PARAMETER(NotUsed);
  24251. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  24252. /* We have to initialize zBuf to prevent valgrind from reporting
  24253. ** errors. The reports issued by valgrind are incorrect - we would
  24254. ** prefer that the randomness be increased by making use of the
  24255. ** uninitialized space in zBuf - but valgrind errors tend to worry
  24256. ** some users. Rather than argue, it seems easier just to initialize
  24257. ** the whole array and silence valgrind, even if that means less randomness
  24258. ** in the random seed.
  24259. **
  24260. ** When testing, initializing zBuf[] to zero is all we do. That means
  24261. ** that we always use the same random number sequence. This makes the
  24262. ** tests repeatable.
  24263. */
  24264. memset(zBuf, 0, nBuf);
  24265. #if !defined(SQLITE_TEST)
  24266. {
  24267. int pid, fd;
  24268. fd = open("/dev/urandom", O_RDONLY);
  24269. if( fd<0 ){
  24270. time_t t;
  24271. time(&t);
  24272. memcpy(zBuf, &t, sizeof(t));
  24273. pid = getpid();
  24274. memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
  24275. assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
  24276. nBuf = sizeof(t) + sizeof(pid);
  24277. }else{
  24278. nBuf = read(fd, zBuf, nBuf);
  24279. close(fd);
  24280. }
  24281. }
  24282. #endif
  24283. return nBuf;
  24284. }
  24285. /*
  24286. ** Sleep for a little while. Return the amount of time slept.
  24287. ** The argument is the number of microseconds we want to sleep.
  24288. ** The return value is the number of microseconds of sleep actually
  24289. ** requested from the underlying operating system, a number which
  24290. ** might be greater than or equal to the argument, but not less
  24291. ** than the argument.
  24292. */
  24293. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  24294. #if OS_VXWORKS
  24295. struct timespec sp;
  24296. sp.tv_sec = microseconds / 1000000;
  24297. sp.tv_nsec = (microseconds % 1000000) * 1000;
  24298. nanosleep(&sp, NULL);
  24299. return microseconds;
  24300. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  24301. usleep(microseconds);
  24302. return microseconds;
  24303. #else
  24304. int seconds = (microseconds+999999)/1000000;
  24305. sleep(seconds);
  24306. return seconds*1000000;
  24307. #endif
  24308. UNUSED_PARAMETER(NotUsed);
  24309. }
  24310. /*
  24311. ** The following variable, if set to a non-zero value, is interpreted as
  24312. ** the number of seconds since 1970 and is used to set the result of
  24313. ** sqlite3OsCurrentTime() during testing.
  24314. */
  24315. #ifdef SQLITE_TEST
  24316. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  24317. #endif
  24318. /*
  24319. ** Find the current time (in Universal Coordinated Time). Write the
  24320. ** current time and date as a Julian Day number into *prNow and
  24321. ** return 0. Return 1 if the time and date cannot be found.
  24322. */
  24323. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  24324. #if defined(NO_GETTOD)
  24325. time_t t;
  24326. time(&t);
  24327. *prNow = t/86400.0 + 2440587.5;
  24328. #elif OS_VXWORKS
  24329. struct timespec sNow;
  24330. clock_gettime(CLOCK_REALTIME, &sNow);
  24331. *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
  24332. #else
  24333. struct timeval sNow;
  24334. gettimeofday(&sNow, 0);
  24335. *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
  24336. #endif
  24337. #ifdef SQLITE_TEST
  24338. if( sqlite3_current_time ){
  24339. *prNow = sqlite3_current_time/86400.0 + 2440587.5;
  24340. }
  24341. #endif
  24342. UNUSED_PARAMETER(NotUsed);
  24343. return 0;
  24344. }
  24345. /*
  24346. ** We added the xGetLastError() method with the intention of providing
  24347. ** better low-level error messages when operating-system problems come up
  24348. ** during SQLite operation. But so far, none of that has been implemented
  24349. ** in the core. So this routine is never called. For now, it is merely
  24350. ** a place-holder.
  24351. */
  24352. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  24353. UNUSED_PARAMETER(NotUsed);
  24354. UNUSED_PARAMETER(NotUsed2);
  24355. UNUSED_PARAMETER(NotUsed3);
  24356. return 0;
  24357. }
  24358. /*
  24359. ************************ End of sqlite3_vfs methods ***************************
  24360. ******************************************************************************/
  24361. /******************************************************************************
  24362. ************************** Begin Proxy Locking ********************************
  24363. **
  24364. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  24365. ** other locking methods on secondary lock files. Proxy locking is a
  24366. ** meta-layer over top of the primitive locking implemented above. For
  24367. ** this reason, the division that implements of proxy locking is deferred
  24368. ** until late in the file (here) after all of the other I/O methods have
  24369. ** been defined - so that the primitive locking methods are available
  24370. ** as services to help with the implementation of proxy locking.
  24371. **
  24372. ****
  24373. **
  24374. ** The default locking schemes in SQLite use byte-range locks on the
  24375. ** database file to coordinate safe, concurrent access by multiple readers
  24376. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  24377. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  24378. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  24379. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  24380. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  24381. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  24382. ** address in the shared range is taken for a SHARED lock, the entire
  24383. ** shared range is taken for an EXCLUSIVE lock):
  24384. **
  24385. ** PENDING_BYTE 0x40000000
  24386. ** RESERVED_BYTE 0x40000001
  24387. ** SHARED_RANGE 0x40000002 -> 0x40000200
  24388. **
  24389. ** This works well on the local file system, but shows a nearly 100x
  24390. ** slowdown in read performance on AFP because the AFP client disables
  24391. ** the read cache when byte-range locks are present. Enabling the read
  24392. ** cache exposes a cache coherency problem that is present on all OS X
  24393. ** supported network file systems. NFS and AFP both observe the
  24394. ** close-to-open semantics for ensuring cache coherency
  24395. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  24396. ** address the requirements for concurrent database access by multiple
  24397. ** readers and writers
  24398. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  24399. **
  24400. ** To address the performance and cache coherency issues, proxy file locking
  24401. ** changes the way database access is controlled by limiting access to a
  24402. ** single host at a time and moving file locks off of the database file
  24403. ** and onto a proxy file on the local file system.
  24404. **
  24405. **
  24406. ** Using proxy locks
  24407. ** -----------------
  24408. **
  24409. ** C APIs
  24410. **
  24411. ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
  24412. ** <proxy_path> | ":auto:");
  24413. ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
  24414. **
  24415. **
  24416. ** SQL pragmas
  24417. **
  24418. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  24419. ** PRAGMA [database.]lock_proxy_file
  24420. **
  24421. ** Specifying ":auto:" means that if there is a conch file with a matching
  24422. ** host ID in it, the proxy path in the conch file will be used, otherwise
  24423. ** a proxy path based on the user's temp dir
  24424. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  24425. ** actual proxy file name is generated from the name and path of the
  24426. ** database file. For example:
  24427. **
  24428. ** For database path "/Users/me/foo.db"
  24429. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  24430. **
  24431. ** Once a lock proxy is configured for a database connection, it can not
  24432. ** be removed, however it may be switched to a different proxy path via
  24433. ** the above APIs (assuming the conch file is not being held by another
  24434. ** connection or process).
  24435. **
  24436. **
  24437. ** How proxy locking works
  24438. ** -----------------------
  24439. **
  24440. ** Proxy file locking relies primarily on two new supporting files:
  24441. **
  24442. ** * conch file to limit access to the database file to a single host
  24443. ** at a time
  24444. **
  24445. ** * proxy file to act as a proxy for the advisory locks normally
  24446. ** taken on the database
  24447. **
  24448. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  24449. ** by taking an sqlite-style shared lock on the conch file, reading the
  24450. ** contents and comparing the host's unique host ID (see below) and lock
  24451. ** proxy path against the values stored in the conch. The conch file is
  24452. ** stored in the same directory as the database file and the file name
  24453. ** is patterned after the database file name as ".<databasename>-conch".
  24454. ** If the conch file does not exist, or it's contents do not match the
  24455. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  24456. ** lock and the conch file contents is updated with the host ID and proxy
  24457. ** path and the lock is downgraded to a shared lock again. If the conch
  24458. ** is held by another process (with a shared lock), the exclusive lock
  24459. ** will fail and SQLITE_BUSY is returned.
  24460. **
  24461. ** The proxy file - a single-byte file used for all advisory file locks
  24462. ** normally taken on the database file. This allows for safe sharing
  24463. ** of the database file for multiple readers and writers on the same
  24464. ** host (the conch ensures that they all use the same local lock file).
  24465. **
  24466. ** There is a third file - the host ID file - used as a persistent record
  24467. ** of a unique identifier for the host, a 128-byte unique host id file
  24468. ** in the path defined by the HOSTIDPATH macro (default value is
  24469. ** /Library/Caches/.com.apple.sqliteConchHostId).
  24470. **
  24471. ** Requesting the lock proxy does not immediately take the conch, it is
  24472. ** only taken when the first request to lock database file is made.
  24473. ** This matches the semantics of the traditional locking behavior, where
  24474. ** opening a connection to a database file does not take a lock on it.
  24475. ** The shared lock and an open file descriptor are maintained until
  24476. ** the connection to the database is closed.
  24477. **
  24478. ** The proxy file and the lock file are never deleted so they only need
  24479. ** to be created the first time they are used.
  24480. **
  24481. ** Configuration options
  24482. ** ---------------------
  24483. **
  24484. ** SQLITE_PREFER_PROXY_LOCKING
  24485. **
  24486. ** Database files accessed on non-local file systems are
  24487. ** automatically configured for proxy locking, lock files are
  24488. ** named automatically using the same logic as
  24489. ** PRAGMA lock_proxy_file=":auto:"
  24490. **
  24491. ** SQLITE_PROXY_DEBUG
  24492. **
  24493. ** Enables the logging of error messages during host id file
  24494. ** retrieval and creation
  24495. **
  24496. ** HOSTIDPATH
  24497. **
  24498. ** Overrides the default host ID file path location
  24499. **
  24500. ** LOCKPROXYDIR
  24501. **
  24502. ** Overrides the default directory used for lock proxy files that
  24503. ** are named automatically via the ":auto:" setting
  24504. **
  24505. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  24506. **
  24507. ** Permissions to use when creating a directory for storing the
  24508. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  24509. **
  24510. **
  24511. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  24512. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  24513. ** force proxy locking to be used for every database file opened, and 0
  24514. ** will force automatic proxy locking to be disabled for all database
  24515. ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
  24516. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  24517. */
  24518. /*
  24519. ** Proxy locking is only available on MacOSX
  24520. */
  24521. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  24522. #ifdef SQLITE_TEST
  24523. /* simulate multiple hosts by creating unique hostid file paths */
  24524. SQLITE_API int sqlite3_hostid_num = 0;
  24525. #endif
  24526. /*
  24527. ** The proxyLockingContext has the path and file structures for the remote
  24528. ** and local proxy files in it
  24529. */
  24530. typedef struct proxyLockingContext proxyLockingContext;
  24531. struct proxyLockingContext {
  24532. unixFile *conchFile; /* Open conch file */
  24533. char *conchFilePath; /* Name of the conch file */
  24534. unixFile *lockProxy; /* Open proxy lock file */
  24535. char *lockProxyPath; /* Name of the proxy lock file */
  24536. char *dbPath; /* Name of the open file */
  24537. int conchHeld; /* True if the conch is currently held */
  24538. void *oldLockingContext; /* Original lockingcontext to restore on close */
  24539. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  24540. };
  24541. /* HOSTIDLEN and CONCHLEN both include space for the string
  24542. ** terminating nul
  24543. */
  24544. #define HOSTIDLEN 128
  24545. #define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
  24546. #ifndef HOSTIDPATH
  24547. # define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
  24548. #endif
  24549. /* basically a copy of unixRandomness with different
  24550. ** test behavior built in */
  24551. static int proxyGenerateHostID(char *pHostID){
  24552. int pid, fd, len;
  24553. unsigned char *key = (unsigned char *)pHostID;
  24554. memset(key, 0, HOSTIDLEN);
  24555. len = 0;
  24556. fd = open("/dev/urandom", O_RDONLY);
  24557. if( fd>=0 ){
  24558. len = read(fd, key, HOSTIDLEN);
  24559. close(fd); /* silently leak the fd if it fails */
  24560. }
  24561. if( len < HOSTIDLEN ){
  24562. time_t t;
  24563. time(&t);
  24564. memcpy(key, &t, sizeof(t));
  24565. pid = getpid();
  24566. memcpy(&key[sizeof(t)], &pid, sizeof(pid));
  24567. }
  24568. #ifdef MAKE_PRETTY_HOSTID
  24569. {
  24570. int i;
  24571. /* filter the bytes into printable ascii characters and NUL terminate */
  24572. key[(HOSTIDLEN-1)] = 0x00;
  24573. for( i=0; i<(HOSTIDLEN-1); i++ ){
  24574. unsigned char pa = key[i]&0x7F;
  24575. if( pa<0x20 ){
  24576. key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
  24577. }else if( pa==0x7F ){
  24578. key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
  24579. }
  24580. }
  24581. }
  24582. #endif
  24583. return SQLITE_OK;
  24584. }
  24585. /* writes the host id path to path, path should be an pre-allocated buffer
  24586. ** with enough space for a path
  24587. */
  24588. static void proxyGetHostIDPath(char *path, size_t len){
  24589. strlcpy(path, HOSTIDPATH, len);
  24590. #ifdef SQLITE_TEST
  24591. if( sqlite3_hostid_num>0 ){
  24592. char suffix[2] = "1";
  24593. suffix[0] = suffix[0] + sqlite3_hostid_num;
  24594. strlcat(path, suffix, len);
  24595. }
  24596. #endif
  24597. OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
  24598. }
  24599. /* get the host ID from a sqlite hostid file stored in the
  24600. ** user-specific tmp directory, create the ID if it's not there already
  24601. */
  24602. static int proxyGetHostID(char *pHostID, int *pError){
  24603. int fd;
  24604. char path[MAXPATHLEN];
  24605. size_t len;
  24606. int rc=SQLITE_OK;
  24607. proxyGetHostIDPath(path, MAXPATHLEN);
  24608. /* try to create the host ID file, if it already exists read the contents */
  24609. fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
  24610. if( fd<0 ){
  24611. int err=errno;
  24612. if( err!=EEXIST ){
  24613. #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
  24614. fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
  24615. path, strerror(err));
  24616. #endif
  24617. return SQLITE_PERM;
  24618. }
  24619. /* couldn't create the file, read it instead */
  24620. fd = open(path, O_RDONLY|O_EXCL);
  24621. if( fd<0 ){
  24622. #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
  24623. int err = errno;
  24624. fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
  24625. path, strerror(err));
  24626. #endif
  24627. return SQLITE_PERM;
  24628. }
  24629. len = pread(fd, pHostID, HOSTIDLEN, 0);
  24630. if( len<0 ){
  24631. *pError = errno;
  24632. rc = SQLITE_IOERR_READ;
  24633. }else if( len<HOSTIDLEN ){
  24634. *pError = 0;
  24635. rc = SQLITE_IOERR_SHORT_READ;
  24636. }
  24637. close(fd); /* silently leak the fd if it fails */
  24638. OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
  24639. return rc;
  24640. }else{
  24641. /* we're creating the host ID file (use a random string of bytes) */
  24642. proxyGenerateHostID(pHostID);
  24643. len = pwrite(fd, pHostID, HOSTIDLEN, 0);
  24644. if( len<0 ){
  24645. *pError = errno;
  24646. rc = SQLITE_IOERR_WRITE;
  24647. }else if( len<HOSTIDLEN ){
  24648. *pError = 0;
  24649. rc = SQLITE_IOERR_WRITE;
  24650. }
  24651. close(fd); /* silently leak the fd if it fails */
  24652. OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
  24653. return rc;
  24654. }
  24655. }
  24656. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  24657. int len;
  24658. int dbLen;
  24659. int i;
  24660. #ifdef LOCKPROXYDIR
  24661. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  24662. #else
  24663. # ifdef _CS_DARWIN_USER_TEMP_DIR
  24664. {
  24665. confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
  24666. len = strlcat(lPath, "sqliteplocks", maxLen);
  24667. if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  24668. /* if mkdir fails, handle as lock file creation failure */
  24669. int err = errno;
  24670. # ifdef SQLITE_DEBUG
  24671. if( err!=EEXIST ){
  24672. fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
  24673. SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
  24674. }
  24675. # endif
  24676. }else{
  24677. OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
  24678. }
  24679. }
  24680. # else
  24681. len = strlcpy(lPath, "/tmp/", maxLen);
  24682. # endif
  24683. #endif
  24684. if( lPath[len-1]!='/' ){
  24685. len = strlcat(lPath, "/", maxLen);
  24686. }
  24687. /* transform the db path to a unique cache name */
  24688. dbLen = (int)strlen(dbPath);
  24689. for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
  24690. char c = dbPath[i];
  24691. lPath[i+len] = (c=='/')?'_':c;
  24692. }
  24693. lPath[i+len]='\0';
  24694. strlcat(lPath, ":auto:", maxLen);
  24695. return SQLITE_OK;
  24696. }
  24697. /*
  24698. ** Create a new VFS file descriptor (stored in memory obtained from
  24699. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  24700. **
  24701. ** The caller is responsible not only for closing the file descriptor
  24702. ** but also for freeing the memory associated with the file descriptor.
  24703. */
  24704. static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
  24705. int fd;
  24706. int dirfd = -1;
  24707. unixFile *pNew;
  24708. int rc = SQLITE_OK;
  24709. sqlite3_vfs dummyVfs;
  24710. fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
  24711. if( fd<0 ){
  24712. return SQLITE_CANTOPEN;
  24713. }
  24714. pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
  24715. if( pNew==NULL ){
  24716. rc = SQLITE_NOMEM;
  24717. goto end_create_proxy;
  24718. }
  24719. memset(pNew, 0, sizeof(unixFile));
  24720. dummyVfs.pAppData = (void*)&autolockIoFinder;
  24721. rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
  24722. if( rc==SQLITE_OK ){
  24723. *ppFile = pNew;
  24724. return SQLITE_OK;
  24725. }
  24726. end_create_proxy:
  24727. close(fd); /* silently leak fd if error, we're already in error */
  24728. sqlite3_free(pNew);
  24729. return rc;
  24730. }
  24731. /* takes the conch by taking a shared lock and read the contents conch, if
  24732. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  24733. ** lockPath means that the lockPath in the conch file will be used if the
  24734. ** host IDs match, or a new lock path will be generated automatically
  24735. ** and written to the conch file.
  24736. */
  24737. static int proxyTakeConch(unixFile *pFile){
  24738. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  24739. if( pCtx->conchHeld>0 ){
  24740. return SQLITE_OK;
  24741. }else{
  24742. unixFile *conchFile = pCtx->conchFile;
  24743. char testValue[CONCHLEN];
  24744. char conchValue[CONCHLEN];
  24745. char lockPath[MAXPATHLEN];
  24746. char *tLockPath = NULL;
  24747. int rc = SQLITE_OK;
  24748. int readRc = SQLITE_OK;
  24749. int syncPerms = 0;
  24750. OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  24751. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
  24752. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  24753. if( rc==SQLITE_OK ){
  24754. int pError = 0;
  24755. memset(testValue, 0, CONCHLEN); /* conch is fixed size */
  24756. rc = proxyGetHostID(testValue, &pError);
  24757. if( (rc&0xff)==SQLITE_IOERR ){
  24758. pFile->lastErrno = pError;
  24759. }
  24760. if( pCtx->lockProxyPath ){
  24761. strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
  24762. }
  24763. }
  24764. if( rc!=SQLITE_OK ){
  24765. goto end_takeconch;
  24766. }
  24767. readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
  24768. if( readRc!=SQLITE_IOERR_SHORT_READ ){
  24769. if( readRc!=SQLITE_OK ){
  24770. if( (rc&0xff)==SQLITE_IOERR ){
  24771. pFile->lastErrno = conchFile->lastErrno;
  24772. }
  24773. rc = readRc;
  24774. goto end_takeconch;
  24775. }
  24776. /* if the conch has data compare the contents */
  24777. if( !pCtx->lockProxyPath ){
  24778. /* for auto-named local lock file, just check the host ID and we'll
  24779. ** use the local lock file path that's already in there */
  24780. if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
  24781. tLockPath = (char *)&conchValue[HOSTIDLEN];
  24782. goto end_takeconch;
  24783. }
  24784. }else{
  24785. /* we've got the conch if conchValue matches our path and host ID */
  24786. if( !memcmp(testValue, conchValue, CONCHLEN) ){
  24787. goto end_takeconch;
  24788. }
  24789. }
  24790. }else{
  24791. /* a short read means we're "creating" the conch (even though it could
  24792. ** have been user-intervention), if we acquire the exclusive lock,
  24793. ** we'll try to match the current on-disk permissions of the database
  24794. */
  24795. syncPerms = 1;
  24796. }
  24797. /* either conch was emtpy or didn't match */
  24798. if( !pCtx->lockProxyPath ){
  24799. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  24800. tLockPath = lockPath;
  24801. strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
  24802. }
  24803. /* update conch with host and path (this will fail if other process
  24804. ** has a shared lock already) */
  24805. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
  24806. if( rc==SQLITE_OK ){
  24807. rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
  24808. if( rc==SQLITE_OK && syncPerms ){
  24809. struct stat buf;
  24810. int err = fstat(pFile->h, &buf);
  24811. if( err==0 ){
  24812. /* try to match the database file permissions, ignore failure */
  24813. #ifndef SQLITE_PROXY_DEBUG
  24814. fchmod(conchFile->h, buf.st_mode);
  24815. #else
  24816. if( fchmod(conchFile->h, buf.st_mode)!=0 ){
  24817. int code = errno;
  24818. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  24819. buf.st_mode, code, strerror(code));
  24820. } else {
  24821. fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
  24822. }
  24823. }else{
  24824. int code = errno;
  24825. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  24826. err, code, strerror(code));
  24827. #endif
  24828. }
  24829. }
  24830. }
  24831. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  24832. end_takeconch:
  24833. OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
  24834. if( rc==SQLITE_OK && pFile->openFlags ){
  24835. if( pFile->h>=0 ){
  24836. #ifdef STRICT_CLOSE_ERROR
  24837. if( close(pFile->h) ){
  24838. pFile->lastErrno = errno;
  24839. return SQLITE_IOERR_CLOSE;
  24840. }
  24841. #else
  24842. close(pFile->h); /* silently leak fd if fail */
  24843. #endif
  24844. }
  24845. pFile->h = -1;
  24846. int fd = open(pCtx->dbPath, pFile->openFlags,
  24847. SQLITE_DEFAULT_FILE_PERMISSIONS);
  24848. OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
  24849. if( fd>=0 ){
  24850. pFile->h = fd;
  24851. }else{
  24852. rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
  24853. during locking */
  24854. }
  24855. }
  24856. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  24857. char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
  24858. /* ACS: Need to make a copy of path sometimes */
  24859. rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
  24860. }
  24861. if( rc==SQLITE_OK ){
  24862. pCtx->conchHeld = 1;
  24863. if( tLockPath ){
  24864. pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
  24865. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  24866. ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
  24867. pCtx->lockProxyPath;
  24868. }
  24869. }
  24870. } else {
  24871. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  24872. }
  24873. OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
  24874. return rc;
  24875. }
  24876. }
  24877. /*
  24878. ** If pFile holds a lock on a conch file, then release that lock.
  24879. */
  24880. static int proxyReleaseConch(unixFile *pFile){
  24881. int rc; /* Subroutine return code */
  24882. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  24883. unixFile *conchFile; /* Name of the conch file */
  24884. pCtx = (proxyLockingContext *)pFile->lockingContext;
  24885. conchFile = pCtx->conchFile;
  24886. OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  24887. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  24888. getpid());
  24889. pCtx->conchHeld = 0;
  24890. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  24891. OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
  24892. (rc==SQLITE_OK ? "ok" : "failed"));
  24893. return rc;
  24894. }
  24895. /*
  24896. ** Given the name of a database file, compute the name of its conch file.
  24897. ** Store the conch filename in memory obtained from sqlite3_malloc().
  24898. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  24899. ** or SQLITE_NOMEM if unable to obtain memory.
  24900. **
  24901. ** The caller is responsible for ensuring that the allocated memory
  24902. ** space is eventually freed.
  24903. **
  24904. ** *pConchPath is set to NULL if a memory allocation error occurs.
  24905. */
  24906. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  24907. int i; /* Loop counter */
  24908. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  24909. char *conchPath; /* buffer in which to construct conch name */
  24910. /* Allocate space for the conch filename and initialize the name to
  24911. ** the name of the original database file. */
  24912. *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  24913. if( conchPath==0 ){
  24914. return SQLITE_NOMEM;
  24915. }
  24916. memcpy(conchPath, dbPath, len+1);
  24917. /* now insert a "." before the last / character */
  24918. for( i=(len-1); i>=0; i-- ){
  24919. if( conchPath[i]=='/' ){
  24920. i++;
  24921. break;
  24922. }
  24923. }
  24924. conchPath[i]='.';
  24925. while ( i<len ){
  24926. conchPath[i+1]=dbPath[i];
  24927. i++;
  24928. }
  24929. /* append the "-conch" suffix to the file */
  24930. memcpy(&conchPath[i+1], "-conch", 7);
  24931. assert( (int)strlen(conchPath) == len+7 );
  24932. return SQLITE_OK;
  24933. }
  24934. /* Takes a fully configured proxy locking-style unix file and switches
  24935. ** the local lock file path
  24936. */
  24937. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  24938. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  24939. char *oldPath = pCtx->lockProxyPath;
  24940. int rc = SQLITE_OK;
  24941. if( pFile->locktype!=NO_LOCK ){
  24942. return SQLITE_BUSY;
  24943. }
  24944. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  24945. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  24946. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  24947. return SQLITE_OK;
  24948. }else{
  24949. unixFile *lockProxy = pCtx->lockProxy;
  24950. pCtx->lockProxy=NULL;
  24951. pCtx->conchHeld = 0;
  24952. if( lockProxy!=NULL ){
  24953. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  24954. if( rc ) return rc;
  24955. sqlite3_free(lockProxy);
  24956. }
  24957. sqlite3_free(oldPath);
  24958. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  24959. }
  24960. return rc;
  24961. }
  24962. /*
  24963. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  24964. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  24965. **
  24966. ** This routine find the filename associated with pFile and writes it
  24967. ** int dbPath.
  24968. */
  24969. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  24970. #if defined(__APPLE__)
  24971. if( pFile->pMethod == &afpIoMethods ){
  24972. /* afp style keeps a reference to the db path in the filePath field
  24973. ** of the struct */
  24974. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  24975. strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
  24976. }else
  24977. #endif
  24978. if( pFile->pMethod == &dotlockIoMethods ){
  24979. /* dot lock style uses the locking context to store the dot lock
  24980. ** file path */
  24981. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  24982. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  24983. }else{
  24984. /* all other styles use the locking context to store the db file path */
  24985. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  24986. strcpy(dbPath, (char *)pFile->lockingContext);
  24987. }
  24988. return SQLITE_OK;
  24989. }
  24990. /*
  24991. ** Takes an already filled in unix file and alters it so all file locking
  24992. ** will be performed on the local proxy lock file. The following fields
  24993. ** are preserved in the locking context so that they can be restored and
  24994. ** the unix structure properly cleaned up at close time:
  24995. ** ->lockingContext
  24996. ** ->pMethod
  24997. */
  24998. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  24999. proxyLockingContext *pCtx;
  25000. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  25001. char *lockPath=NULL;
  25002. int rc = SQLITE_OK;
  25003. if( pFile->locktype!=NO_LOCK ){
  25004. return SQLITE_BUSY;
  25005. }
  25006. proxyGetDbPathForUnixFile(pFile, dbPath);
  25007. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  25008. lockPath=NULL;
  25009. }else{
  25010. lockPath=(char *)path;
  25011. }
  25012. OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  25013. (lockPath ? lockPath : ":auto:"), getpid());
  25014. pCtx = sqlite3_malloc( sizeof(*pCtx) );
  25015. if( pCtx==0 ){
  25016. return SQLITE_NOMEM;
  25017. }
  25018. memset(pCtx, 0, sizeof(*pCtx));
  25019. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  25020. if( rc==SQLITE_OK ){
  25021. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
  25022. }
  25023. if( rc==SQLITE_OK && lockPath ){
  25024. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  25025. }
  25026. if( rc==SQLITE_OK ){
  25027. /* all memory is allocated, proxys are created and assigned,
  25028. ** switch the locking context and pMethod then return.
  25029. */
  25030. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  25031. pCtx->oldLockingContext = pFile->lockingContext;
  25032. pFile->lockingContext = pCtx;
  25033. pCtx->pOldMethod = pFile->pMethod;
  25034. pFile->pMethod = &proxyIoMethods;
  25035. }else{
  25036. if( pCtx->conchFile ){
  25037. rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  25038. if( rc ) return rc;
  25039. sqlite3_free(pCtx->conchFile);
  25040. }
  25041. sqlite3_free(pCtx->conchFilePath);
  25042. sqlite3_free(pCtx);
  25043. }
  25044. OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
  25045. (rc==SQLITE_OK ? "ok" : "failed"));
  25046. return rc;
  25047. }
  25048. /*
  25049. ** This routine handles sqlite3_file_control() calls that are specific
  25050. ** to proxy locking.
  25051. */
  25052. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  25053. switch( op ){
  25054. case SQLITE_GET_LOCKPROXYFILE: {
  25055. unixFile *pFile = (unixFile*)id;
  25056. if( pFile->pMethod == &proxyIoMethods ){
  25057. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  25058. proxyTakeConch(pFile);
  25059. if( pCtx->lockProxyPath ){
  25060. *(const char **)pArg = pCtx->lockProxyPath;
  25061. }else{
  25062. *(const char **)pArg = ":auto: (not held)";
  25063. }
  25064. } else {
  25065. *(const char **)pArg = NULL;
  25066. }
  25067. return SQLITE_OK;
  25068. }
  25069. case SQLITE_SET_LOCKPROXYFILE: {
  25070. unixFile *pFile = (unixFile*)id;
  25071. int rc = SQLITE_OK;
  25072. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  25073. if( pArg==NULL || (const char *)pArg==0 ){
  25074. if( isProxyStyle ){
  25075. /* turn off proxy locking - not supported */
  25076. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  25077. }else{
  25078. /* turn off proxy locking - already off - NOOP */
  25079. rc = SQLITE_OK;
  25080. }
  25081. }else{
  25082. const char *proxyPath = (const char *)pArg;
  25083. if( isProxyStyle ){
  25084. proxyLockingContext *pCtx =
  25085. (proxyLockingContext*)pFile->lockingContext;
  25086. if( !strcmp(pArg, ":auto:")
  25087. || (pCtx->lockProxyPath &&
  25088. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  25089. ){
  25090. rc = SQLITE_OK;
  25091. }else{
  25092. rc = switchLockProxyPath(pFile, proxyPath);
  25093. }
  25094. }else{
  25095. /* turn on proxy file locking */
  25096. rc = proxyTransformUnixFile(pFile, proxyPath);
  25097. }
  25098. }
  25099. return rc;
  25100. }
  25101. default: {
  25102. assert( 0 ); /* The call assures that only valid opcodes are sent */
  25103. }
  25104. }
  25105. /*NOTREACHED*/
  25106. return SQLITE_ERROR;
  25107. }
  25108. /*
  25109. ** Within this division (the proxying locking implementation) the procedures
  25110. ** above this point are all utilities. The lock-related methods of the
  25111. ** proxy-locking sqlite3_io_method object follow.
  25112. */
  25113. /*
  25114. ** This routine checks if there is a RESERVED lock held on the specified
  25115. ** file by this or any other process. If such a lock is held, set *pResOut
  25116. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  25117. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  25118. */
  25119. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  25120. unixFile *pFile = (unixFile*)id;
  25121. int rc = proxyTakeConch(pFile);
  25122. if( rc==SQLITE_OK ){
  25123. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  25124. unixFile *proxy = pCtx->lockProxy;
  25125. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  25126. }
  25127. return rc;
  25128. }
  25129. /*
  25130. ** Lock the file with the lock specified by parameter locktype - one
  25131. ** of the following:
  25132. **
  25133. ** (1) SHARED_LOCK
  25134. ** (2) RESERVED_LOCK
  25135. ** (3) PENDING_LOCK
  25136. ** (4) EXCLUSIVE_LOCK
  25137. **
  25138. ** Sometimes when requesting one lock state, additional lock states
  25139. ** are inserted in between. The locking might fail on one of the later
  25140. ** transitions leaving the lock state different from what it started but
  25141. ** still short of its goal. The following chart shows the allowed
  25142. ** transitions and the inserted intermediate states:
  25143. **
  25144. ** UNLOCKED -> SHARED
  25145. ** SHARED -> RESERVED
  25146. ** SHARED -> (PENDING) -> EXCLUSIVE
  25147. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25148. ** PENDING -> EXCLUSIVE
  25149. **
  25150. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  25151. ** routine to lower a locking level.
  25152. */
  25153. static int proxyLock(sqlite3_file *id, int locktype) {
  25154. unixFile *pFile = (unixFile*)id;
  25155. int rc = proxyTakeConch(pFile);
  25156. if( rc==SQLITE_OK ){
  25157. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  25158. unixFile *proxy = pCtx->lockProxy;
  25159. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
  25160. pFile->locktype = proxy->locktype;
  25161. }
  25162. return rc;
  25163. }
  25164. /*
  25165. ** Lower the locking level on file descriptor pFile to locktype. locktype
  25166. ** must be either NO_LOCK or SHARED_LOCK.
  25167. **
  25168. ** If the locking level of the file descriptor is already at or below
  25169. ** the requested locking level, this routine is a no-op.
  25170. */
  25171. static int proxyUnlock(sqlite3_file *id, int locktype) {
  25172. unixFile *pFile = (unixFile*)id;
  25173. int rc = proxyTakeConch(pFile);
  25174. if( rc==SQLITE_OK ){
  25175. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  25176. unixFile *proxy = pCtx->lockProxy;
  25177. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
  25178. pFile->locktype = proxy->locktype;
  25179. }
  25180. return rc;
  25181. }
  25182. /*
  25183. ** Close a file that uses proxy locks.
  25184. */
  25185. static int proxyClose(sqlite3_file *id) {
  25186. if( id ){
  25187. unixFile *pFile = (unixFile*)id;
  25188. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  25189. unixFile *lockProxy = pCtx->lockProxy;
  25190. unixFile *conchFile = pCtx->conchFile;
  25191. int rc = SQLITE_OK;
  25192. if( lockProxy ){
  25193. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  25194. if( rc ) return rc;
  25195. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  25196. if( rc ) return rc;
  25197. sqlite3_free(lockProxy);
  25198. pCtx->lockProxy = 0;
  25199. }
  25200. if( conchFile ){
  25201. if( pCtx->conchHeld ){
  25202. rc = proxyReleaseConch(pFile);
  25203. if( rc ) return rc;
  25204. }
  25205. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  25206. if( rc ) return rc;
  25207. sqlite3_free(conchFile);
  25208. }
  25209. sqlite3_free(pCtx->lockProxyPath);
  25210. sqlite3_free(pCtx->conchFilePath);
  25211. sqlite3_free(pCtx->dbPath);
  25212. /* restore the original locking context and pMethod then close it */
  25213. pFile->lockingContext = pCtx->oldLockingContext;
  25214. pFile->pMethod = pCtx->pOldMethod;
  25215. sqlite3_free(pCtx);
  25216. return pFile->pMethod->xClose(id);
  25217. }
  25218. return SQLITE_OK;
  25219. }
  25220. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25221. /*
  25222. ** The proxy locking style is intended for use with AFP filesystems.
  25223. ** And since AFP is only supported on MacOSX, the proxy locking is also
  25224. ** restricted to MacOSX.
  25225. **
  25226. **
  25227. ******************* End of the proxy lock implementation **********************
  25228. ******************************************************************************/
  25229. /*
  25230. ** Initialize the operating system interface.
  25231. **
  25232. ** This routine registers all VFS implementations for unix-like operating
  25233. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  25234. ** should be the only routines in this file that are visible from other
  25235. ** files.
  25236. **
  25237. ** This routine is called once during SQLite initialization and by a
  25238. ** single thread. The memory allocation and mutex subsystems have not
  25239. ** necessarily been initialized when this routine is called, and so they
  25240. ** should not be used.
  25241. */
  25242. SQLITE_API int sqlite3_os_init(void){
  25243. /*
  25244. ** The following macro defines an initializer for an sqlite3_vfs object.
  25245. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  25246. ** to the "finder" function. (pAppData is a pointer to a pointer because
  25247. ** silly C90 rules prohibit a void* from being cast to a function pointer
  25248. ** and so we have to go through the intermediate pointer to avoid problems
  25249. ** when compiling with -pedantic-errors on GCC.)
  25250. **
  25251. ** The FINDER parameter to this macro is the name of the pointer to the
  25252. ** finder-function. The finder-function returns a pointer to the
  25253. ** sqlite_io_methods object that implements the desired locking
  25254. ** behaviors. See the division above that contains the IOMETHODS
  25255. ** macro for addition information on finder-functions.
  25256. **
  25257. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  25258. ** object. But the "autolockIoFinder" available on MacOSX does a little
  25259. ** more than that; it looks at the filesystem type that hosts the
  25260. ** database file and tries to choose an locking method appropriate for
  25261. ** that filesystem time.
  25262. */
  25263. #define UNIXVFS(VFSNAME, FINDER) { \
  25264. 1, /* iVersion */ \
  25265. sizeof(unixFile), /* szOsFile */ \
  25266. MAX_PATHNAME, /* mxPathname */ \
  25267. 0, /* pNext */ \
  25268. VFSNAME, /* zName */ \
  25269. (void*)&FINDER, /* pAppData */ \
  25270. unixOpen, /* xOpen */ \
  25271. unixDelete, /* xDelete */ \
  25272. unixAccess, /* xAccess */ \
  25273. unixFullPathname, /* xFullPathname */ \
  25274. unixDlOpen, /* xDlOpen */ \
  25275. unixDlError, /* xDlError */ \
  25276. unixDlSym, /* xDlSym */ \
  25277. unixDlClose, /* xDlClose */ \
  25278. unixRandomness, /* xRandomness */ \
  25279. unixSleep, /* xSleep */ \
  25280. unixCurrentTime, /* xCurrentTime */ \
  25281. unixGetLastError /* xGetLastError */ \
  25282. }
  25283. /*
  25284. ** All default VFSes for unix are contained in the following array.
  25285. **
  25286. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  25287. ** by the SQLite core when the VFS is registered. So the following
  25288. ** array cannot be const.
  25289. */
  25290. static sqlite3_vfs aVfs[] = {
  25291. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25292. UNIXVFS("unix", autolockIoFinder ),
  25293. #else
  25294. UNIXVFS("unix", posixIoFinder ),
  25295. #endif
  25296. UNIXVFS("unix-none", nolockIoFinder ),
  25297. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  25298. #if OS_VXWORKS
  25299. UNIXVFS("unix-namedsem", semIoFinder ),
  25300. #endif
  25301. #if SQLITE_ENABLE_LOCKING_STYLE
  25302. UNIXVFS("unix-posix", posixIoFinder ),
  25303. UNIXVFS("unix-flock", flockIoFinder ),
  25304. #endif
  25305. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25306. UNIXVFS("unix-afp", afpIoFinder ),
  25307. UNIXVFS("unix-proxy", proxyIoFinder ),
  25308. #endif
  25309. };
  25310. unsigned int i; /* Loop counter */
  25311. /* Register all VFSes defined in the aVfs[] array */
  25312. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  25313. sqlite3_vfs_register(&aVfs[i], i==0);
  25314. }
  25315. return SQLITE_OK;
  25316. }
  25317. /*
  25318. ** Shutdown the operating system interface.
  25319. **
  25320. ** Some operating systems might need to do some cleanup in this routine,
  25321. ** to release dynamically allocated objects. But not on unix.
  25322. ** This routine is a no-op for unix.
  25323. */
  25324. SQLITE_API int sqlite3_os_end(void){
  25325. return SQLITE_OK;
  25326. }
  25327. #endif /* SQLITE_OS_UNIX */
  25328. /************** End of os_unix.c *********************************************/
  25329. /************** Begin file os_win.c ******************************************/
  25330. /*
  25331. ** 2004 May 22
  25332. **
  25333. ** The author disclaims copyright to this source code. In place of
  25334. ** a legal notice, here is a blessing:
  25335. **
  25336. ** May you do good and not evil.
  25337. ** May you find forgiveness for yourself and forgive others.
  25338. ** May you share freely, never taking more than you give.
  25339. **
  25340. ******************************************************************************
  25341. **
  25342. ** This file contains code that is specific to windows.
  25343. **
  25344. ** $Id: os_win.c,v 1.145 2008/12/11 02:58:27 shane Exp $
  25345. */
  25346. #if SQLITE_OS_WIN /* This file is used for windows only */
  25347. /*
  25348. ** A Note About Memory Allocation:
  25349. **
  25350. ** This driver uses malloc()/free() directly rather than going through
  25351. ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
  25352. ** are designed for use on embedded systems where memory is scarce and
  25353. ** malloc failures happen frequently. Win32 does not typically run on
  25354. ** embedded systems, and when it does the developers normally have bigger
  25355. ** problems to worry about than running out of memory. So there is not
  25356. ** a compelling need to use the wrappers.
  25357. **
  25358. ** But there is a good reason to not use the wrappers. If we use the
  25359. ** wrappers then we will get simulated malloc() failures within this
  25360. ** driver. And that causes all kinds of problems for our tests. We
  25361. ** could enhance SQLite to deal with simulated malloc failures within
  25362. ** the OS driver, but the code to deal with those failure would not
  25363. ** be exercised on Linux (which does not need to malloc() in the driver)
  25364. ** and so we would have difficulty writing coverage tests for that
  25365. ** code. Better to leave the code out, we think.
  25366. **
  25367. ** The point of this discussion is as follows: When creating a new
  25368. ** OS layer for an embedded system, if you use this file as an example,
  25369. ** avoid the use of malloc()/free(). Those routines work ok on windows
  25370. ** desktops but not so well in embedded systems.
  25371. */
  25372. #include <winbase.h>
  25373. #ifdef __CYGWIN__
  25374. # include <sys/cygwin.h>
  25375. #endif
  25376. /*
  25377. ** Macros used to determine whether or not to use threads.
  25378. */
  25379. #if defined(THREADSAFE) && THREADSAFE
  25380. # define SQLITE_W32_THREADS 1
  25381. #endif
  25382. /*
  25383. ** Include code that is common to all os_*.c files
  25384. */
  25385. /************** Include os_common.h in the middle of os_win.c ****************/
  25386. /************** Begin file os_common.h ***************************************/
  25387. /*
  25388. ** 2004 May 22
  25389. **
  25390. ** The author disclaims copyright to this source code. In place of
  25391. ** a legal notice, here is a blessing:
  25392. **
  25393. ** May you do good and not evil.
  25394. ** May you find forgiveness for yourself and forgive others.
  25395. ** May you share freely, never taking more than you give.
  25396. **
  25397. ******************************************************************************
  25398. **
  25399. ** This file contains macros and a little bit of code that is common to
  25400. ** all of the platform-specific files (os_*.c) and is #included into those
  25401. ** files.
  25402. **
  25403. ** This file should be #included by the os_*.c files only. It is not a
  25404. ** general purpose header file.
  25405. **
  25406. ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
  25407. */
  25408. #ifndef _OS_COMMON_H_
  25409. #define _OS_COMMON_H_
  25410. /*
  25411. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  25412. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  25413. ** switch. The following code should catch this problem at compile-time.
  25414. */
  25415. #ifdef MEMORY_DEBUG
  25416. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  25417. #endif
  25418. /*
  25419. * When testing, this global variable stores the location of the
  25420. * pending-byte in the database file.
  25421. */
  25422. #ifdef SQLITE_TEST
  25423. SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
  25424. #endif
  25425. #ifdef SQLITE_DEBUG
  25426. SQLITE_PRIVATE int sqlite3OSTrace = 0;
  25427. #define OSTRACE1(X) if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
  25428. #define OSTRACE2(X,Y) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
  25429. #define OSTRACE3(X,Y,Z) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
  25430. #define OSTRACE4(X,Y,Z,A) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
  25431. #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
  25432. #define OSTRACE6(X,Y,Z,A,B,C) \
  25433. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
  25434. #define OSTRACE7(X,Y,Z,A,B,C,D) \
  25435. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
  25436. #else
  25437. #define OSTRACE1(X)
  25438. #define OSTRACE2(X,Y)
  25439. #define OSTRACE3(X,Y,Z)
  25440. #define OSTRACE4(X,Y,Z,A)
  25441. #define OSTRACE5(X,Y,Z,A,B)
  25442. #define OSTRACE6(X,Y,Z,A,B,C)
  25443. #define OSTRACE7(X,Y,Z,A,B,C,D)
  25444. #endif
  25445. /*
  25446. ** Macros for performance tracing. Normally turned off. Only works
  25447. ** on i486 hardware.
  25448. */
  25449. #ifdef SQLITE_PERFORMANCE_TRACE
  25450. /*
  25451. ** hwtime.h contains inline assembler code for implementing
  25452. ** high-performance timing routines.
  25453. */
  25454. /************** Include hwtime.h in the middle of os_common.h ****************/
  25455. /************** Begin file hwtime.h ******************************************/
  25456. /*
  25457. ** 2008 May 27
  25458. **
  25459. ** The author disclaims copyright to this source code. In place of
  25460. ** a legal notice, here is a blessing:
  25461. **
  25462. ** May you do good and not evil.
  25463. ** May you find forgiveness for yourself and forgive others.
  25464. ** May you share freely, never taking more than you give.
  25465. **
  25466. ******************************************************************************
  25467. **
  25468. ** This file contains inline asm code for retrieving "high-performance"
  25469. ** counters for x86 class CPUs.
  25470. **
  25471. ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
  25472. */
  25473. #ifndef _HWTIME_H_
  25474. #define _HWTIME_H_
  25475. /*
  25476. ** The following routine only works on pentium-class (or newer) processors.
  25477. ** It uses the RDTSC opcode to read the cycle count value out of the
  25478. ** processor and returns that value. This can be used for high-res
  25479. ** profiling.
  25480. */
  25481. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  25482. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  25483. #if defined(__GNUC__)
  25484. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25485. unsigned int lo, hi;
  25486. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  25487. return (sqlite_uint64)hi << 32 | lo;
  25488. }
  25489. #elif defined(_MSC_VER)
  25490. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  25491. __asm {
  25492. rdtsc
  25493. ret ; return value at EDX:EAX
  25494. }
  25495. }
  25496. #endif
  25497. #elif (defined(__GNUC__) && defined(__x86_64__))
  25498. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25499. unsigned long val;
  25500. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  25501. return val;
  25502. }
  25503. #elif (defined(__GNUC__) && defined(__ppc__))
  25504. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25505. unsigned long long retval;
  25506. unsigned long junk;
  25507. __asm__ __volatile__ ("\n\
  25508. 1: mftbu %1\n\
  25509. mftb %L0\n\
  25510. mftbu %0\n\
  25511. cmpw %0,%1\n\
  25512. bne 1b"
  25513. : "=r" (retval), "=r" (junk));
  25514. return retval;
  25515. }
  25516. #else
  25517. #error Need implementation of sqlite3Hwtime() for your platform.
  25518. /*
  25519. ** To compile without implementing sqlite3Hwtime() for your platform,
  25520. ** you can remove the above #error and use the following
  25521. ** stub function. You will lose timing support for many
  25522. ** of the debugging and testing utilities, but it should at
  25523. ** least compile and run.
  25524. */
  25525. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  25526. #endif
  25527. #endif /* !defined(_HWTIME_H_) */
  25528. /************** End of hwtime.h **********************************************/
  25529. /************** Continuing where we left off in os_common.h ******************/
  25530. static sqlite_uint64 g_start;
  25531. static sqlite_uint64 g_elapsed;
  25532. #define TIMER_START g_start=sqlite3Hwtime()
  25533. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  25534. #define TIMER_ELAPSED g_elapsed
  25535. #else
  25536. #define TIMER_START
  25537. #define TIMER_END
  25538. #define TIMER_ELAPSED ((sqlite_uint64)0)
  25539. #endif
  25540. /*
  25541. ** If we compile with the SQLITE_TEST macro set, then the following block
  25542. ** of code will give us the ability to simulate a disk I/O error. This
  25543. ** is used for testing the I/O recovery logic.
  25544. */
  25545. #ifdef SQLITE_TEST
  25546. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  25547. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  25548. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  25549. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  25550. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  25551. SQLITE_API int sqlite3_diskfull_pending = 0;
  25552. SQLITE_API int sqlite3_diskfull = 0;
  25553. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  25554. #define SimulateIOError(CODE) \
  25555. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  25556. || sqlite3_io_error_pending-- == 1 ) \
  25557. { local_ioerr(); CODE; }
  25558. static void local_ioerr(){
  25559. IOTRACE(("IOERR\n"));
  25560. sqlite3_io_error_hit++;
  25561. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  25562. }
  25563. #define SimulateDiskfullError(CODE) \
  25564. if( sqlite3_diskfull_pending ){ \
  25565. if( sqlite3_diskfull_pending == 1 ){ \
  25566. local_ioerr(); \
  25567. sqlite3_diskfull = 1; \
  25568. sqlite3_io_error_hit = 1; \
  25569. CODE; \
  25570. }else{ \
  25571. sqlite3_diskfull_pending--; \
  25572. } \
  25573. }
  25574. #else
  25575. #define SimulateIOErrorBenign(X)
  25576. #define SimulateIOError(A)
  25577. #define SimulateDiskfullError(A)
  25578. #endif
  25579. /*
  25580. ** When testing, keep a count of the number of open files.
  25581. */
  25582. #ifdef SQLITE_TEST
  25583. SQLITE_API int sqlite3_open_file_count = 0;
  25584. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  25585. #else
  25586. #define OpenCounter(X)
  25587. #endif
  25588. #endif /* !defined(_OS_COMMON_H_) */
  25589. /************** End of os_common.h *******************************************/
  25590. /************** Continuing where we left off in os_win.c *********************/
  25591. /*
  25592. ** Some microsoft compilers lack this definition.
  25593. */
  25594. #ifndef INVALID_FILE_ATTRIBUTES
  25595. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  25596. #endif
  25597. /*
  25598. ** Determine if we are dealing with WindowsCE - which has a much
  25599. ** reduced API.
  25600. */
  25601. #if SQLITE_OS_WINCE
  25602. # define AreFileApisANSI() 1
  25603. #endif
  25604. /*
  25605. ** WinCE lacks native support for file locking so we have to fake it
  25606. ** with some code of our own.
  25607. */
  25608. #if SQLITE_OS_WINCE
  25609. typedef struct winceLock {
  25610. int nReaders; /* Number of reader locks obtained */
  25611. BOOL bPending; /* Indicates a pending lock has been obtained */
  25612. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  25613. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  25614. } winceLock;
  25615. #endif
  25616. /*
  25617. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  25618. ** portability layer.
  25619. */
  25620. typedef struct winFile winFile;
  25621. struct winFile {
  25622. const sqlite3_io_methods *pMethod;/* Must be first */
  25623. HANDLE h; /* Handle for accessing the file */
  25624. unsigned char locktype; /* Type of lock currently held on this file */
  25625. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  25626. #if SQLITE_OS_WINCE
  25627. WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
  25628. HANDLE hMutex; /* Mutex used to control access to shared lock */
  25629. HANDLE hShared; /* Shared memory segment used for locking */
  25630. winceLock local; /* Locks obtained by this instance of winFile */
  25631. winceLock *shared; /* Global shared lock memory for the file */
  25632. #endif
  25633. };
  25634. /*
  25635. ** The following variable is (normally) set once and never changes
  25636. ** thereafter. It records whether the operating system is Win95
  25637. ** or WinNT.
  25638. **
  25639. ** 0: Operating system unknown.
  25640. ** 1: Operating system is Win95.
  25641. ** 2: Operating system is WinNT.
  25642. **
  25643. ** In order to facilitate testing on a WinNT system, the test fixture
  25644. ** can manually set this value to 1 to emulate Win98 behavior.
  25645. */
  25646. #ifdef SQLITE_TEST
  25647. SQLITE_API int sqlite3_os_type = 0;
  25648. #else
  25649. static int sqlite3_os_type = 0;
  25650. #endif
  25651. /*
  25652. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  25653. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  25654. **
  25655. ** Here is an interesting observation: Win95, Win98, and WinME lack
  25656. ** the LockFileEx() API. But we can still statically link against that
  25657. ** API as long as we don't call it win running Win95/98/ME. A call to
  25658. ** this routine is used to determine if the host is Win95/98/ME or
  25659. ** WinNT/2K/XP so that we will know whether or not we can safely call
  25660. ** the LockFileEx() API.
  25661. */
  25662. #if SQLITE_OS_WINCE
  25663. # define isNT() (1)
  25664. #else
  25665. static int isNT(void){
  25666. if( sqlite3_os_type==0 ){
  25667. OSVERSIONINFO sInfo;
  25668. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  25669. GetVersionEx(&sInfo);
  25670. sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  25671. }
  25672. return sqlite3_os_type==2;
  25673. }
  25674. #endif /* SQLITE_OS_WINCE */
  25675. /*
  25676. ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
  25677. **
  25678. ** Space to hold the returned string is obtained from malloc.
  25679. */
  25680. static WCHAR *utf8ToUnicode(const char *zFilename){
  25681. int nChar;
  25682. WCHAR *zWideFilename;
  25683. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  25684. zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
  25685. if( zWideFilename==0 ){
  25686. return 0;
  25687. }
  25688. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
  25689. if( nChar==0 ){
  25690. free(zWideFilename);
  25691. zWideFilename = 0;
  25692. }
  25693. return zWideFilename;
  25694. }
  25695. /*
  25696. ** Convert microsoft unicode to UTF-8. Space to hold the returned string is
  25697. ** obtained from malloc().
  25698. */
  25699. static char *unicodeToUtf8(const WCHAR *zWideFilename){
  25700. int nByte;
  25701. char *zFilename;
  25702. nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  25703. zFilename = malloc( nByte );
  25704. if( zFilename==0 ){
  25705. return 0;
  25706. }
  25707. nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  25708. 0, 0);
  25709. if( nByte == 0 ){
  25710. free(zFilename);
  25711. zFilename = 0;
  25712. }
  25713. return zFilename;
  25714. }
  25715. /*
  25716. ** Convert an ansi string to microsoft unicode, based on the
  25717. ** current codepage settings for file apis.
  25718. **
  25719. ** Space to hold the returned string is obtained
  25720. ** from malloc.
  25721. */
  25722. static WCHAR *mbcsToUnicode(const char *zFilename){
  25723. int nByte;
  25724. WCHAR *zMbcsFilename;
  25725. int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
  25726. nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
  25727. zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
  25728. if( zMbcsFilename==0 ){
  25729. return 0;
  25730. }
  25731. nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
  25732. if( nByte==0 ){
  25733. free(zMbcsFilename);
  25734. zMbcsFilename = 0;
  25735. }
  25736. return zMbcsFilename;
  25737. }
  25738. /*
  25739. ** Convert microsoft unicode to multibyte character string, based on the
  25740. ** user's Ansi codepage.
  25741. **
  25742. ** Space to hold the returned string is obtained from
  25743. ** malloc().
  25744. */
  25745. static char *unicodeToMbcs(const WCHAR *zWideFilename){
  25746. int nByte;
  25747. char *zFilename;
  25748. int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
  25749. nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  25750. zFilename = malloc( nByte );
  25751. if( zFilename==0 ){
  25752. return 0;
  25753. }
  25754. nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
  25755. 0, 0);
  25756. if( nByte == 0 ){
  25757. free(zFilename);
  25758. zFilename = 0;
  25759. }
  25760. return zFilename;
  25761. }
  25762. /*
  25763. ** Convert multibyte character string to UTF-8. Space to hold the
  25764. ** returned string is obtained from malloc().
  25765. */
  25766. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  25767. char *zFilenameUtf8;
  25768. WCHAR *zTmpWide;
  25769. zTmpWide = mbcsToUnicode(zFilename);
  25770. if( zTmpWide==0 ){
  25771. return 0;
  25772. }
  25773. zFilenameUtf8 = unicodeToUtf8(zTmpWide);
  25774. free(zTmpWide);
  25775. return zFilenameUtf8;
  25776. }
  25777. /*
  25778. ** Convert UTF-8 to multibyte character string. Space to hold the
  25779. ** returned string is obtained from malloc().
  25780. */
  25781. static char *utf8ToMbcs(const char *zFilename){
  25782. char *zFilenameMbcs;
  25783. WCHAR *zTmpWide;
  25784. zTmpWide = utf8ToUnicode(zFilename);
  25785. if( zTmpWide==0 ){
  25786. return 0;
  25787. }
  25788. zFilenameMbcs = unicodeToMbcs(zTmpWide);
  25789. free(zTmpWide);
  25790. return zFilenameMbcs;
  25791. }
  25792. #if SQLITE_OS_WINCE
  25793. /*************************************************************************
  25794. ** This section contains code for WinCE only.
  25795. */
  25796. /*
  25797. ** WindowsCE does not have a localtime() function. So create a
  25798. ** substitute.
  25799. */
  25800. struct tm *__cdecl localtime(const time_t *t)
  25801. {
  25802. static struct tm y;
  25803. FILETIME uTm, lTm;
  25804. SYSTEMTIME pTm;
  25805. sqlite3_int64 t64;
  25806. t64 = *t;
  25807. t64 = (t64 + 11644473600)*10000000;
  25808. uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
  25809. uTm.dwHighDateTime= t64 >> 32;
  25810. FileTimeToLocalFileTime(&uTm,&lTm);
  25811. FileTimeToSystemTime(&lTm,&pTm);
  25812. y.tm_year = pTm.wYear - 1900;
  25813. y.tm_mon = pTm.wMonth - 1;
  25814. y.tm_wday = pTm.wDayOfWeek;
  25815. y.tm_mday = pTm.wDay;
  25816. y.tm_hour = pTm.wHour;
  25817. y.tm_min = pTm.wMinute;
  25818. y.tm_sec = pTm.wSecond;
  25819. return &y;
  25820. }
  25821. /* This will never be called, but defined to make the code compile */
  25822. #define GetTempPathA(a,b)
  25823. #define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
  25824. #define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
  25825. #define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
  25826. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
  25827. /*
  25828. ** Acquire a lock on the handle h
  25829. */
  25830. static void winceMutexAcquire(HANDLE h){
  25831. DWORD dwErr;
  25832. do {
  25833. dwErr = WaitForSingleObject(h, INFINITE);
  25834. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  25835. }
  25836. /*
  25837. ** Release a lock acquired by winceMutexAcquire()
  25838. */
  25839. #define winceMutexRelease(h) ReleaseMutex(h)
  25840. /*
  25841. ** Create the mutex and shared memory used for locking in the file
  25842. ** descriptor pFile
  25843. */
  25844. static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
  25845. WCHAR *zTok;
  25846. WCHAR *zName = utf8ToUnicode(zFilename);
  25847. BOOL bInit = TRUE;
  25848. /* Initialize the local lockdata */
  25849. ZeroMemory(&pFile->local, sizeof(pFile->local));
  25850. /* Replace the backslashes from the filename and lowercase it
  25851. ** to derive a mutex name. */
  25852. zTok = CharLowerW(zName);
  25853. for (;*zTok;zTok++){
  25854. if (*zTok == '\\') *zTok = '_';
  25855. }
  25856. /* Create/open the named mutex */
  25857. pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
  25858. if (!pFile->hMutex){
  25859. free(zName);
  25860. return FALSE;
  25861. }
  25862. /* Acquire the mutex before continuing */
  25863. winceMutexAcquire(pFile->hMutex);
  25864. /* Since the names of named mutexes, semaphores, file mappings etc are
  25865. ** case-sensitive, take advantage of that by uppercasing the mutex name
  25866. ** and using that as the shared filemapping name.
  25867. */
  25868. CharUpperW(zName);
  25869. pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  25870. PAGE_READWRITE, 0, sizeof(winceLock),
  25871. zName);
  25872. /* Set a flag that indicates we're the first to create the memory so it
  25873. ** must be zero-initialized */
  25874. if (GetLastError() == ERROR_ALREADY_EXISTS){
  25875. bInit = FALSE;
  25876. }
  25877. free(zName);
  25878. /* If we succeeded in making the shared memory handle, map it. */
  25879. if (pFile->hShared){
  25880. pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
  25881. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  25882. /* If mapping failed, close the shared memory handle and erase it */
  25883. if (!pFile->shared){
  25884. CloseHandle(pFile->hShared);
  25885. pFile->hShared = NULL;
  25886. }
  25887. }
  25888. /* If shared memory could not be created, then close the mutex and fail */
  25889. if (pFile->hShared == NULL){
  25890. winceMutexRelease(pFile->hMutex);
  25891. CloseHandle(pFile->hMutex);
  25892. pFile->hMutex = NULL;
  25893. return FALSE;
  25894. }
  25895. /* Initialize the shared memory if we're supposed to */
  25896. if (bInit) {
  25897. ZeroMemory(pFile->shared, sizeof(winceLock));
  25898. }
  25899. winceMutexRelease(pFile->hMutex);
  25900. return TRUE;
  25901. }
  25902. /*
  25903. ** Destroy the part of winFile that deals with wince locks
  25904. */
  25905. static void winceDestroyLock(winFile *pFile){
  25906. if (pFile->hMutex){
  25907. /* Acquire the mutex */
  25908. winceMutexAcquire(pFile->hMutex);
  25909. /* The following blocks should probably assert in debug mode, but they
  25910. are to cleanup in case any locks remained open */
  25911. if (pFile->local.nReaders){
  25912. pFile->shared->nReaders --;
  25913. }
  25914. if (pFile->local.bReserved){
  25915. pFile->shared->bReserved = FALSE;
  25916. }
  25917. if (pFile->local.bPending){
  25918. pFile->shared->bPending = FALSE;
  25919. }
  25920. if (pFile->local.bExclusive){
  25921. pFile->shared->bExclusive = FALSE;
  25922. }
  25923. /* De-reference and close our copy of the shared memory handle */
  25924. UnmapViewOfFile(pFile->shared);
  25925. CloseHandle(pFile->hShared);
  25926. /* Done with the mutex */
  25927. winceMutexRelease(pFile->hMutex);
  25928. CloseHandle(pFile->hMutex);
  25929. pFile->hMutex = NULL;
  25930. }
  25931. }
  25932. /*
  25933. ** An implementation of the LockFile() API of windows for wince
  25934. */
  25935. static BOOL winceLockFile(
  25936. HANDLE *phFile,
  25937. DWORD dwFileOffsetLow,
  25938. DWORD dwFileOffsetHigh,
  25939. DWORD nNumberOfBytesToLockLow,
  25940. DWORD nNumberOfBytesToLockHigh
  25941. ){
  25942. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  25943. BOOL bReturn = FALSE;
  25944. if (!pFile->hMutex) return TRUE;
  25945. winceMutexAcquire(pFile->hMutex);
  25946. /* Wanting an exclusive lock? */
  25947. if (dwFileOffsetLow == SHARED_FIRST
  25948. && nNumberOfBytesToLockLow == SHARED_SIZE){
  25949. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  25950. pFile->shared->bExclusive = TRUE;
  25951. pFile->local.bExclusive = TRUE;
  25952. bReturn = TRUE;
  25953. }
  25954. }
  25955. /* Want a read-only lock? */
  25956. else if ((dwFileOffsetLow >= SHARED_FIRST &&
  25957. dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
  25958. nNumberOfBytesToLockLow == 1){
  25959. if (pFile->shared->bExclusive == 0){
  25960. pFile->local.nReaders ++;
  25961. if (pFile->local.nReaders == 1){
  25962. pFile->shared->nReaders ++;
  25963. }
  25964. bReturn = TRUE;
  25965. }
  25966. }
  25967. /* Want a pending lock? */
  25968. else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
  25969. /* If no pending lock has been acquired, then acquire it */
  25970. if (pFile->shared->bPending == 0) {
  25971. pFile->shared->bPending = TRUE;
  25972. pFile->local.bPending = TRUE;
  25973. bReturn = TRUE;
  25974. }
  25975. }
  25976. /* Want a reserved lock? */
  25977. else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
  25978. if (pFile->shared->bReserved == 0) {
  25979. pFile->shared->bReserved = TRUE;
  25980. pFile->local.bReserved = TRUE;
  25981. bReturn = TRUE;
  25982. }
  25983. }
  25984. winceMutexRelease(pFile->hMutex);
  25985. return bReturn;
  25986. }
  25987. /*
  25988. ** An implementation of the UnlockFile API of windows for wince
  25989. */
  25990. static BOOL winceUnlockFile(
  25991. HANDLE *phFile,
  25992. DWORD dwFileOffsetLow,
  25993. DWORD dwFileOffsetHigh,
  25994. DWORD nNumberOfBytesToUnlockLow,
  25995. DWORD nNumberOfBytesToUnlockHigh
  25996. ){
  25997. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  25998. BOOL bReturn = FALSE;
  25999. if (!pFile->hMutex) return TRUE;
  26000. winceMutexAcquire(pFile->hMutex);
  26001. /* Releasing a reader lock or an exclusive lock */
  26002. if (dwFileOffsetLow >= SHARED_FIRST &&
  26003. dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
  26004. /* Did we have an exclusive lock? */
  26005. if (pFile->local.bExclusive){
  26006. pFile->local.bExclusive = FALSE;
  26007. pFile->shared->bExclusive = FALSE;
  26008. bReturn = TRUE;
  26009. }
  26010. /* Did we just have a reader lock? */
  26011. else if (pFile->local.nReaders){
  26012. pFile->local.nReaders --;
  26013. if (pFile->local.nReaders == 0)
  26014. {
  26015. pFile->shared->nReaders --;
  26016. }
  26017. bReturn = TRUE;
  26018. }
  26019. }
  26020. /* Releasing a pending lock */
  26021. else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
  26022. if (pFile->local.bPending){
  26023. pFile->local.bPending = FALSE;
  26024. pFile->shared->bPending = FALSE;
  26025. bReturn = TRUE;
  26026. }
  26027. }
  26028. /* Releasing a reserved lock */
  26029. else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
  26030. if (pFile->local.bReserved) {
  26031. pFile->local.bReserved = FALSE;
  26032. pFile->shared->bReserved = FALSE;
  26033. bReturn = TRUE;
  26034. }
  26035. }
  26036. winceMutexRelease(pFile->hMutex);
  26037. return bReturn;
  26038. }
  26039. /*
  26040. ** An implementation of the LockFileEx() API of windows for wince
  26041. */
  26042. static BOOL winceLockFileEx(
  26043. HANDLE *phFile,
  26044. DWORD dwFlags,
  26045. DWORD dwReserved,
  26046. DWORD nNumberOfBytesToLockLow,
  26047. DWORD nNumberOfBytesToLockHigh,
  26048. LPOVERLAPPED lpOverlapped
  26049. ){
  26050. /* If the caller wants a shared read lock, forward this call
  26051. ** to winceLockFile */
  26052. if (lpOverlapped->Offset == SHARED_FIRST &&
  26053. dwFlags == 1 &&
  26054. nNumberOfBytesToLockLow == SHARED_SIZE){
  26055. return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
  26056. }
  26057. return FALSE;
  26058. }
  26059. /*
  26060. ** End of the special code for wince
  26061. *****************************************************************************/
  26062. #endif /* SQLITE_OS_WINCE */
  26063. /*****************************************************************************
  26064. ** The next group of routines implement the I/O methods specified
  26065. ** by the sqlite3_io_methods object.
  26066. ******************************************************************************/
  26067. /*
  26068. ** Close a file.
  26069. **
  26070. ** It is reported that an attempt to close a handle might sometimes
  26071. ** fail. This is a very unreasonable result, but windows is notorious
  26072. ** for being unreasonable so I do not doubt that it might happen. If
  26073. ** the close fails, we pause for 100 milliseconds and try again. As
  26074. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  26075. ** giving up and returning an error.
  26076. */
  26077. #define MX_CLOSE_ATTEMPT 3
  26078. static int winClose(sqlite3_file *id){
  26079. int rc, cnt = 0;
  26080. winFile *pFile = (winFile*)id;
  26081. OSTRACE2("CLOSE %d\n", pFile->h);
  26082. do{
  26083. rc = CloseHandle(pFile->h);
  26084. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
  26085. #if SQLITE_OS_WINCE
  26086. #define WINCE_DELETION_ATTEMPTS 3
  26087. winceDestroyLock(pFile);
  26088. if( pFile->zDeleteOnClose ){
  26089. int cnt = 0;
  26090. while(
  26091. DeleteFileW(pFile->zDeleteOnClose)==0
  26092. && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  26093. && cnt++ < WINCE_DELETION_ATTEMPTS
  26094. ){
  26095. Sleep(100); /* Wait a little before trying again */
  26096. }
  26097. free(pFile->zDeleteOnClose);
  26098. }
  26099. #endif
  26100. OpenCounter(-1);
  26101. return rc ? SQLITE_OK : SQLITE_IOERR;
  26102. }
  26103. /*
  26104. ** Some microsoft compilers lack this definition.
  26105. */
  26106. #ifndef INVALID_SET_FILE_POINTER
  26107. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  26108. #endif
  26109. /*
  26110. ** Read data from a file into a buffer. Return SQLITE_OK if all
  26111. ** bytes were read successfully and SQLITE_IOERR if anything goes
  26112. ** wrong.
  26113. */
  26114. static int winRead(
  26115. sqlite3_file *id, /* File to read from */
  26116. void *pBuf, /* Write content into this buffer */
  26117. int amt, /* Number of bytes to read */
  26118. sqlite3_int64 offset /* Begin reading at this offset */
  26119. ){
  26120. LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  26121. LONG lowerBits = (LONG)(offset & 0xffffffff);
  26122. DWORD rc;
  26123. DWORD got;
  26124. winFile *pFile = (winFile*)id;
  26125. assert( id!=0 );
  26126. SimulateIOError(return SQLITE_IOERR_READ);
  26127. OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
  26128. rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  26129. if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
  26130. return SQLITE_FULL;
  26131. }
  26132. if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
  26133. return SQLITE_IOERR_READ;
  26134. }
  26135. if( got==(DWORD)amt ){
  26136. return SQLITE_OK;
  26137. }else{
  26138. /* Unread parts of the buffer must be zero-filled */
  26139. memset(&((char*)pBuf)[got], 0, amt-got);
  26140. return SQLITE_IOERR_SHORT_READ;
  26141. }
  26142. }
  26143. /*
  26144. ** Write data from a buffer into a file. Return SQLITE_OK on success
  26145. ** or some other error code on failure.
  26146. */
  26147. static int winWrite(
  26148. sqlite3_file *id, /* File to write into */
  26149. const void *pBuf, /* The bytes to be written */
  26150. int amt, /* Number of bytes to write */
  26151. sqlite3_int64 offset /* Offset into the file to begin writing at */
  26152. ){
  26153. LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  26154. LONG lowerBits = (LONG)(offset & 0xffffffff);
  26155. DWORD rc;
  26156. DWORD wrote = 0;
  26157. winFile *pFile = (winFile*)id;
  26158. assert( id!=0 );
  26159. SimulateIOError(return SQLITE_IOERR_WRITE);
  26160. SimulateDiskfullError(return SQLITE_FULL);
  26161. OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
  26162. rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  26163. if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
  26164. return SQLITE_FULL;
  26165. }
  26166. assert( amt>0 );
  26167. while(
  26168. amt>0
  26169. && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
  26170. && wrote>0
  26171. ){
  26172. amt -= wrote;
  26173. pBuf = &((char*)pBuf)[wrote];
  26174. }
  26175. if( !rc || amt>(int)wrote ){
  26176. return SQLITE_FULL;
  26177. }
  26178. return SQLITE_OK;
  26179. }
  26180. /*
  26181. ** Truncate an open file to a specified size
  26182. */
  26183. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  26184. DWORD rc;
  26185. LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
  26186. LONG lowerBits = (LONG)(nByte & 0xffffffff);
  26187. winFile *pFile = (winFile*)id;
  26188. OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
  26189. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  26190. rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  26191. if( INVALID_SET_FILE_POINTER != rc ){
  26192. /* SetEndOfFile will fail if nByte is negative */
  26193. if( SetEndOfFile(pFile->h) ){
  26194. return SQLITE_OK;
  26195. }
  26196. }
  26197. return SQLITE_IOERR_TRUNCATE;
  26198. }
  26199. #ifdef SQLITE_TEST
  26200. /*
  26201. ** Count the number of fullsyncs and normal syncs. This is used to test
  26202. ** that syncs and fullsyncs are occuring at the right times.
  26203. */
  26204. SQLITE_API int sqlite3_sync_count = 0;
  26205. SQLITE_API int sqlite3_fullsync_count = 0;
  26206. #endif
  26207. /*
  26208. ** Make sure all writes to a particular file are committed to disk.
  26209. */
  26210. static int winSync(sqlite3_file *id, int flags){
  26211. #ifndef SQLITE_NO_SYNC
  26212. winFile *pFile = (winFile*)id;
  26213. #else
  26214. UNUSED_PARAMETER(id);
  26215. #endif
  26216. OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
  26217. #ifndef SQLITE_TEST
  26218. UNUSED_PARAMETER(flags);
  26219. #else
  26220. if( flags & SQLITE_SYNC_FULL ){
  26221. sqlite3_fullsync_count++;
  26222. }
  26223. sqlite3_sync_count++;
  26224. #endif
  26225. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  26226. ** no-op
  26227. */
  26228. #ifdef SQLITE_NO_SYNC
  26229. return SQLITE_OK;
  26230. #else
  26231. if( FlushFileBuffers(pFile->h) ){
  26232. return SQLITE_OK;
  26233. }else{
  26234. return SQLITE_IOERR;
  26235. }
  26236. #endif
  26237. }
  26238. /*
  26239. ** Determine the current size of a file in bytes
  26240. */
  26241. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  26242. winFile *pFile = (winFile*)id;
  26243. DWORD upperBits, lowerBits;
  26244. SimulateIOError(return SQLITE_IOERR_FSTAT);
  26245. lowerBits = GetFileSize(pFile->h, &upperBits);
  26246. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  26247. return SQLITE_OK;
  26248. }
  26249. /*
  26250. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  26251. */
  26252. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  26253. # define LOCKFILE_FAIL_IMMEDIATELY 1
  26254. #endif
  26255. /*
  26256. ** Acquire a reader lock.
  26257. ** Different API routines are called depending on whether or not this
  26258. ** is Win95 or WinNT.
  26259. */
  26260. static int getReadLock(winFile *pFile){
  26261. int res;
  26262. if( isNT() ){
  26263. OVERLAPPED ovlp;
  26264. ovlp.Offset = SHARED_FIRST;
  26265. ovlp.OffsetHigh = 0;
  26266. ovlp.hEvent = 0;
  26267. res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
  26268. 0, SHARED_SIZE, 0, &ovlp);
  26269. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  26270. */
  26271. #if SQLITE_OS_WINCE==0
  26272. }else{
  26273. int lk;
  26274. sqlite3_randomness(sizeof(lk), &lk);
  26275. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  26276. res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  26277. #endif
  26278. }
  26279. return res;
  26280. }
  26281. /*
  26282. ** Undo a readlock
  26283. */
  26284. static int unlockReadLock(winFile *pFile){
  26285. int res;
  26286. if( isNT() ){
  26287. res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  26288. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  26289. */
  26290. #if SQLITE_OS_WINCE==0
  26291. }else{
  26292. res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
  26293. #endif
  26294. }
  26295. return res;
  26296. }
  26297. /*
  26298. ** Lock the file with the lock specified by parameter locktype - one
  26299. ** of the following:
  26300. **
  26301. ** (1) SHARED_LOCK
  26302. ** (2) RESERVED_LOCK
  26303. ** (3) PENDING_LOCK
  26304. ** (4) EXCLUSIVE_LOCK
  26305. **
  26306. ** Sometimes when requesting one lock state, additional lock states
  26307. ** are inserted in between. The locking might fail on one of the later
  26308. ** transitions leaving the lock state different from what it started but
  26309. ** still short of its goal. The following chart shows the allowed
  26310. ** transitions and the inserted intermediate states:
  26311. **
  26312. ** UNLOCKED -> SHARED
  26313. ** SHARED -> RESERVED
  26314. ** SHARED -> (PENDING) -> EXCLUSIVE
  26315. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26316. ** PENDING -> EXCLUSIVE
  26317. **
  26318. ** This routine will only increase a lock. The winUnlock() routine
  26319. ** erases all locks at once and returns us immediately to locking level 0.
  26320. ** It is not possible to lower the locking level one step at a time. You
  26321. ** must go straight to locking level 0.
  26322. */
  26323. static int winLock(sqlite3_file *id, int locktype){
  26324. int rc = SQLITE_OK; /* Return code from subroutines */
  26325. int res = 1; /* Result of a windows lock call */
  26326. int newLocktype; /* Set pFile->locktype to this value before exiting */
  26327. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  26328. winFile *pFile = (winFile*)id;
  26329. assert( pFile!=0 );
  26330. OSTRACE5("LOCK %d %d was %d(%d)\n",
  26331. pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
  26332. /* If there is already a lock of this type or more restrictive on the
  26333. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  26334. ** sqlite3OsEnterMutex() hasn't been called yet.
  26335. */
  26336. if( pFile->locktype>=locktype ){
  26337. return SQLITE_OK;
  26338. }
  26339. /* Make sure the locking sequence is correct
  26340. */
  26341. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  26342. assert( locktype!=PENDING_LOCK );
  26343. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  26344. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  26345. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  26346. ** the PENDING_LOCK byte is temporary.
  26347. */
  26348. newLocktype = pFile->locktype;
  26349. if( pFile->locktype==NO_LOCK
  26350. || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
  26351. ){
  26352. int cnt = 3;
  26353. while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
  26354. /* Try 3 times to get the pending lock. The pending lock might be
  26355. ** held by another reader process who will release it momentarily.
  26356. */
  26357. OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
  26358. Sleep(1);
  26359. }
  26360. gotPendingLock = res;
  26361. }
  26362. /* Acquire a shared lock
  26363. */
  26364. if( locktype==SHARED_LOCK && res ){
  26365. assert( pFile->locktype==NO_LOCK );
  26366. res = getReadLock(pFile);
  26367. if( res ){
  26368. newLocktype = SHARED_LOCK;
  26369. }
  26370. }
  26371. /* Acquire a RESERVED lock
  26372. */
  26373. if( locktype==RESERVED_LOCK && res ){
  26374. assert( pFile->locktype==SHARED_LOCK );
  26375. res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  26376. if( res ){
  26377. newLocktype = RESERVED_LOCK;
  26378. }
  26379. }
  26380. /* Acquire a PENDING lock
  26381. */
  26382. if( locktype==EXCLUSIVE_LOCK && res ){
  26383. newLocktype = PENDING_LOCK;
  26384. gotPendingLock = 0;
  26385. }
  26386. /* Acquire an EXCLUSIVE lock
  26387. */
  26388. if( locktype==EXCLUSIVE_LOCK && res ){
  26389. assert( pFile->locktype>=SHARED_LOCK );
  26390. res = unlockReadLock(pFile);
  26391. OSTRACE2("unreadlock = %d\n", res);
  26392. res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  26393. if( res ){
  26394. newLocktype = EXCLUSIVE_LOCK;
  26395. }else{
  26396. OSTRACE2("error-code = %d\n", GetLastError());
  26397. getReadLock(pFile);
  26398. }
  26399. }
  26400. /* If we are holding a PENDING lock that ought to be released, then
  26401. ** release it now.
  26402. */
  26403. if( gotPendingLock && locktype==SHARED_LOCK ){
  26404. UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  26405. }
  26406. /* Update the state of the lock has held in the file descriptor then
  26407. ** return the appropriate result code.
  26408. */
  26409. if( res ){
  26410. rc = SQLITE_OK;
  26411. }else{
  26412. OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
  26413. locktype, newLocktype);
  26414. rc = SQLITE_BUSY;
  26415. }
  26416. pFile->locktype = (u8)newLocktype;
  26417. return rc;
  26418. }
  26419. /*
  26420. ** This routine checks if there is a RESERVED lock held on the specified
  26421. ** file by this or any other process. If such a lock is held, return
  26422. ** non-zero, otherwise zero.
  26423. */
  26424. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  26425. int rc;
  26426. winFile *pFile = (winFile*)id;
  26427. assert( pFile!=0 );
  26428. if( pFile->locktype>=RESERVED_LOCK ){
  26429. rc = 1;
  26430. OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
  26431. }else{
  26432. rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  26433. if( rc ){
  26434. UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  26435. }
  26436. rc = !rc;
  26437. OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
  26438. }
  26439. *pResOut = rc;
  26440. return SQLITE_OK;
  26441. }
  26442. /*
  26443. ** Lower the locking level on file descriptor id to locktype. locktype
  26444. ** must be either NO_LOCK or SHARED_LOCK.
  26445. **
  26446. ** If the locking level of the file descriptor is already at or below
  26447. ** the requested locking level, this routine is a no-op.
  26448. **
  26449. ** It is not possible for this routine to fail if the second argument
  26450. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  26451. ** might return SQLITE_IOERR;
  26452. */
  26453. static int winUnlock(sqlite3_file *id, int locktype){
  26454. int type;
  26455. winFile *pFile = (winFile*)id;
  26456. int rc = SQLITE_OK;
  26457. assert( pFile!=0 );
  26458. assert( locktype<=SHARED_LOCK );
  26459. OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
  26460. pFile->locktype, pFile->sharedLockByte);
  26461. type = pFile->locktype;
  26462. if( type>=EXCLUSIVE_LOCK ){
  26463. UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  26464. if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
  26465. /* This should never happen. We should always be able to
  26466. ** reacquire the read lock */
  26467. rc = SQLITE_IOERR_UNLOCK;
  26468. }
  26469. }
  26470. if( type>=RESERVED_LOCK ){
  26471. UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  26472. }
  26473. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  26474. unlockReadLock(pFile);
  26475. }
  26476. if( type>=PENDING_LOCK ){
  26477. UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  26478. }
  26479. pFile->locktype = (u8)locktype;
  26480. return rc;
  26481. }
  26482. /*
  26483. ** Control and query of the open file handle.
  26484. */
  26485. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  26486. switch( op ){
  26487. case SQLITE_FCNTL_LOCKSTATE: {
  26488. *(int*)pArg = ((winFile*)id)->locktype;
  26489. return SQLITE_OK;
  26490. }
  26491. }
  26492. return SQLITE_ERROR;
  26493. }
  26494. /*
  26495. ** Return the sector size in bytes of the underlying block device for
  26496. ** the specified file. This is almost always 512 bytes, but may be
  26497. ** larger for some devices.
  26498. **
  26499. ** SQLite code assumes this function cannot fail. It also assumes that
  26500. ** if two files are created in the same file-system directory (i.e.
  26501. ** a database and its journal file) that the sector size will be the
  26502. ** same for both.
  26503. */
  26504. static int winSectorSize(sqlite3_file *id){
  26505. UNUSED_PARAMETER(id);
  26506. return SQLITE_DEFAULT_SECTOR_SIZE;
  26507. }
  26508. /*
  26509. ** Return a vector of device characteristics.
  26510. */
  26511. static int winDeviceCharacteristics(sqlite3_file *id){
  26512. UNUSED_PARAMETER(id);
  26513. return 0;
  26514. }
  26515. /*
  26516. ** This vector defines all the methods that can operate on an
  26517. ** sqlite3_file for win32.
  26518. */
  26519. static const sqlite3_io_methods winIoMethod = {
  26520. 1, /* iVersion */
  26521. winClose,
  26522. winRead,
  26523. winWrite,
  26524. winTruncate,
  26525. winSync,
  26526. winFileSize,
  26527. winLock,
  26528. winUnlock,
  26529. winCheckReservedLock,
  26530. winFileControl,
  26531. winSectorSize,
  26532. winDeviceCharacteristics
  26533. };
  26534. /***************************************************************************
  26535. ** Here ends the I/O methods that form the sqlite3_io_methods object.
  26536. **
  26537. ** The next block of code implements the VFS methods.
  26538. ****************************************************************************/
  26539. /*
  26540. ** Convert a UTF-8 filename into whatever form the underlying
  26541. ** operating system wants filenames in. Space to hold the result
  26542. ** is obtained from malloc and must be freed by the calling
  26543. ** function.
  26544. */
  26545. static void *convertUtf8Filename(const char *zFilename){
  26546. void *zConverted = 0;
  26547. if( isNT() ){
  26548. zConverted = utf8ToUnicode(zFilename);
  26549. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  26550. */
  26551. #if SQLITE_OS_WINCE==0
  26552. }else{
  26553. zConverted = utf8ToMbcs(zFilename);
  26554. #endif
  26555. }
  26556. /* caller will handle out of memory */
  26557. return zConverted;
  26558. }
  26559. /*
  26560. ** Create a temporary file name in zBuf. zBuf must be big enough to
  26561. ** hold at pVfs->mxPathname characters.
  26562. */
  26563. static int getTempname(int nBuf, char *zBuf){
  26564. static char zChars[] =
  26565. "abcdefghijklmnopqrstuvwxyz"
  26566. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  26567. "0123456789";
  26568. size_t i, j;
  26569. char zTempPath[MAX_PATH+1];
  26570. if( sqlite3_temp_directory ){
  26571. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
  26572. }else if( isNT() ){
  26573. char *zMulti;
  26574. WCHAR zWidePath[MAX_PATH];
  26575. GetTempPathW(MAX_PATH-30, zWidePath);
  26576. zMulti = unicodeToUtf8(zWidePath);
  26577. if( zMulti ){
  26578. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
  26579. free(zMulti);
  26580. }else{
  26581. return SQLITE_NOMEM;
  26582. }
  26583. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  26584. ** Since the ASCII version of these Windows API do not exist for WINCE,
  26585. ** it's important to not reference them for WINCE builds.
  26586. */
  26587. #if SQLITE_OS_WINCE==0
  26588. }else{
  26589. char *zUtf8;
  26590. char zMbcsPath[MAX_PATH];
  26591. GetTempPathA(MAX_PATH-30, zMbcsPath);
  26592. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  26593. if( zUtf8 ){
  26594. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
  26595. free(zUtf8);
  26596. }else{
  26597. return SQLITE_NOMEM;
  26598. }
  26599. #endif
  26600. }
  26601. for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
  26602. zTempPath[i] = 0;
  26603. sqlite3_snprintf(nBuf-30, zBuf,
  26604. "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
  26605. j = sqlite3Strlen30(zBuf);
  26606. sqlite3_randomness(20, &zBuf[j]);
  26607. for(i=0; i<20; i++, j++){
  26608. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  26609. }
  26610. zBuf[j] = 0;
  26611. OSTRACE2("TEMP FILENAME: %s\n", zBuf);
  26612. return SQLITE_OK;
  26613. }
  26614. /*
  26615. ** The return value of getLastErrorMsg
  26616. ** is zero if the error message fits in the buffer, or non-zero
  26617. ** otherwise (if the message was truncated).
  26618. */
  26619. static int getLastErrorMsg(int nBuf, char *zBuf){
  26620. DWORD error = GetLastError();
  26621. #if SQLITE_OS_WINCE
  26622. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
  26623. #else
  26624. /* FormatMessage returns 0 on failure. Otherwise it
  26625. ** returns the number of TCHARs written to the output
  26626. ** buffer, excluding the terminating null char.
  26627. */
  26628. if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
  26629. NULL,
  26630. error,
  26631. 0,
  26632. zBuf,
  26633. nBuf-1,
  26634. 0))
  26635. {
  26636. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
  26637. }
  26638. #endif
  26639. return 0;
  26640. }
  26641. /*
  26642. ** Open a file.
  26643. */
  26644. static int winOpen(
  26645. sqlite3_vfs *pVfs, /* Not used */
  26646. const char *zName, /* Name of the file (UTF-8) */
  26647. sqlite3_file *id, /* Write the SQLite file handle here */
  26648. int flags, /* Open mode flags */
  26649. int *pOutFlags /* Status return flags */
  26650. ){
  26651. HANDLE h;
  26652. DWORD dwDesiredAccess;
  26653. DWORD dwShareMode;
  26654. DWORD dwCreationDisposition;
  26655. DWORD dwFlagsAndAttributes = 0;
  26656. #if SQLITE_OS_WINCE
  26657. int isTemp = 0;
  26658. #endif
  26659. winFile *pFile = (winFile*)id;
  26660. void *zConverted; /* Filename in OS encoding */
  26661. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  26662. char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
  26663. UNUSED_PARAMETER(pVfs);
  26664. /* If the second argument to this function is NULL, generate a
  26665. ** temporary file name to use
  26666. */
  26667. if( !zUtf8Name ){
  26668. int rc = getTempname(MAX_PATH+1, zTmpname);
  26669. if( rc!=SQLITE_OK ){
  26670. return rc;
  26671. }
  26672. zUtf8Name = zTmpname;
  26673. }
  26674. /* Convert the filename to the system encoding. */
  26675. zConverted = convertUtf8Filename(zUtf8Name);
  26676. if( zConverted==0 ){
  26677. return SQLITE_NOMEM;
  26678. }
  26679. if( flags & SQLITE_OPEN_READWRITE ){
  26680. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  26681. }else{
  26682. dwDesiredAccess = GENERIC_READ;
  26683. }
  26684. if( flags & SQLITE_OPEN_CREATE ){
  26685. dwCreationDisposition = OPEN_ALWAYS;
  26686. }else{
  26687. dwCreationDisposition = OPEN_EXISTING;
  26688. }
  26689. if( flags & SQLITE_OPEN_MAIN_DB ){
  26690. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  26691. }else{
  26692. dwShareMode = 0;
  26693. }
  26694. if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  26695. #if SQLITE_OS_WINCE
  26696. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  26697. isTemp = 1;
  26698. #else
  26699. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  26700. | FILE_ATTRIBUTE_HIDDEN
  26701. | FILE_FLAG_DELETE_ON_CLOSE;
  26702. #endif
  26703. }else{
  26704. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  26705. }
  26706. /* Reports from the internet are that performance is always
  26707. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  26708. #if SQLITE_OS_WINCE
  26709. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  26710. #endif
  26711. if( isNT() ){
  26712. h = CreateFileW((WCHAR*)zConverted,
  26713. dwDesiredAccess,
  26714. dwShareMode,
  26715. NULL,
  26716. dwCreationDisposition,
  26717. dwFlagsAndAttributes,
  26718. NULL
  26719. );
  26720. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  26721. ** Since the ASCII version of these Windows API do not exist for WINCE,
  26722. ** it's important to not reference them for WINCE builds.
  26723. */
  26724. #if SQLITE_OS_WINCE==0
  26725. }else{
  26726. h = CreateFileA((char*)zConverted,
  26727. dwDesiredAccess,
  26728. dwShareMode,
  26729. NULL,
  26730. dwCreationDisposition,
  26731. dwFlagsAndAttributes,
  26732. NULL
  26733. );
  26734. #endif
  26735. }
  26736. if( h==INVALID_HANDLE_VALUE ){
  26737. free(zConverted);
  26738. if( flags & SQLITE_OPEN_READWRITE ){
  26739. return winOpen(0, zName, id,
  26740. ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
  26741. }else{
  26742. return SQLITE_CANTOPEN;
  26743. }
  26744. }
  26745. if( pOutFlags ){
  26746. if( flags & SQLITE_OPEN_READWRITE ){
  26747. *pOutFlags = SQLITE_OPEN_READWRITE;
  26748. }else{
  26749. *pOutFlags = SQLITE_OPEN_READONLY;
  26750. }
  26751. }
  26752. memset(pFile, 0, sizeof(*pFile));
  26753. pFile->pMethod = &winIoMethod;
  26754. pFile->h = h;
  26755. #if SQLITE_OS_WINCE
  26756. if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
  26757. (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
  26758. && !winceCreateLock(zName, pFile)
  26759. ){
  26760. CloseHandle(h);
  26761. free(zConverted);
  26762. return SQLITE_CANTOPEN;
  26763. }
  26764. if( isTemp ){
  26765. pFile->zDeleteOnClose = zConverted;
  26766. }else
  26767. #endif
  26768. {
  26769. free(zConverted);
  26770. }
  26771. OpenCounter(+1);
  26772. return SQLITE_OK;
  26773. }
  26774. /*
  26775. ** Delete the named file.
  26776. **
  26777. ** Note that windows does not allow a file to be deleted if some other
  26778. ** process has it open. Sometimes a virus scanner or indexing program
  26779. ** will open a journal file shortly after it is created in order to do
  26780. ** whatever it does. While this other process is holding the
  26781. ** file open, we will be unable to delete it. To work around this
  26782. ** problem, we delay 100 milliseconds and try to delete again. Up
  26783. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  26784. ** up and returning an error.
  26785. */
  26786. #define MX_DELETION_ATTEMPTS 5
  26787. static int winDelete(
  26788. sqlite3_vfs *pVfs, /* Not used on win32 */
  26789. const char *zFilename, /* Name of file to delete */
  26790. int syncDir /* Not used on win32 */
  26791. ){
  26792. int cnt = 0;
  26793. DWORD rc;
  26794. DWORD error = 0;
  26795. void *zConverted = convertUtf8Filename(zFilename);
  26796. UNUSED_PARAMETER(pVfs);
  26797. UNUSED_PARAMETER(syncDir);
  26798. if( zConverted==0 ){
  26799. return SQLITE_NOMEM;
  26800. }
  26801. SimulateIOError(return SQLITE_IOERR_DELETE);
  26802. if( isNT() ){
  26803. do{
  26804. DeleteFileW(zConverted);
  26805. }while( ( ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
  26806. || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
  26807. && (++cnt < MX_DELETION_ATTEMPTS)
  26808. && (Sleep(100), 1) );
  26809. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  26810. ** Since the ASCII version of these Windows API do not exist for WINCE,
  26811. ** it's important to not reference them for WINCE builds.
  26812. */
  26813. #if SQLITE_OS_WINCE==0
  26814. }else{
  26815. do{
  26816. DeleteFileA(zConverted);
  26817. }while( ( ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
  26818. || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
  26819. && (++cnt < MX_DELETION_ATTEMPTS)
  26820. && (Sleep(100), 1) );
  26821. #endif
  26822. }
  26823. free(zConverted);
  26824. OSTRACE2("DELETE \"%s\"\n", zFilename);
  26825. return ( (rc == INVALID_FILE_ATTRIBUTES)
  26826. && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
  26827. }
  26828. /*
  26829. ** Check the existance and status of a file.
  26830. */
  26831. static int winAccess(
  26832. sqlite3_vfs *pVfs, /* Not used on win32 */
  26833. const char *zFilename, /* Name of file to check */
  26834. int flags, /* Type of test to make on this file */
  26835. int *pResOut /* OUT: Result */
  26836. ){
  26837. DWORD attr;
  26838. int rc = 0;
  26839. void *zConverted = convertUtf8Filename(zFilename);
  26840. UNUSED_PARAMETER(pVfs);
  26841. if( zConverted==0 ){
  26842. return SQLITE_NOMEM;
  26843. }
  26844. if( isNT() ){
  26845. attr = GetFileAttributesW((WCHAR*)zConverted);
  26846. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  26847. ** Since the ASCII version of these Windows API do not exist for WINCE,
  26848. ** it's important to not reference them for WINCE builds.
  26849. */
  26850. #if SQLITE_OS_WINCE==0
  26851. }else{
  26852. attr = GetFileAttributesA((char*)zConverted);
  26853. #endif
  26854. }
  26855. free(zConverted);
  26856. switch( flags ){
  26857. case SQLITE_ACCESS_READ:
  26858. case SQLITE_ACCESS_EXISTS:
  26859. rc = attr!=INVALID_FILE_ATTRIBUTES;
  26860. break;
  26861. case SQLITE_ACCESS_READWRITE:
  26862. rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
  26863. break;
  26864. default:
  26865. assert(!"Invalid flags argument");
  26866. }
  26867. *pResOut = rc;
  26868. return SQLITE_OK;
  26869. }
  26870. /*
  26871. ** Turn a relative pathname into a full pathname. Write the full
  26872. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  26873. ** bytes in size.
  26874. */
  26875. static int winFullPathname(
  26876. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  26877. const char *zRelative, /* Possibly relative input path */
  26878. int nFull, /* Size of output buffer in bytes */
  26879. char *zFull /* Output buffer */
  26880. ){
  26881. #if defined(__CYGWIN__)
  26882. UNUSED_PARAMETER(nFull);
  26883. cygwin_conv_to_full_win32_path(zRelative, zFull);
  26884. return SQLITE_OK;
  26885. #endif
  26886. #if SQLITE_OS_WINCE
  26887. UNUSED_PARAMETER(nFull);
  26888. /* WinCE has no concept of a relative pathname, or so I am told. */
  26889. sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
  26890. return SQLITE_OK;
  26891. #endif
  26892. #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
  26893. int nByte;
  26894. void *zConverted;
  26895. char *zOut;
  26896. UNUSED_PARAMETER(nFull);
  26897. zConverted = convertUtf8Filename(zRelative);
  26898. if( isNT() ){
  26899. WCHAR *zTemp;
  26900. nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
  26901. zTemp = malloc( nByte*sizeof(zTemp[0]) );
  26902. if( zTemp==0 ){
  26903. free(zConverted);
  26904. return SQLITE_NOMEM;
  26905. }
  26906. GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
  26907. free(zConverted);
  26908. zOut = unicodeToUtf8(zTemp);
  26909. free(zTemp);
  26910. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  26911. ** Since the ASCII version of these Windows API do not exist for WINCE,
  26912. ** it's important to not reference them for WINCE builds.
  26913. */
  26914. #if SQLITE_OS_WINCE==0
  26915. }else{
  26916. char *zTemp;
  26917. nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
  26918. zTemp = malloc( nByte*sizeof(zTemp[0]) );
  26919. if( zTemp==0 ){
  26920. free(zConverted);
  26921. return SQLITE_NOMEM;
  26922. }
  26923. GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  26924. free(zConverted);
  26925. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  26926. free(zTemp);
  26927. #endif
  26928. }
  26929. if( zOut ){
  26930. sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
  26931. free(zOut);
  26932. return SQLITE_OK;
  26933. }else{
  26934. return SQLITE_NOMEM;
  26935. }
  26936. #endif
  26937. }
  26938. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  26939. /*
  26940. ** Interfaces for opening a shared library, finding entry points
  26941. ** within the shared library, and closing the shared library.
  26942. */
  26943. /*
  26944. ** Interfaces for opening a shared library, finding entry points
  26945. ** within the shared library, and closing the shared library.
  26946. */
  26947. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  26948. HANDLE h;
  26949. void *zConverted = convertUtf8Filename(zFilename);
  26950. UNUSED_PARAMETER(pVfs);
  26951. if( zConverted==0 ){
  26952. return 0;
  26953. }
  26954. if( isNT() ){
  26955. h = LoadLibraryW((WCHAR*)zConverted);
  26956. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  26957. ** Since the ASCII version of these Windows API do not exist for WINCE,
  26958. ** it's important to not reference them for WINCE builds.
  26959. */
  26960. #if SQLITE_OS_WINCE==0
  26961. }else{
  26962. h = LoadLibraryA((char*)zConverted);
  26963. #endif
  26964. }
  26965. free(zConverted);
  26966. return (void*)h;
  26967. }
  26968. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  26969. UNUSED_PARAMETER(pVfs);
  26970. getLastErrorMsg(nBuf, zBufOut);
  26971. }
  26972. void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
  26973. UNUSED_PARAMETER(pVfs);
  26974. #if SQLITE_OS_WINCE
  26975. /* The GetProcAddressA() routine is only available on wince. */
  26976. return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
  26977. #else
  26978. /* All other windows platforms expect GetProcAddress() to take
  26979. ** an Ansi string regardless of the _UNICODE setting */
  26980. return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
  26981. #endif
  26982. }
  26983. void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  26984. UNUSED_PARAMETER(pVfs);
  26985. FreeLibrary((HANDLE)pHandle);
  26986. }
  26987. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  26988. #define winDlOpen 0
  26989. #define winDlError 0
  26990. #define winDlSym 0
  26991. #define winDlClose 0
  26992. #endif
  26993. /*
  26994. ** Write up to nBuf bytes of randomness into zBuf.
  26995. */
  26996. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  26997. int n = 0;
  26998. UNUSED_PARAMETER(pVfs);
  26999. #if defined(SQLITE_TEST)
  27000. n = nBuf;
  27001. memset(zBuf, 0, nBuf);
  27002. #else
  27003. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  27004. SYSTEMTIME x;
  27005. GetSystemTime(&x);
  27006. memcpy(&zBuf[n], &x, sizeof(x));
  27007. n += sizeof(x);
  27008. }
  27009. if( sizeof(DWORD)<=nBuf-n ){
  27010. DWORD pid = GetCurrentProcessId();
  27011. memcpy(&zBuf[n], &pid, sizeof(pid));
  27012. n += sizeof(pid);
  27013. }
  27014. if( sizeof(DWORD)<=nBuf-n ){
  27015. DWORD cnt = GetTickCount();
  27016. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  27017. n += sizeof(cnt);
  27018. }
  27019. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  27020. LARGE_INTEGER i;
  27021. QueryPerformanceCounter(&i);
  27022. memcpy(&zBuf[n], &i, sizeof(i));
  27023. n += sizeof(i);
  27024. }
  27025. #endif
  27026. return n;
  27027. }
  27028. /*
  27029. ** Sleep for a little while. Return the amount of time slept.
  27030. */
  27031. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  27032. Sleep((microsec+999)/1000);
  27033. UNUSED_PARAMETER(pVfs);
  27034. return ((microsec+999)/1000)*1000;
  27035. }
  27036. /*
  27037. ** The following variable, if set to a non-zero value, becomes the result
  27038. ** returned from sqlite3OsCurrentTime(). This is used for testing.
  27039. */
  27040. #ifdef SQLITE_TEST
  27041. SQLITE_API int sqlite3_current_time = 0;
  27042. #endif
  27043. /*
  27044. ** Find the current time (in Universal Coordinated Time). Write the
  27045. ** current time and date as a Julian Day number into *prNow and
  27046. ** return 0. Return 1 if the time and date cannot be found.
  27047. */
  27048. int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  27049. FILETIME ft;
  27050. /* FILETIME structure is a 64-bit value representing the number of
  27051. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  27052. */
  27053. double now;
  27054. #if SQLITE_OS_WINCE
  27055. SYSTEMTIME time;
  27056. GetSystemTime(&time);
  27057. /* if SystemTimeToFileTime() fails, it returns zero. */
  27058. if (!SystemTimeToFileTime(&time,&ft)){
  27059. return 1;
  27060. }
  27061. #else
  27062. GetSystemTimeAsFileTime( &ft );
  27063. #endif
  27064. UNUSED_PARAMETER(pVfs);
  27065. now = ((double)ft.dwHighDateTime) * 4294967296.0;
  27066. *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
  27067. #ifdef SQLITE_TEST
  27068. if( sqlite3_current_time ){
  27069. *prNow = sqlite3_current_time/86400.0 + 2440587.5;
  27070. }
  27071. #endif
  27072. return 0;
  27073. }
  27074. /*
  27075. ** The idea is that this function works like a combination of
  27076. ** GetLastError() and FormatMessage() on windows (or errno and
  27077. ** strerror_r() on unix). After an error is returned by an OS
  27078. ** function, SQLite calls this function with zBuf pointing to
  27079. ** a buffer of nBuf bytes. The OS layer should populate the
  27080. ** buffer with a nul-terminated UTF-8 encoded error message
  27081. ** describing the last IO error to have occured within the calling
  27082. ** thread.
  27083. **
  27084. ** If the error message is too large for the supplied buffer,
  27085. ** it should be truncated. The return value of xGetLastError
  27086. ** is zero if the error message fits in the buffer, or non-zero
  27087. ** otherwise (if the message was truncated). If non-zero is returned,
  27088. ** then it is not necessary to include the nul-terminator character
  27089. ** in the output buffer.
  27090. **
  27091. ** Not supplying an error message will have no adverse effect
  27092. ** on SQLite. It is fine to have an implementation that never
  27093. ** returns an error message:
  27094. **
  27095. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  27096. ** assert(zBuf[0]=='\0');
  27097. ** return 0;
  27098. ** }
  27099. **
  27100. ** However if an error message is supplied, it will be incorporated
  27101. ** by sqlite into the error message available to the user using
  27102. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  27103. */
  27104. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  27105. UNUSED_PARAMETER(pVfs);
  27106. return getLastErrorMsg(nBuf, zBuf);
  27107. }
  27108. /*
  27109. ** Initialize and deinitialize the operating system interface.
  27110. */
  27111. SQLITE_API int sqlite3_os_init(void){
  27112. static sqlite3_vfs winVfs = {
  27113. 1, /* iVersion */
  27114. sizeof(winFile), /* szOsFile */
  27115. MAX_PATH, /* mxPathname */
  27116. 0, /* pNext */
  27117. "win32", /* zName */
  27118. 0, /* pAppData */
  27119. winOpen, /* xOpen */
  27120. winDelete, /* xDelete */
  27121. winAccess, /* xAccess */
  27122. winFullPathname, /* xFullPathname */
  27123. winDlOpen, /* xDlOpen */
  27124. winDlError, /* xDlError */
  27125. winDlSym, /* xDlSym */
  27126. winDlClose, /* xDlClose */
  27127. winRandomness, /* xRandomness */
  27128. winSleep, /* xSleep */
  27129. winCurrentTime, /* xCurrentTime */
  27130. winGetLastError /* xGetLastError */
  27131. };
  27132. sqlite3_vfs_register(&winVfs, 1);
  27133. return SQLITE_OK;
  27134. }
  27135. SQLITE_API int sqlite3_os_end(void){
  27136. return SQLITE_OK;
  27137. }
  27138. #endif /* SQLITE_OS_WIN */
  27139. /************** End of os_win.c **********************************************/
  27140. /************** Begin file bitvec.c ******************************************/
  27141. /*
  27142. ** 2008 February 16
  27143. **
  27144. ** The author disclaims copyright to this source code. In place of
  27145. ** a legal notice, here is a blessing:
  27146. **
  27147. ** May you do good and not evil.
  27148. ** May you find forgiveness for yourself and forgive others.
  27149. ** May you share freely, never taking more than you give.
  27150. **
  27151. *************************************************************************
  27152. ** This file implements an object that represents a fixed-length
  27153. ** bitmap. Bits are numbered starting with 1.
  27154. **
  27155. ** A bitmap is used to record which pages of a database file have been
  27156. ** journalled during a transaction, or which pages have the "dont-write"
  27157. ** property. Usually only a few pages are meet either condition.
  27158. ** So the bitmap is usually sparse and has low cardinality.
  27159. ** But sometimes (for example when during a DROP of a large table) most
  27160. ** or all of the pages in a database can get journalled. In those cases,
  27161. ** the bitmap becomes dense with high cardinality. The algorithm needs
  27162. ** to handle both cases well.
  27163. **
  27164. ** The size of the bitmap is fixed when the object is created.
  27165. **
  27166. ** All bits are clear when the bitmap is created. Individual bits
  27167. ** may be set or cleared one at a time.
  27168. **
  27169. ** Test operations are about 100 times more common that set operations.
  27170. ** Clear operations are exceedingly rare. There are usually between
  27171. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  27172. ** sometimes grow into tens of thousands or larger. The size of the
  27173. ** Bitvec object is the number of pages in the database file at the
  27174. ** start of a transaction, and is thus usually less than a few thousand,
  27175. ** but can be as large as 2 billion for a really big database.
  27176. **
  27177. ** @(#) $Id: bitvec.c,v 1.10 2009/01/02 21:39:39 drh Exp $
  27178. */
  27179. /* Size of the Bitvec structure in bytes. */
  27180. #define BITVEC_SZ 512
  27181. /* Round the union size down to the nearest pointer boundary, since that's how
  27182. ** it will be aligned within the Bitvec struct. */
  27183. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  27184. /* Type of the array "element" for the bitmap representation.
  27185. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  27186. ** Setting this to the "natural word" size of your CPU may improve
  27187. ** performance. */
  27188. #define BITVEC_TELEM u8
  27189. /* Size, in bits, of the bitmap element. */
  27190. #define BITVEC_SZELEM 8
  27191. /* Number of elements in a bitmap array. */
  27192. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  27193. /* Number of bits in the bitmap array. */
  27194. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  27195. /* Number of u32 values in hash table. */
  27196. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  27197. /* Maximum number of entries in hash table before
  27198. ** sub-dividing and re-hashing. */
  27199. #define BITVEC_MXHASH (BITVEC_NINT/2)
  27200. /* Hashing function for the aHash representation.
  27201. ** Empirical testing showed that the *37 multiplier
  27202. ** (an arbitrary prime)in the hash function provided
  27203. ** no fewer collisions than the no-op *1. */
  27204. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  27205. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  27206. /*
  27207. ** A bitmap is an instance of the following structure.
  27208. **
  27209. ** This bitmap records the existance of zero or more bits
  27210. ** with values between 1 and iSize, inclusive.
  27211. **
  27212. ** There are three possible representations of the bitmap.
  27213. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  27214. ** bitmap. The least significant bit is bit 1.
  27215. **
  27216. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  27217. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  27218. **
  27219. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  27220. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  27221. ** handles up to iDivisor separate values of i. apSub[0] holds
  27222. ** values between 1 and iDivisor. apSub[1] holds values between
  27223. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  27224. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  27225. ** to hold deal with values between 1 and iDivisor.
  27226. */
  27227. struct Bitvec {
  27228. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  27229. u32 nSet; /* Number of bits that are set - only valid for aHash element */
  27230. /* Max nSet is BITVEC_NINT. For BITVEC_SZ of 512, this would be 125. */
  27231. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  27232. /* Should >=0 for apSub element. */
  27233. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  27234. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  27235. union {
  27236. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  27237. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  27238. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  27239. } u;
  27240. };
  27241. /*
  27242. ** Create a new bitmap object able to handle bits between 0 and iSize,
  27243. ** inclusive. Return a pointer to the new object. Return NULL if
  27244. ** malloc fails.
  27245. */
  27246. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  27247. Bitvec *p;
  27248. assert( sizeof(*p)==BITVEC_SZ );
  27249. p = sqlite3MallocZero( sizeof(*p) );
  27250. if( p ){
  27251. p->iSize = iSize;
  27252. }
  27253. return p;
  27254. }
  27255. /*
  27256. ** Check to see if the i-th bit is set. Return true or false.
  27257. ** If p is NULL (if the bitmap has not been created) or if
  27258. ** i is out of range, then return false.
  27259. */
  27260. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  27261. if( p==0 ) return 0;
  27262. if( i>p->iSize || i==0 ) return 0;
  27263. i--;
  27264. while( p->iDivisor ){
  27265. u32 bin = i/p->iDivisor;
  27266. i = i%p->iDivisor;
  27267. p = p->u.apSub[bin];
  27268. if (!p) {
  27269. return 0;
  27270. }
  27271. }
  27272. if( p->iSize<=BITVEC_NBIT ){
  27273. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  27274. } else{
  27275. u32 h = BITVEC_HASH(i++);
  27276. while( p->u.aHash[h] ){
  27277. if( p->u.aHash[h]==i ) return 1;
  27278. h++;
  27279. if( h>=BITVEC_NINT ) h = 0;
  27280. }
  27281. return 0;
  27282. }
  27283. }
  27284. /*
  27285. ** Set the i-th bit. Return 0 on success and an error code if
  27286. ** anything goes wrong.
  27287. **
  27288. ** This routine might cause sub-bitmaps to be allocated. Failing
  27289. ** to get the memory needed to hold the sub-bitmap is the only
  27290. ** that can go wrong with an insert, assuming p and i are valid.
  27291. **
  27292. ** The calling function must ensure that p is a valid Bitvec object
  27293. ** and that the value for "i" is within range of the Bitvec object.
  27294. ** Otherwise the behavior is undefined.
  27295. */
  27296. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  27297. u32 h;
  27298. assert( p!=0 );
  27299. assert( i>0 );
  27300. assert( i<=p->iSize );
  27301. i--;
  27302. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  27303. u32 bin = i/p->iDivisor;
  27304. i = i%p->iDivisor;
  27305. if( p->u.apSub[bin]==0 ){
  27306. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  27307. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  27308. }
  27309. p = p->u.apSub[bin];
  27310. }
  27311. if( p->iSize<=BITVEC_NBIT ){
  27312. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  27313. return SQLITE_OK;
  27314. }
  27315. h = BITVEC_HASH(i++);
  27316. /* if there wasn't a hash collision, and this doesn't */
  27317. /* completely fill the hash, then just add it without */
  27318. /* worring about sub-dividing and re-hashing. */
  27319. if( !p->u.aHash[h] ){
  27320. if (p->nSet<(BITVEC_NINT-1)) {
  27321. goto bitvec_set_end;
  27322. } else {
  27323. goto bitvec_set_rehash;
  27324. }
  27325. }
  27326. /* there was a collision, check to see if it's already */
  27327. /* in hash, if not, try to find a spot for it */
  27328. do {
  27329. if( p->u.aHash[h]==i ) return SQLITE_OK;
  27330. h++;
  27331. if( h>=BITVEC_NINT ) h = 0;
  27332. } while( p->u.aHash[h] );
  27333. /* we didn't find it in the hash. h points to the first */
  27334. /* available free spot. check to see if this is going to */
  27335. /* make our hash too "full". */
  27336. bitvec_set_rehash:
  27337. if( p->nSet>=BITVEC_MXHASH ){
  27338. unsigned int j;
  27339. int rc;
  27340. u32 aiValues[BITVEC_NINT];
  27341. memcpy(aiValues, p->u.aHash, sizeof(aiValues));
  27342. memset(p->u.apSub, 0, sizeof(aiValues));
  27343. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  27344. rc = sqlite3BitvecSet(p, i);
  27345. for(j=0; j<BITVEC_NINT; j++){
  27346. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  27347. }
  27348. return rc;
  27349. }
  27350. bitvec_set_end:
  27351. p->nSet++;
  27352. p->u.aHash[h] = i;
  27353. return SQLITE_OK;
  27354. }
  27355. /*
  27356. ** Clear the i-th bit.
  27357. */
  27358. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i){
  27359. assert( p!=0 );
  27360. assert( i>0 );
  27361. i--;
  27362. while( p->iDivisor ){
  27363. u32 bin = i/p->iDivisor;
  27364. i = i%p->iDivisor;
  27365. p = p->u.apSub[bin];
  27366. if (!p) {
  27367. return;
  27368. }
  27369. }
  27370. if( p->iSize<=BITVEC_NBIT ){
  27371. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  27372. }else{
  27373. unsigned int j;
  27374. u32 aiValues[BITVEC_NINT];
  27375. memcpy(aiValues, p->u.aHash, sizeof(aiValues));
  27376. memset(p->u.aHash, 0, sizeof(aiValues));
  27377. p->nSet = 0;
  27378. for(j=0; j<BITVEC_NINT; j++){
  27379. if( aiValues[j] && aiValues[j]!=(i+1) ){
  27380. u32 h = BITVEC_HASH(aiValues[j]-1);
  27381. p->nSet++;
  27382. while( p->u.aHash[h] ){
  27383. h++;
  27384. if( h>=BITVEC_NINT ) h = 0;
  27385. }
  27386. p->u.aHash[h] = aiValues[j];
  27387. }
  27388. }
  27389. }
  27390. }
  27391. /*
  27392. ** Destroy a bitmap object. Reclaim all memory used.
  27393. */
  27394. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  27395. if( p==0 ) return;
  27396. if( p->iDivisor ){
  27397. unsigned int i;
  27398. for(i=0; i<BITVEC_NPTR; i++){
  27399. sqlite3BitvecDestroy(p->u.apSub[i]);
  27400. }
  27401. }
  27402. sqlite3_free(p);
  27403. }
  27404. #ifndef SQLITE_OMIT_BUILTIN_TEST
  27405. /*
  27406. ** Let V[] be an array of unsigned characters sufficient to hold
  27407. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  27408. ** Then the following macros can be used to set, clear, or test
  27409. ** individual bits within V.
  27410. */
  27411. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  27412. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  27413. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  27414. /*
  27415. ** This routine runs an extensive test of the Bitvec code.
  27416. **
  27417. ** The input is an array of integers that acts as a program
  27418. ** to test the Bitvec. The integers are opcodes followed
  27419. ** by 0, 1, or 3 operands, depending on the opcode. Another
  27420. ** opcode follows immediately after the last operand.
  27421. **
  27422. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  27423. ** "halt" opcode and causes the test to end.
  27424. **
  27425. ** 0 Halt and return the number of errors
  27426. ** 1 N S X Set N bits beginning with S and incrementing by X
  27427. ** 2 N S X Clear N bits beginning with S and incrementing by X
  27428. ** 3 N Set N randomly chosen bits
  27429. ** 4 N Clear N randomly chosen bits
  27430. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  27431. **
  27432. ** The opcodes 1 through 4 perform set and clear operations are performed
  27433. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  27434. ** Opcode 5 works on the linear array only, not on the Bitvec.
  27435. ** Opcode 5 is used to deliberately induce a fault in order to
  27436. ** confirm that error detection works.
  27437. **
  27438. ** At the conclusion of the test the linear array is compared
  27439. ** against the Bitvec object. If there are any differences,
  27440. ** an error is returned. If they are the same, zero is returned.
  27441. **
  27442. ** If a memory allocation error occurs, return -1.
  27443. */
  27444. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  27445. Bitvec *pBitvec = 0;
  27446. unsigned char *pV = 0;
  27447. int rc = -1;
  27448. int i, nx, pc, op;
  27449. /* Allocate the Bitvec to be tested and a linear array of
  27450. ** bits to act as the reference */
  27451. pBitvec = sqlite3BitvecCreate( sz );
  27452. pV = sqlite3_malloc( (sz+7)/8 + 1 );
  27453. if( pBitvec==0 || pV==0 ) goto bitvec_end;
  27454. memset(pV, 0, (sz+7)/8 + 1);
  27455. /* Run the program */
  27456. pc = 0;
  27457. while( (op = aOp[pc])!=0 ){
  27458. switch( op ){
  27459. case 1:
  27460. case 2:
  27461. case 5: {
  27462. nx = 4;
  27463. i = aOp[pc+2] - 1;
  27464. aOp[pc+2] += aOp[pc+3];
  27465. break;
  27466. }
  27467. case 3:
  27468. case 4:
  27469. default: {
  27470. nx = 2;
  27471. sqlite3_randomness(sizeof(i), &i);
  27472. break;
  27473. }
  27474. }
  27475. if( (--aOp[pc+1]) > 0 ) nx = 0;
  27476. pc += nx;
  27477. i = (i & 0x7fffffff)%sz;
  27478. if( (op & 1)!=0 ){
  27479. SETBIT(pV, (i+1));
  27480. if( op!=5 ){
  27481. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  27482. }
  27483. }else{
  27484. CLEARBIT(pV, (i+1));
  27485. sqlite3BitvecClear(pBitvec, i+1);
  27486. }
  27487. }
  27488. /* Test to make sure the linear array exactly matches the
  27489. ** Bitvec object. Start with the assumption that they do
  27490. ** match (rc==0). Change rc to non-zero if a discrepancy
  27491. ** is found.
  27492. */
  27493. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  27494. + sqlite3BitvecTest(pBitvec, 0);
  27495. for(i=1; i<=sz; i++){
  27496. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  27497. rc = i;
  27498. break;
  27499. }
  27500. }
  27501. /* Free allocated structure */
  27502. bitvec_end:
  27503. sqlite3_free(pV);
  27504. sqlite3BitvecDestroy(pBitvec);
  27505. return rc;
  27506. }
  27507. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  27508. /************** End of bitvec.c **********************************************/
  27509. /************** Begin file pcache.c ******************************************/
  27510. /*
  27511. ** 2008 August 05
  27512. **
  27513. ** The author disclaims copyright to this source code. In place of
  27514. ** a legal notice, here is a blessing:
  27515. **
  27516. ** May you do good and not evil.
  27517. ** May you find forgiveness for yourself and forgive others.
  27518. ** May you share freely, never taking more than you give.
  27519. **
  27520. *************************************************************************
  27521. ** This file implements that page cache.
  27522. **
  27523. ** @(#) $Id: pcache.c,v 1.39 2008/12/04 20:40:10 drh Exp $
  27524. */
  27525. /*
  27526. ** A complete page cache is an instance of this structure.
  27527. */
  27528. struct PCache {
  27529. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  27530. PgHdr *pSynced; /* Last synced page in dirty page list */
  27531. int nRef; /* Number of referenced pages */
  27532. int nMax; /* Configured cache size */
  27533. int nMin; /* Configured minimum cache size */
  27534. int szPage; /* Size of every page in this cache */
  27535. int szExtra; /* Size of extra space for each page */
  27536. int bPurgeable; /* True if pages are on backing store */
  27537. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  27538. void *pStress; /* Argument to xStress */
  27539. sqlite3_pcache *pCache; /* Pluggable cache module */
  27540. PgHdr *pPage1;
  27541. };
  27542. /*
  27543. ** Some of the assert() macros in this code are too expensive to run
  27544. ** even during normal debugging. Use them only rarely on long-running
  27545. ** tests. Enable the expensive asserts using the
  27546. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  27547. */
  27548. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  27549. # define expensive_assert(X) assert(X)
  27550. #else
  27551. # define expensive_assert(X)
  27552. #endif
  27553. /********************************** Linked List Management ********************/
  27554. #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
  27555. /*
  27556. ** Check that the pCache->pSynced variable is set correctly. If it
  27557. ** is not, either fail an assert or return zero. Otherwise, return
  27558. ** non-zero. This is only used in debugging builds, as follows:
  27559. **
  27560. ** expensive_assert( pcacheCheckSynced(pCache) );
  27561. */
  27562. static int pcacheCheckSynced(PCache *pCache){
  27563. PgHdr *p;
  27564. for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
  27565. assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  27566. }
  27567. return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
  27568. }
  27569. #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
  27570. /*
  27571. ** Remove page pPage from the list of dirty pages.
  27572. */
  27573. static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  27574. PCache *p = pPage->pCache;
  27575. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  27576. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  27577. /* Update the PCache1.pSynced variable if necessary. */
  27578. if( p->pSynced==pPage ){
  27579. PgHdr *pSynced = pPage->pDirtyPrev;
  27580. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  27581. pSynced = pSynced->pDirtyPrev;
  27582. }
  27583. p->pSynced = pSynced;
  27584. }
  27585. if( pPage->pDirtyNext ){
  27586. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  27587. }else{
  27588. assert( pPage==p->pDirtyTail );
  27589. p->pDirtyTail = pPage->pDirtyPrev;
  27590. }
  27591. if( pPage->pDirtyPrev ){
  27592. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  27593. }else{
  27594. assert( pPage==p->pDirty );
  27595. p->pDirty = pPage->pDirtyNext;
  27596. }
  27597. pPage->pDirtyNext = 0;
  27598. pPage->pDirtyPrev = 0;
  27599. expensive_assert( pcacheCheckSynced(p) );
  27600. }
  27601. /*
  27602. ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
  27603. ** pPage).
  27604. */
  27605. static void pcacheAddToDirtyList(PgHdr *pPage){
  27606. PCache *p = pPage->pCache;
  27607. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  27608. pPage->pDirtyNext = p->pDirty;
  27609. if( pPage->pDirtyNext ){
  27610. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  27611. pPage->pDirtyNext->pDirtyPrev = pPage;
  27612. }
  27613. p->pDirty = pPage;
  27614. if( !p->pDirtyTail ){
  27615. p->pDirtyTail = pPage;
  27616. }
  27617. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  27618. p->pSynced = pPage;
  27619. }
  27620. expensive_assert( pcacheCheckSynced(p) );
  27621. }
  27622. /*
  27623. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  27624. ** being used for an in-memory database, this function is a no-op.
  27625. */
  27626. static void pcacheUnpin(PgHdr *p){
  27627. PCache *pCache = p->pCache;
  27628. if( pCache->bPurgeable ){
  27629. if( p->pgno==1 ){
  27630. pCache->pPage1 = 0;
  27631. }
  27632. sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
  27633. }
  27634. }
  27635. /*************************************************** General Interfaces ******
  27636. **
  27637. ** Initialize and shutdown the page cache subsystem. Neither of these
  27638. ** functions are threadsafe.
  27639. */
  27640. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  27641. if( sqlite3GlobalConfig.pcache.xInit==0 ){
  27642. sqlite3PCacheSetDefault();
  27643. }
  27644. return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
  27645. }
  27646. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  27647. if( sqlite3GlobalConfig.pcache.xShutdown ){
  27648. sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
  27649. }
  27650. }
  27651. /*
  27652. ** Return the size in bytes of a PCache object.
  27653. */
  27654. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  27655. /*
  27656. ** Create a new PCache object. Storage space to hold the object
  27657. ** has already been allocated and is passed in as the p pointer.
  27658. ** The caller discovers how much space needs to be allocated by
  27659. ** calling sqlite3PcacheSize().
  27660. */
  27661. SQLITE_PRIVATE void sqlite3PcacheOpen(
  27662. int szPage, /* Size of every page */
  27663. int szExtra, /* Extra space associated with each page */
  27664. int bPurgeable, /* True if pages are on backing store */
  27665. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  27666. void *pStress, /* Argument to xStress */
  27667. PCache *p /* Preallocated space for the PCache */
  27668. ){
  27669. memset(p, 0, sizeof(PCache));
  27670. p->szPage = szPage;
  27671. p->szExtra = szExtra;
  27672. p->bPurgeable = bPurgeable;
  27673. p->xStress = xStress;
  27674. p->pStress = pStress;
  27675. p->nMax = 100;
  27676. p->nMin = 10;
  27677. }
  27678. /*
  27679. ** Change the page size for PCache object. The caller must ensure that there
  27680. ** are no outstanding page references when this function is called.
  27681. */
  27682. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  27683. assert( pCache->nRef==0 && pCache->pDirty==0 );
  27684. if( pCache->pCache ){
  27685. sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
  27686. pCache->pCache = 0;
  27687. }
  27688. pCache->szPage = szPage;
  27689. }
  27690. /*
  27691. ** Try to obtain a page from the cache.
  27692. */
  27693. SQLITE_PRIVATE int sqlite3PcacheFetch(
  27694. PCache *pCache, /* Obtain the page from this cache */
  27695. Pgno pgno, /* Page number to obtain */
  27696. int createFlag, /* If true, create page if it does not exist already */
  27697. PgHdr **ppPage /* Write the page here */
  27698. ){
  27699. PgHdr *pPage = 0;
  27700. int eCreate;
  27701. assert( pCache!=0 );
  27702. assert( pgno>0 );
  27703. /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  27704. ** allocate it now.
  27705. */
  27706. if( !pCache->pCache && createFlag ){
  27707. sqlite3_pcache *p;
  27708. int nByte;
  27709. nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
  27710. p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
  27711. if( !p ){
  27712. return SQLITE_NOMEM;
  27713. }
  27714. sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
  27715. pCache->pCache = p;
  27716. }
  27717. eCreate = createFlag ? 1 : 0;
  27718. if( eCreate && (!pCache->bPurgeable || !pCache->pDirty) ){
  27719. eCreate = 2;
  27720. }
  27721. if( pCache->pCache ){
  27722. pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
  27723. }
  27724. if( !pPage && eCreate==1 ){
  27725. PgHdr *pPg;
  27726. /* Find a dirty page to write-out and recycle. First try to find a
  27727. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  27728. ** cleared), but if that is not possible settle for any other
  27729. ** unreferenced dirty page.
  27730. */
  27731. expensive_assert( pcacheCheckSynced(pCache) );
  27732. for(pPg=pCache->pSynced;
  27733. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  27734. pPg=pPg->pDirtyPrev
  27735. );
  27736. if( !pPg ){
  27737. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  27738. }
  27739. if( pPg ){
  27740. int rc;
  27741. rc = pCache->xStress(pCache->pStress, pPg);
  27742. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  27743. return rc;
  27744. }
  27745. }
  27746. pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
  27747. }
  27748. if( pPage ){
  27749. if( 0==pPage->nRef ){
  27750. pCache->nRef++;
  27751. }
  27752. pPage->nRef++;
  27753. pPage->pData = (void*)&pPage[1];
  27754. pPage->pExtra = (void*)&((char*)pPage->pData)[pCache->szPage];
  27755. pPage->pCache = pCache;
  27756. pPage->pgno = pgno;
  27757. if( pgno==1 ){
  27758. pCache->pPage1 = pPage;
  27759. }
  27760. }
  27761. *ppPage = pPage;
  27762. return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
  27763. }
  27764. /*
  27765. ** Decrement the reference count on a page. If the page is clean and the
  27766. ** reference count drops to 0, then it is made elible for recycling.
  27767. */
  27768. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
  27769. assert( p->nRef>0 );
  27770. p->nRef--;
  27771. if( p->nRef==0 ){
  27772. PCache *pCache = p->pCache;
  27773. pCache->nRef--;
  27774. if( (p->flags&PGHDR_DIRTY)==0 ){
  27775. pcacheUnpin(p);
  27776. }else{
  27777. /* Move the page to the head of the dirty list. */
  27778. pcacheRemoveFromDirtyList(p);
  27779. pcacheAddToDirtyList(p);
  27780. }
  27781. }
  27782. }
  27783. /*
  27784. ** Increase the reference count of a supplied page by 1.
  27785. */
  27786. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  27787. assert(p->nRef>0);
  27788. p->nRef++;
  27789. }
  27790. /*
  27791. ** Drop a page from the cache. There must be exactly one reference to the
  27792. ** page. This function deletes that reference, so after it returns the
  27793. ** page pointed to by p is invalid.
  27794. */
  27795. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  27796. PCache *pCache;
  27797. assert( p->nRef==1 );
  27798. if( p->flags&PGHDR_DIRTY ){
  27799. pcacheRemoveFromDirtyList(p);
  27800. }
  27801. pCache = p->pCache;
  27802. pCache->nRef--;
  27803. if( p->pgno==1 ){
  27804. pCache->pPage1 = 0;
  27805. }
  27806. sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
  27807. }
  27808. /*
  27809. ** Make sure the page is marked as dirty. If it isn't dirty already,
  27810. ** make it so.
  27811. */
  27812. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  27813. PCache *pCache;
  27814. p->flags &= ~PGHDR_DONT_WRITE;
  27815. assert( p->nRef>0 );
  27816. if( 0==(p->flags & PGHDR_DIRTY) ){
  27817. pCache = p->pCache;
  27818. p->flags |= PGHDR_DIRTY;
  27819. pcacheAddToDirtyList( p);
  27820. }
  27821. }
  27822. /*
  27823. ** Make sure the page is marked as clean. If it isn't clean already,
  27824. ** make it so.
  27825. */
  27826. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  27827. if( (p->flags & PGHDR_DIRTY) ){
  27828. pcacheRemoveFromDirtyList(p);
  27829. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  27830. if( p->nRef==0 ){
  27831. pcacheUnpin(p);
  27832. }
  27833. }
  27834. }
  27835. /*
  27836. ** Make every page in the cache clean.
  27837. */
  27838. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  27839. PgHdr *p;
  27840. while( (p = pCache->pDirty)!=0 ){
  27841. sqlite3PcacheMakeClean(p);
  27842. }
  27843. }
  27844. /*
  27845. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  27846. */
  27847. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  27848. PgHdr *p;
  27849. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  27850. p->flags &= ~PGHDR_NEED_SYNC;
  27851. }
  27852. pCache->pSynced = pCache->pDirtyTail;
  27853. }
  27854. /*
  27855. ** Change the page number of page p to newPgno.
  27856. */
  27857. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  27858. PCache *pCache = p->pCache;
  27859. assert( p->nRef>0 );
  27860. assert( newPgno>0 );
  27861. sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
  27862. p->pgno = newPgno;
  27863. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  27864. pcacheRemoveFromDirtyList(p);
  27865. pcacheAddToDirtyList(p);
  27866. }
  27867. }
  27868. /*
  27869. ** Drop every cache entry whose page number is greater than "pgno". The
  27870. ** caller must ensure that there are no outstanding references to any pages
  27871. ** other than page 1 with a page number greater than pgno.
  27872. **
  27873. ** If there is a reference to page 1 and the pgno parameter passed to this
  27874. ** function is 0, then the data area associated with page 1 is zeroed, but
  27875. ** the page object is not dropped.
  27876. */
  27877. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  27878. if( pCache->pCache ){
  27879. PgHdr *p;
  27880. PgHdr *pNext;
  27881. for(p=pCache->pDirty; p; p=pNext){
  27882. pNext = p->pDirtyNext;
  27883. if( p->pgno>pgno ){
  27884. assert( p->flags&PGHDR_DIRTY );
  27885. sqlite3PcacheMakeClean(p);
  27886. }
  27887. }
  27888. if( pgno==0 && pCache->pPage1 ){
  27889. memset(pCache->pPage1->pData, 0, pCache->szPage);
  27890. pgno = 1;
  27891. }
  27892. sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
  27893. }
  27894. }
  27895. /*
  27896. ** Close a cache.
  27897. */
  27898. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  27899. if( pCache->pCache ){
  27900. sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
  27901. }
  27902. }
  27903. /*
  27904. ** Discard the contents of the cache.
  27905. */
  27906. SQLITE_PRIVATE int sqlite3PcacheClear(PCache *pCache){
  27907. sqlite3PcacheTruncate(pCache, 0);
  27908. return SQLITE_OK;
  27909. }
  27910. /*
  27911. ** Merge two lists of pages connected by pDirty and in pgno order.
  27912. ** Do not both fixing the pDirtyPrev pointers.
  27913. */
  27914. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  27915. PgHdr result, *pTail;
  27916. pTail = &result;
  27917. while( pA && pB ){
  27918. if( pA->pgno<pB->pgno ){
  27919. pTail->pDirty = pA;
  27920. pTail = pA;
  27921. pA = pA->pDirty;
  27922. }else{
  27923. pTail->pDirty = pB;
  27924. pTail = pB;
  27925. pB = pB->pDirty;
  27926. }
  27927. }
  27928. if( pA ){
  27929. pTail->pDirty = pA;
  27930. }else if( pB ){
  27931. pTail->pDirty = pB;
  27932. }else{
  27933. pTail->pDirty = 0;
  27934. }
  27935. return result.pDirty;
  27936. }
  27937. /*
  27938. ** Sort the list of pages in accending order by pgno. Pages are
  27939. ** connected by pDirty pointers. The pDirtyPrev pointers are
  27940. ** corrupted by this sort.
  27941. */
  27942. #define N_SORT_BUCKET_ALLOC 25
  27943. #define N_SORT_BUCKET 25
  27944. #ifdef SQLITE_TEST
  27945. int sqlite3_pager_n_sort_bucket = 0;
  27946. #undef N_SORT_BUCKET
  27947. #define N_SORT_BUCKET \
  27948. (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
  27949. #endif
  27950. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  27951. PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
  27952. int i;
  27953. memset(a, 0, sizeof(a));
  27954. while( pIn ){
  27955. p = pIn;
  27956. pIn = p->pDirty;
  27957. p->pDirty = 0;
  27958. for(i=0; i<N_SORT_BUCKET-1; i++){
  27959. if( a[i]==0 ){
  27960. a[i] = p;
  27961. break;
  27962. }else{
  27963. p = pcacheMergeDirtyList(a[i], p);
  27964. a[i] = 0;
  27965. }
  27966. }
  27967. if( i==N_SORT_BUCKET-1 ){
  27968. /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET)
  27969. ** elements in the input list. This is possible, but impractical.
  27970. ** Testing this line is the point of global variable
  27971. ** sqlite3_pager_n_sort_bucket.
  27972. */
  27973. a[i] = pcacheMergeDirtyList(a[i], p);
  27974. }
  27975. }
  27976. p = a[0];
  27977. for(i=1; i<N_SORT_BUCKET; i++){
  27978. p = pcacheMergeDirtyList(p, a[i]);
  27979. }
  27980. return p;
  27981. }
  27982. /*
  27983. ** Return a list of all dirty pages in the cache, sorted by page number.
  27984. */
  27985. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  27986. PgHdr *p;
  27987. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  27988. p->pDirty = p->pDirtyNext;
  27989. }
  27990. return pcacheSortDirtyList(pCache->pDirty);
  27991. }
  27992. /*
  27993. ** Return the total number of referenced pages held by the cache.
  27994. */
  27995. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  27996. return pCache->nRef;
  27997. }
  27998. /*
  27999. ** Return the number of references to the page supplied as an argument.
  28000. */
  28001. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  28002. return p->nRef;
  28003. }
  28004. /*
  28005. ** Return the total number of pages in the cache.
  28006. */
  28007. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  28008. int nPage = 0;
  28009. if( pCache->pCache ){
  28010. nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
  28011. }
  28012. return nPage;
  28013. }
  28014. #ifdef SQLITE_TEST
  28015. /*
  28016. ** Get the suggested cache-size value.
  28017. */
  28018. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  28019. return pCache->nMax;
  28020. }
  28021. #endif
  28022. /*
  28023. ** Set the suggested cache-size value.
  28024. */
  28025. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  28026. pCache->nMax = mxPage;
  28027. if( pCache->pCache ){
  28028. sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
  28029. }
  28030. }
  28031. #ifdef SQLITE_CHECK_PAGES
  28032. /*
  28033. ** For all dirty pages currently in the cache, invoke the specified
  28034. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  28035. ** defined.
  28036. */
  28037. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  28038. PgHdr *pDirty;
  28039. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  28040. xIter(pDirty);
  28041. }
  28042. }
  28043. #endif
  28044. /************** End of pcache.c **********************************************/
  28045. /************** Begin file pcache1.c *****************************************/
  28046. /*
  28047. ** 2008 November 05
  28048. **
  28049. ** The author disclaims copyright to this source code. In place of
  28050. ** a legal notice, here is a blessing:
  28051. **
  28052. ** May you do good and not evil.
  28053. ** May you find forgiveness for yourself and forgive others.
  28054. ** May you share freely, never taking more than you give.
  28055. **
  28056. *************************************************************************
  28057. **
  28058. ** This file implements the default page cache implementation (the
  28059. ** sqlite3_pcache interface). It also contains part of the implementation
  28060. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  28061. ** If the default page cache implementation is overriden, then neither of
  28062. ** these two features are available.
  28063. **
  28064. ** @(#) $Id: pcache1.c,v 1.7 2009/01/07 15:18:21 danielk1977 Exp $
  28065. */
  28066. typedef struct PCache1 PCache1;
  28067. typedef struct PgHdr1 PgHdr1;
  28068. typedef struct PgFreeslot PgFreeslot;
  28069. /* Pointers to structures of this type are cast and returned as
  28070. ** opaque sqlite3_pcache* handles
  28071. */
  28072. struct PCache1 {
  28073. /* Cache configuration parameters. Page size (szPage) and the purgeable
  28074. ** flag (bPurgeable) are set when the cache is created. nMax may be
  28075. ** modified at any time by a call to the pcache1CacheSize() method.
  28076. ** The global mutex must be held when accessing nMax.
  28077. */
  28078. int szPage; /* Size of allocated pages in bytes */
  28079. int bPurgeable; /* True if cache is purgeable */
  28080. unsigned int nMin; /* Minimum number of pages reserved */
  28081. unsigned int nMax; /* Configured "cache_size" value */
  28082. /* Hash table of all pages. The following variables may only be accessed
  28083. ** when the accessor is holding the global mutex (see pcache1EnterMutex()
  28084. ** and pcache1LeaveMutex()).
  28085. */
  28086. unsigned int nRecyclable; /* Number of pages in the LRU list */
  28087. unsigned int nPage; /* Total number of pages in apHash */
  28088. unsigned int nHash; /* Number of slots in apHash[] */
  28089. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  28090. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  28091. };
  28092. /*
  28093. ** Each cache entry is represented by an instance of the following
  28094. ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
  28095. ** directly after the structure in memory (see the PGHDR1_TO_PAGE()
  28096. ** macro below).
  28097. */
  28098. struct PgHdr1 {
  28099. unsigned int iKey; /* Key value (page number) */
  28100. PgHdr1 *pNext; /* Next in hash table chain */
  28101. PCache1 *pCache; /* Cache that currently owns this page */
  28102. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  28103. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  28104. };
  28105. /*
  28106. ** Free slots in the allocator used to divide up the buffer provided using
  28107. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  28108. */
  28109. struct PgFreeslot {
  28110. PgFreeslot *pNext; /* Next free slot */
  28111. };
  28112. /*
  28113. ** Global data used by this cache.
  28114. */
  28115. static SQLITE_WSD struct PCacheGlobal {
  28116. sqlite3_mutex *mutex; /* static mutex MUTEX_STATIC_LRU */
  28117. int nMaxPage; /* Sum of nMaxPage for purgeable caches */
  28118. int nMinPage; /* Sum of nMinPage for purgeable caches */
  28119. int nCurrentPage; /* Number of purgeable pages allocated */
  28120. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  28121. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
  28122. int szSlot; /* Size of each free slot */
  28123. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  28124. PgFreeslot *pFree; /* Free page blocks */
  28125. } pcache1_g;
  28126. /*
  28127. ** All code in this file should access the global structure above via the
  28128. ** alias "pcache1". This ensures that the WSD emulation is used when
  28129. ** compiling for systems that do not support real WSD.
  28130. */
  28131. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  28132. /*
  28133. ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
  28134. ** bytes of data are located directly after it in memory (i.e. the total
  28135. ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
  28136. ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
  28137. ** an argument and returns a pointer to the associated block of szPage
  28138. ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
  28139. ** a pointer to a block of szPage bytes of data and the return value is
  28140. ** a pointer to the associated PgHdr1 structure.
  28141. **
  28142. ** assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(X))==X );
  28143. */
  28144. #define PGHDR1_TO_PAGE(p) (void *)(&((unsigned char *)p)[sizeof(PgHdr1)])
  28145. #define PAGE_TO_PGHDR1(p) (PgHdr1 *)(&((unsigned char *)p)[-1*(int)sizeof(PgHdr1)])
  28146. /*
  28147. ** Macros to enter and leave the global LRU mutex.
  28148. */
  28149. #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
  28150. #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
  28151. /******************************************************************************/
  28152. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  28153. /*
  28154. ** This function is called during initialization if a static buffer is
  28155. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  28156. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  28157. ** enough to contain 'n' buffers of 'sz' bytes each.
  28158. */
  28159. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  28160. PgFreeslot *p;
  28161. sz &= ~7;
  28162. pcache1.szSlot = sz;
  28163. pcache1.pStart = pBuf;
  28164. pcache1.pFree = 0;
  28165. while( n-- ){
  28166. p = (PgFreeslot*)pBuf;
  28167. p->pNext = pcache1.pFree;
  28168. pcache1.pFree = p;
  28169. pBuf = (void*)&((char*)pBuf)[sz];
  28170. }
  28171. pcache1.pEnd = pBuf;
  28172. }
  28173. /*
  28174. ** Malloc function used within this file to allocate space from the buffer
  28175. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  28176. ** such buffer exists or there is no space left in it, this function falls
  28177. ** back to sqlite3Malloc().
  28178. */
  28179. static void *pcache1Alloc(int nByte){
  28180. void *p;
  28181. assert( sqlite3_mutex_held(pcache1.mutex) );
  28182. if( nByte<=pcache1.szSlot && pcache1.pFree ){
  28183. p = (PgHdr1 *)pcache1.pFree;
  28184. pcache1.pFree = pcache1.pFree->pNext;
  28185. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  28186. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  28187. }else{
  28188. /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
  28189. ** global pcache mutex and unlock the pager-cache object pCache. This is
  28190. ** so that if the attempt to allocate a new buffer causes the the
  28191. ** configured soft-heap-limit to be breached, it will be possible to
  28192. ** reclaim memory from this pager-cache.
  28193. */
  28194. pcache1LeaveMutex();
  28195. p = sqlite3Malloc(nByte);
  28196. pcache1EnterMutex();
  28197. if( p ){
  28198. int sz = sqlite3MallocSize(p);
  28199. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  28200. }
  28201. }
  28202. return p;
  28203. }
  28204. /*
  28205. ** Free an allocated buffer obtained from pcache1Alloc().
  28206. */
  28207. static void pcache1Free(void *p){
  28208. assert( sqlite3_mutex_held(pcache1.mutex) );
  28209. if( p==0 ) return;
  28210. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  28211. PgFreeslot *pSlot;
  28212. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  28213. pSlot = (PgFreeslot*)p;
  28214. pSlot->pNext = pcache1.pFree;
  28215. pcache1.pFree = pSlot;
  28216. }else{
  28217. int iSize = sqlite3MallocSize(p);
  28218. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
  28219. sqlite3_free(p);
  28220. }
  28221. }
  28222. /*
  28223. ** Allocate a new page object initially associated with cache pCache.
  28224. */
  28225. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  28226. int nByte = sizeof(PgHdr1) + pCache->szPage;
  28227. PgHdr1 *p = (PgHdr1 *)pcache1Alloc(nByte);
  28228. if( p ){
  28229. memset(p, 0, nByte);
  28230. if( pCache->bPurgeable ){
  28231. pcache1.nCurrentPage++;
  28232. }
  28233. }
  28234. return p;
  28235. }
  28236. /*
  28237. ** Free a page object allocated by pcache1AllocPage().
  28238. */
  28239. static void pcache1FreePage(PgHdr1 *p){
  28240. if( p ){
  28241. if( p->pCache->bPurgeable ){
  28242. pcache1.nCurrentPage--;
  28243. }
  28244. pcache1Free(p);
  28245. }
  28246. }
  28247. /*
  28248. ** Malloc function used by SQLite to obtain space from the buffer configured
  28249. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  28250. ** exists, this function falls back to sqlite3Malloc().
  28251. */
  28252. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  28253. void *p;
  28254. pcache1EnterMutex();
  28255. p = pcache1Alloc(sz);
  28256. pcache1LeaveMutex();
  28257. return p;
  28258. }
  28259. /*
  28260. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  28261. */
  28262. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  28263. pcache1EnterMutex();
  28264. pcache1Free(p);
  28265. pcache1LeaveMutex();
  28266. }
  28267. /******************************************************************************/
  28268. /******** General Implementation Functions ************************************/
  28269. /*
  28270. ** This function is used to resize the hash table used by the cache passed
  28271. ** as the first argument.
  28272. **
  28273. ** The global mutex must be held when this function is called.
  28274. */
  28275. static int pcache1ResizeHash(PCache1 *p){
  28276. PgHdr1 **apNew;
  28277. unsigned int nNew;
  28278. unsigned int i;
  28279. assert( sqlite3_mutex_held(pcache1.mutex) );
  28280. nNew = p->nHash*2;
  28281. if( nNew<256 ){
  28282. nNew = 256;
  28283. }
  28284. pcache1LeaveMutex();
  28285. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  28286. apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
  28287. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  28288. pcache1EnterMutex();
  28289. if( apNew ){
  28290. memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
  28291. for(i=0; i<p->nHash; i++){
  28292. PgHdr1 *pPage;
  28293. PgHdr1 *pNext = p->apHash[i];
  28294. while( (pPage = pNext)!=0 ){
  28295. unsigned int h = pPage->iKey % nNew;
  28296. pNext = pPage->pNext;
  28297. pPage->pNext = apNew[h];
  28298. apNew[h] = pPage;
  28299. }
  28300. }
  28301. sqlite3_free(p->apHash);
  28302. p->apHash = apNew;
  28303. p->nHash = nNew;
  28304. }
  28305. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  28306. }
  28307. /*
  28308. ** This function is used internally to remove the page pPage from the
  28309. ** global LRU list, if is part of it. If pPage is not part of the global
  28310. ** LRU list, then this function is a no-op.
  28311. **
  28312. ** The global mutex must be held when this function is called.
  28313. */
  28314. static void pcache1PinPage(PgHdr1 *pPage){
  28315. assert( sqlite3_mutex_held(pcache1.mutex) );
  28316. if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
  28317. if( pPage->pLruPrev ){
  28318. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  28319. }
  28320. if( pPage->pLruNext ){
  28321. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  28322. }
  28323. if( pcache1.pLruHead==pPage ){
  28324. pcache1.pLruHead = pPage->pLruNext;
  28325. }
  28326. if( pcache1.pLruTail==pPage ){
  28327. pcache1.pLruTail = pPage->pLruPrev;
  28328. }
  28329. pPage->pLruNext = 0;
  28330. pPage->pLruPrev = 0;
  28331. pPage->pCache->nRecyclable--;
  28332. }
  28333. }
  28334. /*
  28335. ** Remove the page supplied as an argument from the hash table
  28336. ** (PCache1.apHash structure) that it is currently stored in.
  28337. **
  28338. ** The global mutex must be held when this function is called.
  28339. */
  28340. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  28341. unsigned int h;
  28342. PCache1 *pCache = pPage->pCache;
  28343. PgHdr1 **pp;
  28344. h = pPage->iKey % pCache->nHash;
  28345. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  28346. *pp = (*pp)->pNext;
  28347. pCache->nPage--;
  28348. }
  28349. /*
  28350. ** If there are currently more than pcache.nMaxPage pages allocated, try
  28351. ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
  28352. */
  28353. static void pcache1EnforceMaxPage(void){
  28354. assert( sqlite3_mutex_held(pcache1.mutex) );
  28355. while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
  28356. PgHdr1 *p = pcache1.pLruTail;
  28357. pcache1PinPage(p);
  28358. pcache1RemoveFromHash(p);
  28359. pcache1FreePage(p);
  28360. }
  28361. }
  28362. /*
  28363. ** Discard all pages from cache pCache with a page number (key value)
  28364. ** greater than or equal to iLimit. Any pinned pages that meet this
  28365. ** criteria are unpinned before they are discarded.
  28366. **
  28367. ** The global mutex must be held when this function is called.
  28368. */
  28369. static void pcache1TruncateUnsafe(
  28370. PCache1 *pCache,
  28371. unsigned int iLimit
  28372. ){
  28373. unsigned int h;
  28374. assert( sqlite3_mutex_held(pcache1.mutex) );
  28375. for(h=0; h<pCache->nHash; h++){
  28376. PgHdr1 **pp = &pCache->apHash[h];
  28377. PgHdr1 *pPage;
  28378. while( (pPage = *pp)!=0 ){
  28379. if( pPage->iKey>=iLimit ){
  28380. pcache1PinPage(pPage);
  28381. *pp = pPage->pNext;
  28382. pcache1FreePage(pPage);
  28383. }else{
  28384. pp = &pPage->pNext;
  28385. }
  28386. }
  28387. }
  28388. }
  28389. /******************************************************************************/
  28390. /******** sqlite3_pcache Methods **********************************************/
  28391. /*
  28392. ** Implementation of the sqlite3_pcache.xInit method.
  28393. */
  28394. static int pcache1Init(void *NotUsed){
  28395. UNUSED_PARAMETER(NotUsed);
  28396. memset(&pcache1, 0, sizeof(pcache1));
  28397. if( sqlite3GlobalConfig.bCoreMutex ){
  28398. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  28399. }
  28400. return SQLITE_OK;
  28401. }
  28402. /*
  28403. ** Implementation of the sqlite3_pcache.xShutdown method.
  28404. */
  28405. static void pcache1Shutdown(void *NotUsed){
  28406. UNUSED_PARAMETER(NotUsed);
  28407. /* no-op */
  28408. }
  28409. /*
  28410. ** Implementation of the sqlite3_pcache.xCreate method.
  28411. **
  28412. ** Allocate a new cache.
  28413. */
  28414. static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
  28415. PCache1 *pCache;
  28416. pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
  28417. if( pCache ){
  28418. memset(pCache, 0, sizeof(PCache1));
  28419. pCache->szPage = szPage;
  28420. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  28421. if( bPurgeable ){
  28422. pCache->nMin = 10;
  28423. pcache1EnterMutex();
  28424. pcache1.nMinPage += pCache->nMin;
  28425. pcache1LeaveMutex();
  28426. }
  28427. }
  28428. return (sqlite3_pcache *)pCache;
  28429. }
  28430. /*
  28431. ** Implementation of the sqlite3_pcache.xCachesize method.
  28432. **
  28433. ** Configure the cache_size limit for a cache.
  28434. */
  28435. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  28436. PCache1 *pCache = (PCache1 *)p;
  28437. if( pCache->bPurgeable ){
  28438. pcache1EnterMutex();
  28439. pcache1.nMaxPage += (nMax - pCache->nMax);
  28440. pCache->nMax = nMax;
  28441. pcache1EnforceMaxPage();
  28442. pcache1LeaveMutex();
  28443. }
  28444. }
  28445. /*
  28446. ** Implementation of the sqlite3_pcache.xPagecount method.
  28447. */
  28448. static int pcache1Pagecount(sqlite3_pcache *p){
  28449. int n;
  28450. pcache1EnterMutex();
  28451. n = ((PCache1 *)p)->nPage;
  28452. pcache1LeaveMutex();
  28453. return n;
  28454. }
  28455. /*
  28456. ** Implementation of the sqlite3_pcache.xFetch method.
  28457. **
  28458. ** Fetch a page by key value.
  28459. **
  28460. ** Whether or not a new page may be allocated by this function depends on
  28461. ** the value of the createFlag argument.
  28462. **
  28463. ** There are three different approaches to obtaining space for a page,
  28464. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  28465. **
  28466. ** 1. Regardless of the value of createFlag, the cache is searched for a
  28467. ** copy of the requested page. If one is found, it is returned.
  28468. **
  28469. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  28470. ** returned.
  28471. **
  28472. ** 3. If createFlag is 1, the cache is marked as purgeable and the page is
  28473. ** not already in the cache, and if either of the following are true,
  28474. ** return NULL:
  28475. **
  28476. ** (a) the number of pages pinned by the cache is greater than
  28477. ** PCache1.nMax, or
  28478. ** (b) the number of pages pinned by the cache is greater than
  28479. ** the sum of nMax for all purgeable caches, less the sum of
  28480. ** nMin for all other purgeable caches.
  28481. **
  28482. ** 4. If none of the first three conditions apply and the cache is marked
  28483. ** as purgeable, and if one of the following is true:
  28484. **
  28485. ** (a) The number of pages allocated for the cache is already
  28486. ** PCache1.nMax, or
  28487. **
  28488. ** (b) The number of pages allocated for all purgeable caches is
  28489. ** already equal to or greater than the sum of nMax for all
  28490. ** purgeable caches,
  28491. **
  28492. ** then attempt to recycle a page from the LRU list. If it is the right
  28493. ** size, return the recycled buffer. Otherwise, free the buffer and
  28494. ** proceed to step 5.
  28495. **
  28496. ** 5. Otherwise, allocate and return a new page buffer.
  28497. */
  28498. static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
  28499. unsigned int nPinned;
  28500. PCache1 *pCache = (PCache1 *)p;
  28501. PgHdr1 *pPage = 0;
  28502. pcache1EnterMutex();
  28503. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  28504. /* Search the hash table for an existing entry. */
  28505. if( pCache->nHash>0 ){
  28506. unsigned int h = iKey % pCache->nHash;
  28507. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  28508. }
  28509. if( pPage || createFlag==0 ){
  28510. pcache1PinPage(pPage);
  28511. goto fetch_out;
  28512. }
  28513. /* Step 3 of header comment. */
  28514. nPinned = pCache->nPage - pCache->nRecyclable;
  28515. if( createFlag==1 && pCache->bPurgeable && (
  28516. nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
  28517. || nPinned>=(pCache->nMax)
  28518. )){
  28519. goto fetch_out;
  28520. }
  28521. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  28522. goto fetch_out;
  28523. }
  28524. /* Step 4. Try to recycle a page buffer if appropriate. */
  28525. if( pCache->bPurgeable && pcache1.pLruTail && (
  28526. pCache->nPage>=pCache->nMax-1 || pcache1.nCurrentPage>=pcache1.nMaxPage
  28527. )){
  28528. pPage = pcache1.pLruTail;
  28529. pcache1RemoveFromHash(pPage);
  28530. pcache1PinPage(pPage);
  28531. if( pPage->pCache->szPage!=pCache->szPage ){
  28532. pcache1FreePage(pPage);
  28533. pPage = 0;
  28534. }else{
  28535. pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
  28536. }
  28537. }
  28538. /* Step 5. If a usable page buffer has still not been found,
  28539. ** attempt to allocate a new one.
  28540. */
  28541. if( !pPage ){
  28542. pPage = pcache1AllocPage(pCache);
  28543. }
  28544. if( pPage ){
  28545. unsigned int h = iKey % pCache->nHash;
  28546. memset(pPage, 0, pCache->szPage + sizeof(PgHdr1));
  28547. pCache->nPage++;
  28548. pPage->iKey = iKey;
  28549. pPage->pNext = pCache->apHash[h];
  28550. pPage->pCache = pCache;
  28551. pCache->apHash[h] = pPage;
  28552. }
  28553. fetch_out:
  28554. if( pPage && iKey>pCache->iMaxKey ){
  28555. pCache->iMaxKey = iKey;
  28556. }
  28557. if( createFlag==1 ) sqlite3EndBenignMalloc();
  28558. pcache1LeaveMutex();
  28559. return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
  28560. }
  28561. /*
  28562. ** Implementation of the sqlite3_pcache.xUnpin method.
  28563. **
  28564. ** Mark a page as unpinned (eligible for asynchronous recycling).
  28565. */
  28566. static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
  28567. PCache1 *pCache = (PCache1 *)p;
  28568. PgHdr1 *pPage = PAGE_TO_PGHDR1(pPg);
  28569. pcache1EnterMutex();
  28570. /* It is an error to call this function if the page is already
  28571. ** part of the global LRU list.
  28572. */
  28573. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  28574. assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
  28575. if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
  28576. pcache1RemoveFromHash(pPage);
  28577. pcache1FreePage(pPage);
  28578. }else{
  28579. /* Add the page to the global LRU list. Normally, the page is added to
  28580. ** the head of the list (last page to be recycled). However, if the
  28581. ** reuseUnlikely flag passed to this function is true, the page is added
  28582. ** to the tail of the list (first page to be recycled).
  28583. */
  28584. if( pcache1.pLruHead ){
  28585. pcache1.pLruHead->pLruPrev = pPage;
  28586. pPage->pLruNext = pcache1.pLruHead;
  28587. pcache1.pLruHead = pPage;
  28588. }else{
  28589. pcache1.pLruTail = pPage;
  28590. pcache1.pLruHead = pPage;
  28591. }
  28592. pCache->nRecyclable++;
  28593. }
  28594. pcache1LeaveMutex();
  28595. }
  28596. /*
  28597. ** Implementation of the sqlite3_pcache.xRekey method.
  28598. */
  28599. static void pcache1Rekey(
  28600. sqlite3_pcache *p,
  28601. void *pPg,
  28602. unsigned int iOld,
  28603. unsigned int iNew
  28604. ){
  28605. PCache1 *pCache = (PCache1 *)p;
  28606. PgHdr1 *pPage = PAGE_TO_PGHDR1(pPg);
  28607. PgHdr1 **pp;
  28608. unsigned int h;
  28609. assert( pPage->iKey==iOld );
  28610. pcache1EnterMutex();
  28611. h = iOld%pCache->nHash;
  28612. pp = &pCache->apHash[h];
  28613. while( (*pp)!=pPage ){
  28614. pp = &(*pp)->pNext;
  28615. }
  28616. *pp = pPage->pNext;
  28617. h = iNew%pCache->nHash;
  28618. pPage->iKey = iNew;
  28619. pPage->pNext = pCache->apHash[h];
  28620. pCache->apHash[h] = pPage;
  28621. if( iNew>pCache->iMaxKey ){
  28622. pCache->iMaxKey = iNew;
  28623. }
  28624. pcache1LeaveMutex();
  28625. }
  28626. /*
  28627. ** Implementation of the sqlite3_pcache.xTruncate method.
  28628. **
  28629. ** Discard all unpinned pages in the cache with a page number equal to
  28630. ** or greater than parameter iLimit. Any pinned pages with a page number
  28631. ** equal to or greater than iLimit are implicitly unpinned.
  28632. */
  28633. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  28634. PCache1 *pCache = (PCache1 *)p;
  28635. pcache1EnterMutex();
  28636. if( iLimit<=pCache->iMaxKey ){
  28637. pcache1TruncateUnsafe(pCache, iLimit);
  28638. pCache->iMaxKey = iLimit-1;
  28639. }
  28640. pcache1LeaveMutex();
  28641. }
  28642. /*
  28643. ** Implementation of the sqlite3_pcache.xDestroy method.
  28644. **
  28645. ** Destroy a cache allocated using pcache1Create().
  28646. */
  28647. static void pcache1Destroy(sqlite3_pcache *p){
  28648. PCache1 *pCache = (PCache1 *)p;
  28649. pcache1EnterMutex();
  28650. pcache1TruncateUnsafe(pCache, 0);
  28651. pcache1.nMaxPage -= pCache->nMax;
  28652. pcache1.nMinPage -= pCache->nMin;
  28653. pcache1EnforceMaxPage();
  28654. pcache1LeaveMutex();
  28655. sqlite3_free(pCache->apHash);
  28656. sqlite3_free(pCache);
  28657. }
  28658. /*
  28659. ** This function is called during initialization (sqlite3_initialize()) to
  28660. ** install the default pluggable cache module, assuming the user has not
  28661. ** already provided an alternative.
  28662. */
  28663. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  28664. static sqlite3_pcache_methods defaultMethods = {
  28665. 0, /* pArg */
  28666. pcache1Init, /* xInit */
  28667. pcache1Shutdown, /* xShutdown */
  28668. pcache1Create, /* xCreate */
  28669. pcache1Cachesize, /* xCachesize */
  28670. pcache1Pagecount, /* xPagecount */
  28671. pcache1Fetch, /* xFetch */
  28672. pcache1Unpin, /* xUnpin */
  28673. pcache1Rekey, /* xRekey */
  28674. pcache1Truncate, /* xTruncate */
  28675. pcache1Destroy /* xDestroy */
  28676. };
  28677. sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
  28678. }
  28679. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  28680. /*
  28681. ** This function is called to free superfluous dynamically allocated memory
  28682. ** held by the pager system. Memory in use by any SQLite pager allocated
  28683. ** by the current thread may be sqlite3_free()ed.
  28684. **
  28685. ** nReq is the number of bytes of memory required. Once this much has
  28686. ** been released, the function returns. The return value is the total number
  28687. ** of bytes of memory released.
  28688. */
  28689. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  28690. int nFree = 0;
  28691. if( pcache1.pStart==0 ){
  28692. PgHdr1 *p;
  28693. pcache1EnterMutex();
  28694. while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
  28695. nFree += sqlite3MallocSize(p);
  28696. pcache1PinPage(p);
  28697. pcache1RemoveFromHash(p);
  28698. pcache1FreePage(p);
  28699. }
  28700. pcache1LeaveMutex();
  28701. }
  28702. return nFree;
  28703. }
  28704. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  28705. #ifdef SQLITE_TEST
  28706. /*
  28707. ** This function is used by test procedures to inspect the internal state
  28708. ** of the global cache.
  28709. */
  28710. SQLITE_PRIVATE void sqlite3PcacheStats(
  28711. int *pnCurrent, /* OUT: Total number of pages cached */
  28712. int *pnMax, /* OUT: Global maximum cache size */
  28713. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  28714. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  28715. ){
  28716. PgHdr1 *p;
  28717. int nRecyclable = 0;
  28718. for(p=pcache1.pLruHead; p; p=p->pLruNext){
  28719. nRecyclable++;
  28720. }
  28721. *pnCurrent = pcache1.nCurrentPage;
  28722. *pnMax = pcache1.nMaxPage;
  28723. *pnMin = pcache1.nMinPage;
  28724. *pnRecyclable = nRecyclable;
  28725. }
  28726. #endif
  28727. /************** End of pcache1.c *********************************************/
  28728. /************** Begin file rowset.c ******************************************/
  28729. /*
  28730. ** 2008 December 3
  28731. **
  28732. ** The author disclaims copyright to this source code. In place of
  28733. ** a legal notice, here is a blessing:
  28734. **
  28735. ** May you do good and not evil.
  28736. ** May you find forgiveness for yourself and forgive others.
  28737. ** May you share freely, never taking more than you give.
  28738. **
  28739. *************************************************************************
  28740. **
  28741. ** This module implements an object we call a "Row Set".
  28742. **
  28743. ** The RowSet object is a bag of rowids. Rowids
  28744. ** are inserted into the bag in an arbitrary order. Then they are
  28745. ** pulled from the bag in sorted order. Rowids only appear in the
  28746. ** bag once. If the same rowid is inserted multiple times, the
  28747. ** second and subsequent inserts make no difference on the output.
  28748. **
  28749. ** This implementation accumulates rowids in a linked list. For
  28750. ** output, it first sorts the linked list (removing duplicates during
  28751. ** the sort) then returns elements one by one by walking the list.
  28752. **
  28753. ** Big chunks of rowid/next-ptr pairs are allocated at a time, to
  28754. ** reduce the malloc overhead.
  28755. **
  28756. ** $Id: rowset.c,v 1.3 2009/01/13 20:14:16 drh Exp $
  28757. */
  28758. /*
  28759. ** The number of rowset entries per allocation chunk.
  28760. */
  28761. #define ROWSET_ENTRY_PER_CHUNK 63
  28762. /*
  28763. ** Each entry in a RowSet is an instance of the following
  28764. ** structure:
  28765. */
  28766. struct RowSetEntry {
  28767. i64 v; /* ROWID value for this entry */
  28768. struct RowSetEntry *pNext; /* Next entry on a list of all entries */
  28769. };
  28770. /*
  28771. ** Index entries are allocated in large chunks (instances of the
  28772. ** following structure) to reduce memory allocation overhead. The
  28773. ** chunks are kept on a linked list so that they can be deallocated
  28774. ** when the RowSet is destroyed.
  28775. */
  28776. struct RowSetChunk {
  28777. struct RowSetChunk *pNext; /* Next chunk on list of them all */
  28778. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  28779. };
  28780. /*
  28781. ** A RowSet in an instance of the following structure.
  28782. **
  28783. ** A typedef of this structure if found in sqliteInt.h.
  28784. */
  28785. struct RowSet {
  28786. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  28787. sqlite3 *db; /* The database connection */
  28788. struct RowSetEntry *pEntry; /* List of entries in the rowset */
  28789. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  28790. struct RowSetEntry *pFresh; /* Source of new entry objects */
  28791. u16 nFresh; /* Number of objects on pFresh */
  28792. u8 isSorted; /* True if content is sorted */
  28793. };
  28794. /*
  28795. ** Turn bulk memory into a RowSet object. N bytes of memory
  28796. ** are available at pSpace. The db pointer is used as a memory context
  28797. ** for any subsequent allocations that need to occur.
  28798. ** Return a pointer to the new RowSet object.
  28799. **
  28800. ** It must be the case that N is sufficient to make a Rowset. If not
  28801. ** an assertion fault occurs.
  28802. **
  28803. ** If N is larger than the minimum, use the surplus as an initial
  28804. ** allocation of entries available to be filled.
  28805. */
  28806. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  28807. RowSet *p;
  28808. assert( N >= sizeof(*p) );
  28809. p = pSpace;
  28810. p->pChunk = 0;
  28811. p->db = db;
  28812. p->pEntry = 0;
  28813. p->pLast = 0;
  28814. p->pFresh = (struct RowSetEntry*)&p[1];
  28815. p->nFresh = (u16)((N - sizeof(*p))/sizeof(struct RowSetEntry));
  28816. p->isSorted = 1;
  28817. return p;
  28818. }
  28819. /*
  28820. ** Deallocate all chunks from a RowSet.
  28821. */
  28822. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  28823. struct RowSetChunk *pChunk, *pNextChunk;
  28824. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  28825. pNextChunk = pChunk->pNext;
  28826. sqlite3DbFree(p->db, pChunk);
  28827. }
  28828. p->pChunk = 0;
  28829. p->nFresh = 0;
  28830. p->pEntry = 0;
  28831. p->pLast = 0;
  28832. p->isSorted = 1;
  28833. }
  28834. /*
  28835. ** Insert a new value into a RowSet.
  28836. **
  28837. ** The mallocFailed flag of the database connection is set if a
  28838. ** memory allocation fails.
  28839. */
  28840. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  28841. struct RowSetEntry *pEntry;
  28842. struct RowSetEntry *pLast;
  28843. if( p==0 ) return; /* Must have been a malloc failure */
  28844. if( p->nFresh==0 ){
  28845. struct RowSetChunk *pNew;
  28846. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  28847. if( pNew==0 ){
  28848. return;
  28849. }
  28850. pNew->pNext = p->pChunk;
  28851. p->pChunk = pNew;
  28852. p->pFresh = pNew->aEntry;
  28853. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  28854. }
  28855. pEntry = p->pFresh++;
  28856. p->nFresh--;
  28857. pEntry->v = rowid;
  28858. pEntry->pNext = 0;
  28859. pLast = p->pLast;
  28860. if( pLast ){
  28861. if( p->isSorted && rowid<=pLast->v ){
  28862. p->isSorted = 0;
  28863. }
  28864. pLast->pNext = pEntry;
  28865. }else{
  28866. assert( p->pEntry==0 );
  28867. p->pEntry = pEntry;
  28868. }
  28869. p->pLast = pEntry;
  28870. }
  28871. /*
  28872. ** Merge two lists of RowSet entries. Remove duplicates.
  28873. **
  28874. ** The input lists are assumed to be in sorted order.
  28875. */
  28876. static struct RowSetEntry *boolidxMerge(
  28877. struct RowSetEntry *pA, /* First sorted list to be merged */
  28878. struct RowSetEntry *pB /* Second sorted list to be merged */
  28879. ){
  28880. struct RowSetEntry head;
  28881. struct RowSetEntry *pTail;
  28882. pTail = &head;
  28883. while( pA && pB ){
  28884. assert( pA->pNext==0 || pA->v<=pA->pNext->v );
  28885. assert( pB->pNext==0 || pB->v<=pB->pNext->v );
  28886. if( pA->v<pB->v ){
  28887. pTail->pNext = pA;
  28888. pA = pA->pNext;
  28889. pTail = pTail->pNext;
  28890. }else if( pB->v<pA->v ){
  28891. pTail->pNext = pB;
  28892. pB = pB->pNext;
  28893. pTail = pTail->pNext;
  28894. }else{
  28895. pA = pA->pNext;
  28896. }
  28897. }
  28898. if( pA ){
  28899. assert( pA->pNext==0 || pA->v<=pA->pNext->v );
  28900. pTail->pNext = pA;
  28901. }else{
  28902. assert( pB==0 || pB->pNext==0 || pB->v<=pB->pNext->v );
  28903. pTail->pNext = pB;
  28904. }
  28905. return head.pNext;
  28906. }
  28907. /*
  28908. ** Sort all elements of the RowSet into ascending order.
  28909. */
  28910. static void sqlite3RowSetSort(RowSet *p){
  28911. unsigned int i;
  28912. struct RowSetEntry *pEntry;
  28913. struct RowSetEntry *aBucket[40];
  28914. assert( p->isSorted==0 );
  28915. memset(aBucket, 0, sizeof(aBucket));
  28916. while( p->pEntry ){
  28917. pEntry = p->pEntry;
  28918. p->pEntry = pEntry->pNext;
  28919. pEntry->pNext = 0;
  28920. for(i=0; aBucket[i]; i++){
  28921. pEntry = boolidxMerge(aBucket[i],pEntry);
  28922. aBucket[i] = 0;
  28923. }
  28924. aBucket[i] = pEntry;
  28925. }
  28926. pEntry = 0;
  28927. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  28928. pEntry = boolidxMerge(pEntry,aBucket[i]);
  28929. }
  28930. p->pEntry = pEntry;
  28931. p->pLast = 0;
  28932. p->isSorted = 1;
  28933. }
  28934. /*
  28935. ** Extract the next (smallest) element from the RowSet.
  28936. ** Write the element into *pRowid. Return 1 on success. Return
  28937. ** 0 if the RowSet is already empty.
  28938. */
  28939. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  28940. if( !p->isSorted ){
  28941. sqlite3RowSetSort(p);
  28942. }
  28943. if( p->pEntry ){
  28944. *pRowid = p->pEntry->v;
  28945. p->pEntry = p->pEntry->pNext;
  28946. if( p->pEntry==0 ){
  28947. sqlite3RowSetClear(p);
  28948. }
  28949. return 1;
  28950. }else{
  28951. return 0;
  28952. }
  28953. }
  28954. /************** End of rowset.c **********************************************/
  28955. /************** Begin file pager.c *******************************************/
  28956. /*
  28957. ** 2001 September 15
  28958. **
  28959. ** The author disclaims copyright to this source code. In place of
  28960. ** a legal notice, here is a blessing:
  28961. **
  28962. ** May you do good and not evil.
  28963. ** May you find forgiveness for yourself and forgive others.
  28964. ** May you share freely, never taking more than you give.
  28965. **
  28966. *************************************************************************
  28967. ** This is the implementation of the page cache subsystem or "pager".
  28968. **
  28969. ** The pager is used to access a database disk file. It implements
  28970. ** atomic commit and rollback through the use of a journal file that
  28971. ** is separate from the database file. The pager also implements file
  28972. ** locking to prevent two processes from writing the same database
  28973. ** file simultaneously, or one process from reading the database while
  28974. ** another is writing.
  28975. **
  28976. ** @(#) $Id: pager.c,v 1.551 2009/01/14 23:03:41 drh Exp $
  28977. */
  28978. #ifndef SQLITE_OMIT_DISKIO
  28979. /*
  28980. ** Macros for troubleshooting. Normally turned off
  28981. */
  28982. #if 0
  28983. int sqlite3PagerTrace=1; /* True to enable tracing */
  28984. #define sqlite3DebugPrintf printf
  28985. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  28986. #else
  28987. #define PAGERTRACE(X)
  28988. #endif
  28989. /*
  28990. ** The following two macros are used within the PAGERTRACE() macros above
  28991. ** to print out file-descriptors.
  28992. **
  28993. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  28994. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  28995. ** struct as its argument.
  28996. */
  28997. #define PAGERID(p) ((int)(p->fd))
  28998. #define FILEHANDLEID(fd) ((int)fd)
  28999. /*
  29000. ** The page cache as a whole is always in one of the following
  29001. ** states:
  29002. **
  29003. ** PAGER_UNLOCK The page cache is not currently reading or
  29004. ** writing the database file. There is no
  29005. ** data held in memory. This is the initial
  29006. ** state.
  29007. **
  29008. ** PAGER_SHARED The page cache is reading the database.
  29009. ** Writing is not permitted. There can be
  29010. ** multiple readers accessing the same database
  29011. ** file at the same time.
  29012. **
  29013. ** PAGER_RESERVED This process has reserved the database for writing
  29014. ** but has not yet made any changes. Only one process
  29015. ** at a time can reserve the database. The original
  29016. ** database file has not been modified so other
  29017. ** processes may still be reading the on-disk
  29018. ** database file.
  29019. **
  29020. ** PAGER_EXCLUSIVE The page cache is writing the database.
  29021. ** Access is exclusive. No other processes or
  29022. ** threads can be reading or writing while one
  29023. ** process is writing.
  29024. **
  29025. ** PAGER_SYNCED The pager moves to this state from PAGER_EXCLUSIVE
  29026. ** after all dirty pages have been written to the
  29027. ** database file and the file has been synced to
  29028. ** disk. All that remains to do is to remove or
  29029. ** truncate the journal file and the transaction
  29030. ** will be committed.
  29031. **
  29032. ** The page cache comes up in PAGER_UNLOCK. The first time a
  29033. ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
  29034. ** After all pages have been released using sqlite_page_unref(),
  29035. ** the state transitions back to PAGER_UNLOCK. The first time
  29036. ** that sqlite3PagerWrite() is called, the state transitions to
  29037. ** PAGER_RESERVED. (Note that sqlite3PagerWrite() can only be
  29038. ** called on an outstanding page which means that the pager must
  29039. ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
  29040. ** PAGER_RESERVED means that there is an open rollback journal.
  29041. ** The transition to PAGER_EXCLUSIVE occurs before any changes
  29042. ** are made to the database file, though writes to the rollback
  29043. ** journal occurs with just PAGER_RESERVED. After an sqlite3PagerRollback()
  29044. ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
  29045. ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
  29046. */
  29047. #define PAGER_UNLOCK 0
  29048. #define PAGER_SHARED 1 /* same as SHARED_LOCK */
  29049. #define PAGER_RESERVED 2 /* same as RESERVED_LOCK */
  29050. #define PAGER_EXCLUSIVE 4 /* same as EXCLUSIVE_LOCK */
  29051. #define PAGER_SYNCED 5
  29052. /*
  29053. ** This macro rounds values up so that if the value is an address it
  29054. ** is guaranteed to be an address that is aligned to an 8-byte boundary.
  29055. */
  29056. #define FORCE_ALIGNMENT(X) (((X)+7)&~7)
  29057. /*
  29058. ** A macro used for invoking the codec if there is one
  29059. */
  29060. #ifdef SQLITE_HAS_CODEC
  29061. # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
  29062. # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
  29063. #else
  29064. # define CODEC1(P,D,N,X) /* NO-OP */
  29065. # define CODEC2(P,D,N,X) ((char*)D)
  29066. #endif
  29067. /*
  29068. ** The maximum allowed sector size. 16MB. If the xSectorsize() method
  29069. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  29070. ** This could conceivably cause corruption following a power failure on
  29071. ** such a system. This is currently an undocumented limit.
  29072. */
  29073. #define MAX_SECTOR_SIZE 0x0100000
  29074. /*
  29075. ** An instance of the following structure is allocated for each active
  29076. ** savepoint and statement transaction in the system. All such structures
  29077. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  29078. ** resized using sqlite3Realloc().
  29079. **
  29080. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  29081. ** set to 0. If a journal-header is written into the main journal while
  29082. ** the savepoint is active, then iHdrOffset is set to the byte offset
  29083. ** immediately following the last journal record written into the main
  29084. ** journal before the journal-header. This is required during savepoint
  29085. ** rollback (see pagerPlaybackSavepoint()).
  29086. */
  29087. typedef struct PagerSavepoint PagerSavepoint;
  29088. struct PagerSavepoint {
  29089. i64 iOffset; /* Starting offset in main journal */
  29090. i64 iHdrOffset; /* See above */
  29091. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  29092. Pgno nOrig; /* Original number of pages in file */
  29093. Pgno iSubRec; /* Index of first record in sub-journal */
  29094. };
  29095. /*
  29096. ** A open page cache is an instance of the following structure.
  29097. **
  29098. ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
  29099. ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
  29100. ** and is returned as the result of every major pager API call. The
  29101. ** SQLITE_FULL return code is slightly different. It persists only until the
  29102. ** next successful rollback is performed on the pager cache. Also,
  29103. ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
  29104. ** APIs, they may still be used successfully.
  29105. **
  29106. ** Managing the size of the database file in pages is a little complicated.
  29107. ** The variable Pager.dbSize contains the number of pages that the database
  29108. ** image currently contains. As the database image grows or shrinks this
  29109. ** variable is updated. The variable Pager.dbFileSize contains the number
  29110. ** of pages in the database file. This may be different from Pager.dbSize
  29111. ** if some pages have been appended to the database image but not yet written
  29112. ** out from the cache to the actual file on disk. Or if the image has been
  29113. ** truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
  29114. ** contains the number of pages in the database image when the current
  29115. ** transaction was opened. The contents of all three of these variables is
  29116. ** only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
  29117. */
  29118. struct Pager {
  29119. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  29120. u8 journalOpen; /* True if journal file descriptors is valid */
  29121. u8 journalStarted; /* True if header of journal is synced */
  29122. u8 useJournal; /* Use a rollback journal on this file */
  29123. u8 noReadlock; /* Do not bother to obtain readlocks */
  29124. u8 noSync; /* Do not sync the journal if true */
  29125. u8 fullSync; /* Do extra syncs of the journal for robustness */
  29126. u8 sync_flags; /* One of SYNC_NORMAL or SYNC_FULL */
  29127. u8 state; /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
  29128. u8 tempFile; /* zFilename is a temporary file */
  29129. u8 readOnly; /* True for a read-only database */
  29130. u8 needSync; /* True if an fsync() is needed on the journal */
  29131. u8 dirtyCache; /* True if cached pages have changed */
  29132. u8 memDb; /* True to inhibit all file I/O */
  29133. u8 setMaster; /* True if a m-j name has been written to jrnl */
  29134. u8 doNotSync; /* Boolean. While true, do not spill the cache */
  29135. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  29136. u8 journalMode; /* On of the PAGER_JOURNALMODE_* values */
  29137. u8 dbModified; /* True if there are any changes to the Db */
  29138. u8 changeCountDone; /* Set after incrementing the change-counter */
  29139. u8 dbSizeValid; /* Set when dbSize is correct */
  29140. Pgno dbSize; /* Number of pages in the database */
  29141. Pgno dbOrigSize; /* dbSize before the current transaction */
  29142. Pgno dbFileSize; /* Number of pages in the database file */
  29143. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  29144. int errCode; /* One of several kinds of errors */
  29145. int nRec; /* Number of pages written to the journal */
  29146. u32 cksumInit; /* Quasi-random value added to every checksum */
  29147. int stmtNRec; /* Number of records in stmt subjournal */
  29148. int nExtra; /* Add this many bytes to each in-memory page */
  29149. int pageSize; /* Number of bytes in a page */
  29150. int nPage; /* Total number of in-memory pages */
  29151. int mxPage; /* Maximum number of pages to hold in cache */
  29152. Pgno mxPgno; /* Maximum allowed size of the database */
  29153. Bitvec *pInJournal; /* One bit for each page in the database file */
  29154. Bitvec *pAlwaysRollback; /* One bit for each page marked always-rollback */
  29155. char *zFilename; /* Name of the database file */
  29156. char *zJournal; /* Name of the journal file */
  29157. char *zDirectory; /* Directory hold database and journal files */
  29158. sqlite3_file *fd, *jfd; /* File descriptors for database and journal */
  29159. sqlite3_file *sjfd; /* File descriptor for the sub-journal*/
  29160. int (*xBusyHandler)(void*); /* Function to call when busy */
  29161. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  29162. i64 journalOff; /* Current byte offset in the journal file */
  29163. i64 journalHdr; /* Byte offset to previous journal header */
  29164. u32 sectorSize; /* Assumed sector size during rollback */
  29165. #ifdef SQLITE_TEST
  29166. int nHit, nMiss; /* Cache hits and missing */
  29167. int nRead, nWrite; /* Database pages read/written */
  29168. #endif
  29169. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  29170. #ifdef SQLITE_HAS_CODEC
  29171. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  29172. void *pCodecArg; /* First argument to xCodec() */
  29173. #endif
  29174. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  29175. char dbFileVers[16]; /* Changes whenever database file changes */
  29176. i64 journalSizeLimit; /* Size limit for persistent journal files */
  29177. PCache *pPCache; /* Pointer to page cache object */
  29178. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  29179. int nSavepoint; /* Number of elements in aSavepoint[] */
  29180. };
  29181. /*
  29182. ** The following global variables hold counters used for
  29183. ** testing purposes only. These variables do not exist in
  29184. ** a non-testing build. These variables are not thread-safe.
  29185. */
  29186. #ifdef SQLITE_TEST
  29187. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  29188. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  29189. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  29190. # define PAGER_INCR(v) v++
  29191. #else
  29192. # define PAGER_INCR(v)
  29193. #endif
  29194. /*
  29195. ** Journal files begin with the following magic string. The data
  29196. ** was obtained from /dev/random. It is used only as a sanity check.
  29197. **
  29198. ** Since version 2.8.0, the journal format contains additional sanity
  29199. ** checking information. If the power fails while the journal is being
  29200. ** written, semi-random garbage data might appear in the journal
  29201. ** file after power is restored. If an attempt is then made
  29202. ** to roll the journal back, the database could be corrupted. The additional
  29203. ** sanity checking data is an attempt to discover the garbage in the
  29204. ** journal and ignore it.
  29205. **
  29206. ** The sanity checking information for the new journal format consists
  29207. ** of a 32-bit checksum on each page of data. The checksum covers both
  29208. ** the page number and the pPager->pageSize bytes of data for the page.
  29209. ** This cksum is initialized to a 32-bit random value that appears in the
  29210. ** journal file right after the header. The random initializer is important,
  29211. ** because garbage data that appears at the end of a journal is likely
  29212. ** data that was once in other files that have now been deleted. If the
  29213. ** garbage data came from an obsolete journal file, the checksums might
  29214. ** be correct. But by initializing the checksum to random value which
  29215. ** is different for every journal, we minimize that risk.
  29216. */
  29217. static const unsigned char aJournalMagic[] = {
  29218. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  29219. };
  29220. /*
  29221. ** The size of the header and of each page in the journal is determined
  29222. ** by the following macros.
  29223. */
  29224. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  29225. /*
  29226. ** The journal header size for this pager. In the future, this could be
  29227. ** set to some value read from the disk controller. The important
  29228. ** characteristic is that it is the same size as a disk sector.
  29229. */
  29230. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  29231. /*
  29232. ** The macro MEMDB is true if we are dealing with an in-memory database.
  29233. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  29234. ** the value of MEMDB will be a constant and the compiler will optimize
  29235. ** out code that would never execute.
  29236. */
  29237. #ifdef SQLITE_OMIT_MEMORYDB
  29238. # define MEMDB 0
  29239. #else
  29240. # define MEMDB pPager->memDb
  29241. #endif
  29242. /*
  29243. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  29244. ** reserved for working around a windows/posix incompatibility). It is
  29245. ** used in the journal to signify that the remainder of the journal file
  29246. ** is devoted to storing a master journal name - there are no more pages to
  29247. ** roll back. See comments for function writeMasterJournal() for details.
  29248. */
  29249. /* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
  29250. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  29251. /*
  29252. ** The maximum legal page number is (2^31 - 1).
  29253. */
  29254. #define PAGER_MAX_PGNO 2147483647
  29255. /*
  29256. ** Return true if it is necessary to write page *pPg into the sub-journal.
  29257. ** A page needs to be written into the sub-journal if there exists one
  29258. ** or more open savepoints for which:
  29259. **
  29260. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  29261. ** * The bit corresponding to the page-number is not set in
  29262. ** PagerSavepoint.pInSavepoint.
  29263. */
  29264. static int subjRequiresPage(PgHdr *pPg){
  29265. Pgno pgno = pPg->pgno;
  29266. Pager *pPager = pPg->pPager;
  29267. int i;
  29268. for(i=0; i<pPager->nSavepoint; i++){
  29269. PagerSavepoint *p = &pPager->aSavepoint[i];
  29270. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  29271. return 1;
  29272. }
  29273. }
  29274. return 0;
  29275. }
  29276. /*
  29277. ** Return true if the page is already in the journal file.
  29278. */
  29279. static int pageInJournal(PgHdr *pPg){
  29280. return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
  29281. }
  29282. /*
  29283. ** Read a 32-bit integer from the given file descriptor. Store the integer
  29284. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  29285. ** error code is something goes wrong.
  29286. **
  29287. ** All values are stored on disk as big-endian.
  29288. */
  29289. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  29290. unsigned char ac[4];
  29291. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  29292. if( rc==SQLITE_OK ){
  29293. *pRes = sqlite3Get4byte(ac);
  29294. }
  29295. return rc;
  29296. }
  29297. /*
  29298. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  29299. */
  29300. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  29301. /*
  29302. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  29303. ** on success or an error code is something goes wrong.
  29304. */
  29305. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  29306. char ac[4];
  29307. put32bits(ac, val);
  29308. return sqlite3OsWrite(fd, ac, 4, offset);
  29309. }
  29310. /*
  29311. ** If file pFd is open, call sqlite3OsUnlock() on it.
  29312. */
  29313. static int osUnlock(sqlite3_file *pFd, int eLock){
  29314. if( !pFd->pMethods ){
  29315. return SQLITE_OK;
  29316. }
  29317. return sqlite3OsUnlock(pFd, eLock);
  29318. }
  29319. /*
  29320. ** This function determines whether or not the atomic-write optimization
  29321. ** can be used with this pager. The optimization can be used if:
  29322. **
  29323. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  29324. ** a database page may be written atomically, and
  29325. ** (b) the value returned by OsSectorSize() is less than or equal
  29326. ** to the page size.
  29327. **
  29328. ** If the optimization cannot be used, 0 is returned. If it can be used,
  29329. ** then the value returned is the size of the journal file when it
  29330. ** contains rollback data for exactly one page.
  29331. */
  29332. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  29333. static int jrnlBufferSize(Pager *pPager){
  29334. int dc; /* Device characteristics */
  29335. int nSector; /* Sector size */
  29336. int szPage; /* Page size */
  29337. sqlite3_file *fd = pPager->fd;
  29338. if( fd->pMethods ){
  29339. dc = sqlite3OsDeviceCharacteristics(fd);
  29340. nSector = pPager->sectorSize;
  29341. szPage = pPager->pageSize;
  29342. }
  29343. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  29344. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  29345. if( !fd->pMethods ||
  29346. (dc & (SQLITE_IOCAP_ATOMIC|(szPage>>8)) && nSector<=szPage) ){
  29347. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  29348. }
  29349. return 0;
  29350. }
  29351. #endif
  29352. /*
  29353. ** This function should be called when an error occurs within the pager
  29354. ** code. The first argument is a pointer to the pager structure, the
  29355. ** second the error-code about to be returned by a pager API function.
  29356. ** The value returned is a copy of the second argument to this function.
  29357. **
  29358. ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
  29359. ** the error becomes persistent. Until the persisten error is cleared,
  29360. ** subsequent API calls on this Pager will immediately return the same
  29361. ** error code.
  29362. **
  29363. ** A persistent error indicates that the contents of the pager-cache
  29364. ** cannot be trusted. This state can be cleared by completely discarding
  29365. ** the contents of the pager-cache. If a transaction was active when
  29366. ** the persistent error occured, then the rollback journal may need
  29367. ** to be replayed.
  29368. */
  29369. static void pager_unlock(Pager *pPager);
  29370. static int pager_error(Pager *pPager, int rc){
  29371. int rc2 = rc & 0xff;
  29372. assert(
  29373. pPager->errCode==SQLITE_FULL ||
  29374. pPager->errCode==SQLITE_OK ||
  29375. (pPager->errCode & 0xff)==SQLITE_IOERR
  29376. );
  29377. if(
  29378. rc2==SQLITE_FULL ||
  29379. rc2==SQLITE_IOERR ||
  29380. rc2==SQLITE_CORRUPT
  29381. ){
  29382. pPager->errCode = rc;
  29383. if( pPager->state==PAGER_UNLOCK
  29384. && sqlite3PcacheRefCount(pPager->pPCache)==0
  29385. ){
  29386. /* If the pager is already unlocked, call pager_unlock() now to
  29387. ** clear the error state and ensure that the pager-cache is
  29388. ** completely empty.
  29389. */
  29390. pager_unlock(pPager);
  29391. }
  29392. }
  29393. return rc;
  29394. }
  29395. /*
  29396. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  29397. ** on the cache using a hash function. This is used for testing
  29398. ** and debugging only.
  29399. */
  29400. #ifdef SQLITE_CHECK_PAGES
  29401. /*
  29402. ** Return a 32-bit hash of the page data for pPage.
  29403. */
  29404. static u32 pager_datahash(int nByte, unsigned char *pData){
  29405. u32 hash = 0;
  29406. int i;
  29407. for(i=0; i<nByte; i++){
  29408. hash = (hash*1039) + pData[i];
  29409. }
  29410. return hash;
  29411. }
  29412. static u32 pager_pagehash(PgHdr *pPage){
  29413. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  29414. }
  29415. static void pager_set_pagehash(PgHdr *pPage){
  29416. pPage->pageHash = pager_pagehash(pPage);
  29417. }
  29418. /*
  29419. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  29420. ** is defined, and NDEBUG is not defined, an assert() statement checks
  29421. ** that the page is either dirty or still matches the calculated page-hash.
  29422. */
  29423. #define CHECK_PAGE(x) checkPage(x)
  29424. static void checkPage(PgHdr *pPg){
  29425. Pager *pPager = pPg->pPager;
  29426. assert( !pPg->pageHash || pPager->errCode
  29427. || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  29428. }
  29429. #else
  29430. #define pager_datahash(X,Y) 0
  29431. #define pager_pagehash(X) 0
  29432. #define CHECK_PAGE(x)
  29433. #endif /* SQLITE_CHECK_PAGES */
  29434. /*
  29435. ** When this is called the journal file for pager pPager must be open.
  29436. ** The master journal file name is read from the end of the file and
  29437. ** written into memory supplied by the caller.
  29438. **
  29439. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  29440. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  29441. ** enough space to write the master journal name). If the master journal
  29442. ** name in the journal is longer than nMaster bytes (including a
  29443. ** nul-terminator), then this is handled as if no master journal name
  29444. ** were present in the journal.
  29445. **
  29446. ** If no master journal file name is present zMaster[0] is set to 0 and
  29447. ** SQLITE_OK returned.
  29448. */
  29449. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  29450. int rc;
  29451. u32 len;
  29452. i64 szJ;
  29453. u32 cksum;
  29454. u32 u; /* Unsigned loop counter */
  29455. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  29456. zMaster[0] = '\0';
  29457. rc = sqlite3OsFileSize(pJrnl, &szJ);
  29458. if( rc!=SQLITE_OK || szJ<16 ) return rc;
  29459. rc = read32bits(pJrnl, szJ-16, &len);
  29460. if( rc!=SQLITE_OK ) return rc;
  29461. if( len>=nMaster ){
  29462. return SQLITE_OK;
  29463. }
  29464. rc = read32bits(pJrnl, szJ-12, &cksum);
  29465. if( rc!=SQLITE_OK ) return rc;
  29466. rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8);
  29467. if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
  29468. rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len);
  29469. if( rc!=SQLITE_OK ){
  29470. return rc;
  29471. }
  29472. zMaster[len] = '\0';
  29473. /* See if the checksum matches the master journal name */
  29474. for(u=0; u<len; u++){
  29475. cksum -= zMaster[u];
  29476. }
  29477. if( cksum ){
  29478. /* If the checksum doesn't add up, then one or more of the disk sectors
  29479. ** containing the master journal filename is corrupted. This means
  29480. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  29481. ** master-journal filename.
  29482. */
  29483. zMaster[0] = '\0';
  29484. }
  29485. return SQLITE_OK;
  29486. }
  29487. /*
  29488. ** Seek the journal file descriptor to the next sector boundary where a
  29489. ** journal header may be read or written. Pager.journalOff is updated with
  29490. ** the new seek offset.
  29491. **
  29492. ** i.e for a sector size of 512:
  29493. **
  29494. ** Input Offset Output Offset
  29495. ** ---------------------------------------
  29496. ** 0 0
  29497. ** 512 512
  29498. ** 100 512
  29499. ** 2000 2048
  29500. **
  29501. */
  29502. static i64 journalHdrOffset(Pager *pPager){
  29503. i64 offset = 0;
  29504. i64 c = pPager->journalOff;
  29505. if( c ){
  29506. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  29507. }
  29508. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  29509. assert( offset>=c );
  29510. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  29511. return offset;
  29512. }
  29513. static void seekJournalHdr(Pager *pPager){
  29514. pPager->journalOff = journalHdrOffset(pPager);
  29515. }
  29516. /*
  29517. ** Write zeros over the header of the journal file. This has the
  29518. ** effect of invalidating the journal file and committing the
  29519. ** transaction.
  29520. */
  29521. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  29522. int rc = SQLITE_OK;
  29523. static const char zeroHdr[28] = {0};
  29524. if( pPager->journalOff ){
  29525. i64 iLimit = pPager->journalSizeLimit;
  29526. IOTRACE(("JZEROHDR %p\n", pPager))
  29527. if( doTruncate || iLimit==0 ){
  29528. rc = sqlite3OsTruncate(pPager->jfd, 0);
  29529. }else{
  29530. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  29531. }
  29532. if( rc==SQLITE_OK && !pPager->noSync ){
  29533. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
  29534. }
  29535. /* At this point the transaction is committed but the write lock
  29536. ** is still held on the file. If there is a size limit configured for
  29537. ** the persistent journal and the journal file currently consumes more
  29538. ** space than that limit allows for, truncate it now. There is no need
  29539. ** to sync the file following this operation.
  29540. */
  29541. if( rc==SQLITE_OK && iLimit>0 ){
  29542. i64 sz;
  29543. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  29544. if( rc==SQLITE_OK && sz>iLimit ){
  29545. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  29546. }
  29547. }
  29548. }
  29549. return rc;
  29550. }
  29551. /*
  29552. ** The journal file must be open when this routine is called. A journal
  29553. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  29554. ** current location.
  29555. **
  29556. ** The format for the journal header is as follows:
  29557. ** - 8 bytes: Magic identifying journal format.
  29558. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  29559. ** - 4 bytes: Random number used for page hash.
  29560. ** - 4 bytes: Initial database page count.
  29561. ** - 4 bytes: Sector size used by the process that wrote this journal.
  29562. ** - 4 bytes: Database page size.
  29563. **
  29564. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  29565. */
  29566. static int writeJournalHdr(Pager *pPager){
  29567. int rc = SQLITE_OK;
  29568. char *zHeader = pPager->pTmpSpace;
  29569. u32 nHeader = pPager->pageSize;
  29570. u32 nWrite;
  29571. int ii;
  29572. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  29573. nHeader = JOURNAL_HDR_SZ(pPager);
  29574. }
  29575. /* If there are active savepoints and any of them were created since the
  29576. ** most recent journal header was written, update the PagerSavepoint.iHdrOff
  29577. ** fields now.
  29578. */
  29579. for(ii=0; ii<pPager->nSavepoint; ii++){
  29580. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  29581. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  29582. }
  29583. }
  29584. seekJournalHdr(pPager);
  29585. pPager->journalHdr = pPager->journalOff;
  29586. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  29587. /*
  29588. ** Write the nRec Field - the number of page records that follow this
  29589. ** journal header. Normally, zero is written to this value at this time.
  29590. ** After the records are added to the journal (and the journal synced,
  29591. ** if in full-sync mode), the zero is overwritten with the true number
  29592. ** of records (see syncJournal()).
  29593. **
  29594. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  29595. ** reading the journal this value tells SQLite to assume that the
  29596. ** rest of the journal file contains valid page records. This assumption
  29597. ** is dangerous, as if a failure occured whilst writing to the journal
  29598. ** file it may contain some garbage data. There are two scenarios
  29599. ** where this risk can be ignored:
  29600. **
  29601. ** * When the pager is in no-sync mode. Corruption can follow a
  29602. ** power failure in this case anyway.
  29603. **
  29604. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  29605. ** that garbage data is never appended to the journal file.
  29606. */
  29607. assert(pPager->fd->pMethods||pPager->noSync);
  29608. if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  29609. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  29610. ){
  29611. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  29612. }else{
  29613. put32bits(&zHeader[sizeof(aJournalMagic)], 0);
  29614. }
  29615. /* The random check-hash initialiser */
  29616. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  29617. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  29618. /* The initial database size */
  29619. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  29620. /* The assumed sector size for this process */
  29621. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  29622. /* Initializing the tail of the buffer is not necessary. Everything
  29623. ** works find if the following memset() is omitted. But initializing
  29624. ** the memory prevents valgrind from complaining, so we are willing to
  29625. ** take the performance hit.
  29626. */
  29627. memset(&zHeader[sizeof(aJournalMagic)+16], 0,
  29628. nHeader-(sizeof(aJournalMagic)+16));
  29629. if( pPager->journalHdr==0 ){
  29630. /* The page size */
  29631. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  29632. }
  29633. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  29634. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  29635. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  29636. pPager->journalOff += nHeader;
  29637. }
  29638. return rc;
  29639. }
  29640. /*
  29641. ** The journal file must be open when this is called. A journal header file
  29642. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  29643. ** file. The current location in the journal file is given by
  29644. ** pPager->journalOff. See comments above function writeJournalHdr() for
  29645. ** a description of the journal header format.
  29646. **
  29647. ** If the header is read successfully, *nRec is set to the number of
  29648. ** page records following this header and *dbSize is set to the size of the
  29649. ** database before the transaction began, in pages. Also, pPager->cksumInit
  29650. ** is set to the value read from the journal header. SQLITE_OK is returned
  29651. ** in this case.
  29652. **
  29653. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  29654. ** returned and *nRec and *dbSize are undefined. If JOURNAL_HDR_SZ bytes
  29655. ** cannot be read from the journal file an error code is returned.
  29656. */
  29657. static int readJournalHdr(
  29658. Pager *pPager,
  29659. i64 journalSize,
  29660. u32 *pNRec,
  29661. u32 *pDbSize
  29662. ){
  29663. int rc;
  29664. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  29665. i64 jrnlOff;
  29666. u32 iPageSize;
  29667. u32 iSectorSize;
  29668. seekJournalHdr(pPager);
  29669. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  29670. return SQLITE_DONE;
  29671. }
  29672. jrnlOff = pPager->journalOff;
  29673. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), jrnlOff);
  29674. if( rc ) return rc;
  29675. jrnlOff += sizeof(aMagic);
  29676. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  29677. return SQLITE_DONE;
  29678. }
  29679. rc = read32bits(pPager->jfd, jrnlOff, pNRec);
  29680. if( rc ) return rc;
  29681. rc = read32bits(pPager->jfd, jrnlOff+4, &pPager->cksumInit);
  29682. if( rc ) return rc;
  29683. rc = read32bits(pPager->jfd, jrnlOff+8, pDbSize);
  29684. if( rc ) return rc;
  29685. if( pPager->journalOff==0 ){
  29686. rc = read32bits(pPager->jfd, jrnlOff+16, &iPageSize);
  29687. if( rc ) return rc;
  29688. if( iPageSize<512
  29689. || iPageSize>SQLITE_MAX_PAGE_SIZE
  29690. || ((iPageSize-1)&iPageSize)!=0
  29691. ){
  29692. /* If the page-size in the journal-header is invalid, then the process
  29693. ** that wrote the journal-header must have crashed before the header
  29694. ** was synced. In this case stop reading the journal file here.
  29695. */
  29696. rc = SQLITE_DONE;
  29697. }else{
  29698. u16 pagesize = (u16)iPageSize;
  29699. rc = sqlite3PagerSetPagesize(pPager, &pagesize);
  29700. assert( rc!=SQLITE_OK || pagesize==(u16)iPageSize );
  29701. }
  29702. if( rc ) return rc;
  29703. /* Update the assumed sector-size to match the value used by
  29704. ** the process that created this journal. If this journal was
  29705. ** created by a process other than this one, then this routine
  29706. ** is being called from within pager_playback(). The local value
  29707. ** of Pager.sectorSize is restored at the end of that routine.
  29708. */
  29709. rc = read32bits(pPager->jfd, jrnlOff+12, &iSectorSize);
  29710. if( rc ) return rc;
  29711. if( (iSectorSize&(iSectorSize-1))
  29712. || iSectorSize<512
  29713. || iSectorSize>MAX_SECTOR_SIZE
  29714. ){
  29715. return SQLITE_DONE;
  29716. }
  29717. pPager->sectorSize = iSectorSize;
  29718. }
  29719. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  29720. return SQLITE_OK;
  29721. }
  29722. /*
  29723. ** Write the supplied master journal name into the journal file for pager
  29724. ** pPager at the current location. The master journal name must be the last
  29725. ** thing written to a journal file. If the pager is in full-sync mode, the
  29726. ** journal file descriptor is advanced to the next sector boundary before
  29727. ** anything is written. The format is:
  29728. **
  29729. ** + 4 bytes: PAGER_MJ_PGNO.
  29730. ** + N bytes: length of master journal name.
  29731. ** + 4 bytes: N
  29732. ** + 4 bytes: Master journal name checksum.
  29733. ** + 8 bytes: aJournalMagic[].
  29734. **
  29735. ** The master journal page checksum is the sum of the bytes in the master
  29736. ** journal name.
  29737. **
  29738. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  29739. ** this call is a no-op.
  29740. */
  29741. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  29742. int rc;
  29743. int len;
  29744. int i;
  29745. i64 jrnlOff;
  29746. i64 jrnlSize;
  29747. u32 cksum = 0;
  29748. char zBuf[sizeof(aJournalMagic)+2*4];
  29749. if( !zMaster || pPager->setMaster ) return SQLITE_OK;
  29750. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ) return SQLITE_OK;
  29751. pPager->setMaster = 1;
  29752. len = sqlite3Strlen30(zMaster);
  29753. for(i=0; i<len; i++){
  29754. cksum += zMaster[i];
  29755. }
  29756. /* If in full-sync mode, advance to the next disk sector before writing
  29757. ** the master journal name. This is in case the previous page written to
  29758. ** the journal has already been synced.
  29759. */
  29760. if( pPager->fullSync ){
  29761. seekJournalHdr(pPager);
  29762. }
  29763. jrnlOff = pPager->journalOff;
  29764. pPager->journalOff += (len+20);
  29765. rc = write32bits(pPager->jfd, jrnlOff, PAGER_MJ_PGNO(pPager));
  29766. if( rc!=SQLITE_OK ) return rc;
  29767. jrnlOff += 4;
  29768. rc = sqlite3OsWrite(pPager->jfd, zMaster, len, jrnlOff);
  29769. if( rc!=SQLITE_OK ) return rc;
  29770. jrnlOff += len;
  29771. put32bits(zBuf, len);
  29772. put32bits(&zBuf[4], cksum);
  29773. memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
  29774. rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic), jrnlOff);
  29775. jrnlOff += 8+sizeof(aJournalMagic);
  29776. pPager->needSync = !pPager->noSync;
  29777. /* If the pager is in peristent-journal mode, then the physical
  29778. ** journal-file may extend past the end of the master-journal name
  29779. ** and 8 bytes of magic data just written to the file. This is
  29780. ** dangerous because the code to rollback a hot-journal file
  29781. ** will not be able to find the master-journal name to determine
  29782. ** whether or not the journal is hot.
  29783. **
  29784. ** Easiest thing to do in this scenario is to truncate the journal
  29785. ** file to the required size.
  29786. */
  29787. if( (rc==SQLITE_OK)
  29788. && (rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))==SQLITE_OK
  29789. && jrnlSize>jrnlOff
  29790. ){
  29791. rc = sqlite3OsTruncate(pPager->jfd, jrnlOff);
  29792. }
  29793. return rc;
  29794. }
  29795. /*
  29796. ** Find a page in the hash table given its page number. Return
  29797. ** a pointer to the page or NULL if not found.
  29798. */
  29799. static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  29800. PgHdr *p;
  29801. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  29802. return p;
  29803. }
  29804. /*
  29805. ** Clear the in-memory cache. This routine
  29806. ** sets the state of the pager back to what it was when it was first
  29807. ** opened. Any outstanding pages are invalidated and subsequent attempts
  29808. ** to access those pages will likely result in a coredump.
  29809. */
  29810. static void pager_reset(Pager *pPager){
  29811. if( pPager->errCode ) return;
  29812. sqlite3PcacheClear(pPager->pPCache);
  29813. }
  29814. /*
  29815. ** Free all structures in the Pager.aSavepoint[] array and set both
  29816. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  29817. ** if it is open and the pager is not in exclusive mode.
  29818. */
  29819. static void releaseAllSavepoint(Pager *pPager){
  29820. int ii;
  29821. for(ii=0; ii<pPager->nSavepoint; ii++){
  29822. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  29823. }
  29824. if( !pPager->exclusiveMode ){
  29825. sqlite3OsClose(pPager->sjfd);
  29826. }
  29827. sqlite3_free(pPager->aSavepoint);
  29828. pPager->aSavepoint = 0;
  29829. pPager->nSavepoint = 0;
  29830. pPager->stmtNRec = 0;
  29831. }
  29832. /*
  29833. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint bitvecs of
  29834. ** all open savepoints.
  29835. */
  29836. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  29837. int ii; /* Loop counter */
  29838. int rc = SQLITE_OK; /* Result code */
  29839. for(ii=0; ii<pPager->nSavepoint; ii++){
  29840. PagerSavepoint *p = &pPager->aSavepoint[ii];
  29841. if( pgno<=p->nOrig ){
  29842. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  29843. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  29844. }
  29845. }
  29846. return rc;
  29847. }
  29848. /*
  29849. ** Unlock the database file.
  29850. **
  29851. ** If the pager is currently in error state, discard the contents of
  29852. ** the cache and reset the Pager structure internal state. If there is
  29853. ** an open journal-file, then the next time a shared-lock is obtained
  29854. ** on the pager file (by this or any other process), it will be
  29855. ** treated as a hot-journal and rolled back.
  29856. */
  29857. static void pager_unlock(Pager *pPager){
  29858. if( !pPager->exclusiveMode ){
  29859. int rc;
  29860. /* Always close the journal file when dropping the database lock.
  29861. ** Otherwise, another connection with journal_mode=delete might
  29862. ** delete the file out from under us.
  29863. */
  29864. if( pPager->journalOpen ){
  29865. sqlite3OsClose(pPager->jfd);
  29866. pPager->journalOpen = 0;
  29867. sqlite3BitvecDestroy(pPager->pInJournal);
  29868. pPager->pInJournal = 0;
  29869. sqlite3BitvecDestroy(pPager->pAlwaysRollback);
  29870. pPager->pAlwaysRollback = 0;
  29871. }
  29872. rc = osUnlock(pPager->fd, NO_LOCK);
  29873. if( rc ) pPager->errCode = rc;
  29874. pPager->dbSizeValid = 0;
  29875. IOTRACE(("UNLOCK %p\n", pPager))
  29876. /* If Pager.errCode is set, the contents of the pager cache cannot be
  29877. ** trusted. Now that the pager file is unlocked, the contents of the
  29878. ** cache can be discarded and the error code safely cleared.
  29879. */
  29880. if( pPager->errCode ){
  29881. if( rc==SQLITE_OK ) pPager->errCode = SQLITE_OK;
  29882. pager_reset(pPager);
  29883. releaseAllSavepoint(pPager);
  29884. pPager->journalOff = 0;
  29885. pPager->journalStarted = 0;
  29886. pPager->dbOrigSize = 0;
  29887. }
  29888. pPager->state = PAGER_UNLOCK;
  29889. pPager->changeCountDone = 0;
  29890. }
  29891. }
  29892. /*
  29893. ** Execute a rollback if a transaction is active and unlock the
  29894. ** database file. If the pager has already entered the error state,
  29895. ** do not attempt the rollback.
  29896. */
  29897. static void pagerUnlockAndRollback(Pager *p){
  29898. if( p->errCode==SQLITE_OK && p->state>=PAGER_RESERVED ){
  29899. sqlite3BeginBenignMalloc();
  29900. sqlite3PagerRollback(p);
  29901. sqlite3EndBenignMalloc();
  29902. }
  29903. pager_unlock(p);
  29904. }
  29905. /*
  29906. ** This routine ends a transaction. A transaction is ended by either
  29907. ** a COMMIT or a ROLLBACK.
  29908. **
  29909. ** When this routine is called, the pager has the journal file open and
  29910. ** a RESERVED or EXCLUSIVE lock on the database. This routine will release
  29911. ** the database lock and acquires a SHARED lock in its place if that is
  29912. ** the appropriate thing to do. Release locks usually is appropriate,
  29913. ** unless we are in exclusive access mode or unless this is a
  29914. ** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
  29915. **
  29916. ** The journal file is either deleted or truncated.
  29917. **
  29918. ** TODO: Consider keeping the journal file open for temporary databases.
  29919. ** This might give a performance improvement on windows where opening
  29920. ** a file is an expensive operation.
  29921. */
  29922. static int pager_end_transaction(Pager *pPager, int hasMaster){
  29923. int rc = SQLITE_OK;
  29924. int rc2 = SQLITE_OK;
  29925. if( pPager->state<PAGER_RESERVED ){
  29926. return SQLITE_OK;
  29927. }
  29928. releaseAllSavepoint(pPager);
  29929. if( pPager->journalOpen ){
  29930. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  29931. int isMemoryJournal = sqlite3IsMemJournal(pPager->jfd);
  29932. sqlite3OsClose(pPager->jfd);
  29933. pPager->journalOpen = 0;
  29934. if( !isMemoryJournal ){
  29935. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  29936. }
  29937. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE
  29938. && (rc = sqlite3OsTruncate(pPager->jfd, 0))==SQLITE_OK ){
  29939. pPager->journalOff = 0;
  29940. pPager->journalStarted = 0;
  29941. }else if( pPager->exclusiveMode
  29942. || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  29943. ){
  29944. rc = zeroJournalHdr(pPager, hasMaster);
  29945. pager_error(pPager, rc);
  29946. pPager->journalOff = 0;
  29947. pPager->journalStarted = 0;
  29948. }else{
  29949. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || rc );
  29950. sqlite3OsClose(pPager->jfd);
  29951. pPager->journalOpen = 0;
  29952. if( rc==SQLITE_OK && !pPager->tempFile ){
  29953. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  29954. }
  29955. }
  29956. sqlite3BitvecDestroy(pPager->pInJournal);
  29957. pPager->pInJournal = 0;
  29958. sqlite3BitvecDestroy(pPager->pAlwaysRollback);
  29959. pPager->pAlwaysRollback = 0;
  29960. #ifdef SQLITE_CHECK_PAGES
  29961. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  29962. #endif
  29963. sqlite3PcacheCleanAll(pPager->pPCache);
  29964. pPager->dirtyCache = 0;
  29965. pPager->nRec = 0;
  29966. }else{
  29967. assert( pPager->pInJournal==0 );
  29968. }
  29969. if( !pPager->exclusiveMode ){
  29970. rc2 = osUnlock(pPager->fd, SHARED_LOCK);
  29971. pPager->state = PAGER_SHARED;
  29972. pPager->changeCountDone = 0;
  29973. }else if( pPager->state==PAGER_SYNCED ){
  29974. pPager->state = PAGER_EXCLUSIVE;
  29975. }
  29976. pPager->dbOrigSize = 0;
  29977. pPager->setMaster = 0;
  29978. pPager->needSync = 0;
  29979. /* lruListSetFirstSynced(pPager); */
  29980. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  29981. if( !MEMDB ){
  29982. pPager->dbSizeValid = 0;
  29983. }
  29984. pPager->dbModified = 0;
  29985. return (rc==SQLITE_OK?rc2:rc);
  29986. }
  29987. /*
  29988. ** Compute and return a checksum for the page of data.
  29989. **
  29990. ** This is not a real checksum. It is really just the sum of the
  29991. ** random initial value and the page number. We experimented with
  29992. ** a checksum of the entire data, but that was found to be too slow.
  29993. **
  29994. ** Note that the page number is stored at the beginning of data and
  29995. ** the checksum is stored at the end. This is important. If journal
  29996. ** corruption occurs due to a power failure, the most likely scenario
  29997. ** is that one end or the other of the record will be changed. It is
  29998. ** much less likely that the two ends of the journal record will be
  29999. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  30000. ** though fast and simple, catches the mostly likely kind of corruption.
  30001. **
  30002. ** FIX ME: Consider adding every 200th (or so) byte of the data to the
  30003. ** checksum. That way if a single page spans 3 or more disk sectors and
  30004. ** only the middle sector is corrupt, we will still have a reasonable
  30005. ** chance of failing the checksum and thus detecting the problem.
  30006. */
  30007. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  30008. u32 cksum = pPager->cksumInit;
  30009. int i = pPager->pageSize-200;
  30010. while( i>0 ){
  30011. cksum += aData[i];
  30012. i -= 200;
  30013. }
  30014. return cksum;
  30015. }
  30016. /*
  30017. ** Read a single page from either the journal file (if isMainJrnl==1) or
  30018. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  30019. ** The page begins at offset *pOffset into the file. The *pOffset
  30020. ** value is increased to the start of the next page in the journal.
  30021. **
  30022. ** The isMainJrnl flag is true if this is the main rollback journal and
  30023. ** false for the statement journal. The main rollback journal uses
  30024. ** checksums - the statement journal does not.
  30025. **
  30026. ** If pDone is not NULL, then it is a record of pages that have already
  30027. ** been played back. If the page at *pOffset has already been played back
  30028. ** (if the corresponding pDone bit is set) then skip the playback.
  30029. ** Make sure the pDone bit corresponding to the *pOffset page is set
  30030. ** prior to returning.
  30031. */
  30032. static int pager_playback_one_page(
  30033. Pager *pPager, /* The pager being played back */
  30034. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  30035. i64 *pOffset, /* Offset of record to playback */
  30036. int isSavepnt, /* True for a savepoint rollback */
  30037. Bitvec *pDone /* Bitvec of pages already played back */
  30038. ){
  30039. int rc;
  30040. PgHdr *pPg; /* An existing page in the cache */
  30041. Pgno pgno; /* The page number of a page in journal */
  30042. u32 cksum; /* Checksum used for sanity checking */
  30043. u8 *aData; /* Temporary storage for the page */
  30044. sqlite3_file *jfd; /* The file descriptor for the journal file */
  30045. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  30046. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  30047. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  30048. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  30049. aData = (u8*)pPager->pTmpSpace;
  30050. assert( aData ); /* Temp storage must have already been allocated */
  30051. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  30052. rc = read32bits(jfd, *pOffset, &pgno);
  30053. if( rc!=SQLITE_OK ) return rc;
  30054. rc = sqlite3OsRead(jfd, aData, pPager->pageSize, (*pOffset)+4);
  30055. if( rc!=SQLITE_OK ) return rc;
  30056. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  30057. /* Sanity checking on the page. This is more important that I originally
  30058. ** thought. If a power failure occurs while the journal is being written,
  30059. ** it could cause invalid data to be written into the journal. We need to
  30060. ** detect this invalid data (with high probability) and ignore it.
  30061. */
  30062. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  30063. return SQLITE_DONE;
  30064. }
  30065. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  30066. return SQLITE_OK;
  30067. }
  30068. if( isMainJrnl ){
  30069. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  30070. if( rc ) return rc;
  30071. if( !isSavepnt && pager_cksum(pPager, aData)!=cksum ){
  30072. return SQLITE_DONE;
  30073. }
  30074. }
  30075. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno)) ){
  30076. return rc;
  30077. }
  30078. assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
  30079. /* If the pager is in RESERVED state, then there must be a copy of this
  30080. ** page in the pager cache. In this case just update the pager cache,
  30081. ** not the database file. The page is left marked dirty in this case.
  30082. **
  30083. ** An exception to the above rule: If the database is in no-sync mode
  30084. ** and a page is moved during an incremental vacuum then the page may
  30085. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  30086. ** during a Movepage() call, then the page may not be in the cache
  30087. ** either. So the condition described in the above paragraph is not
  30088. ** assert()able.
  30089. **
  30090. ** If in EXCLUSIVE state, then we update the pager cache if it exists
  30091. ** and the main file. The page is then marked not dirty.
  30092. **
  30093. ** Ticket #1171: The statement journal might contain page content that is
  30094. ** different from the page content at the start of the transaction.
  30095. ** This occurs when a page is changed prior to the start of a statement
  30096. ** then changed again within the statement. When rolling back such a
  30097. ** statement we must not write to the original database unless we know
  30098. ** for certain that original page contents are synced into the main rollback
  30099. ** journal. Otherwise, a power loss might leave modified data in the
  30100. ** database file without an entry in the rollback journal that can
  30101. ** restore the database to its original form. Two conditions must be
  30102. ** met before writing to the database files. (1) the database must be
  30103. ** locked. (2) we know that the original page content is fully synced
  30104. ** in the main journal either because the page is not in cache or else
  30105. ** the page is marked as needSync==0.
  30106. **
  30107. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  30108. ** is possible to fail a statement on a database that does not yet exist.
  30109. ** Do not attempt to write if database file has never been opened.
  30110. */
  30111. pPg = pager_lookup(pPager, pgno);
  30112. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  30113. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData),
  30114. (isMainJrnl?"main-journal":"sub-journal")
  30115. ));
  30116. if( (pPager->state>=PAGER_EXCLUSIVE)
  30117. && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
  30118. && (pPager->fd->pMethods)
  30119. ){
  30120. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  30121. rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, ofst);
  30122. if( pgno>pPager->dbFileSize ){
  30123. pPager->dbFileSize = pgno;
  30124. }
  30125. }else if( !isMainJrnl && pPg==0 ){
  30126. /* If this is a rollback of a savepoint and data was not written to
  30127. ** the database and the page is not in-memory, there is a potential
  30128. ** problem. When the page is next fetched by the b-tree layer, it
  30129. ** will be read from the database file, which may or may not be
  30130. ** current.
  30131. **
  30132. ** There are a couple of different ways this can happen. All are quite
  30133. ** obscure. When running in synchronous mode, this can only happen
  30134. ** if the page is on the free-list at the start of the transaction, then
  30135. ** populated, then moved using sqlite3PagerMovepage().
  30136. **
  30137. ** The solution is to add an in-memory page to the cache containing
  30138. ** the data just read from the sub-journal. Mark the page as dirty
  30139. ** and if the pager requires a journal-sync, then mark the page as
  30140. ** requiring a journal-sync before it is written.
  30141. */
  30142. assert( isSavepnt );
  30143. if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1)) ){
  30144. return rc;
  30145. }
  30146. pPg->flags &= ~PGHDR_NEED_READ;
  30147. sqlite3PcacheMakeDirty(pPg);
  30148. }
  30149. if( pPg ){
  30150. /* No page should ever be explicitly rolled back that is in use, except
  30151. ** for page 1 which is held in use in order to keep the lock on the
  30152. ** database active. However such a page may be rolled back as a result
  30153. ** of an internal error resulting in an automatic call to
  30154. ** sqlite3PagerRollback().
  30155. */
  30156. void *pData;
  30157. pData = pPg->pData;
  30158. memcpy(pData, aData, pPager->pageSize);
  30159. if( pPager->xReiniter ){
  30160. pPager->xReiniter(pPg);
  30161. }
  30162. if( isMainJrnl && (!isSavepnt || pPager->journalOff<=pPager->journalHdr) ){
  30163. /* If the contents of this page were just restored from the main
  30164. ** journal file, then its content must be as they were when the
  30165. ** transaction was first opened. In this case we can mark the page
  30166. ** as clean, since there will be no need to write it out to the.
  30167. **
  30168. ** There is one exception to this rule. If the page is being rolled
  30169. ** back as part of a savepoint (or statement) rollback from an
  30170. ** unsynced portion of the main journal file, then it is not safe
  30171. ** to mark the page as clean. This is because marking the page as
  30172. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  30173. ** already in the journal file (recorded in Pager.pInJournal) and
  30174. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  30175. ** again within this transaction, it will be marked as dirty but
  30176. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  30177. ** be written out into the database file before its journal file
  30178. ** segment is synced. If a crash occurs during or following this,
  30179. ** database corruption may ensue.
  30180. */
  30181. sqlite3PcacheMakeClean(pPg);
  30182. }
  30183. #ifdef SQLITE_CHECK_PAGES
  30184. pPg->pageHash = pager_pagehash(pPg);
  30185. #endif
  30186. /* If this was page 1, then restore the value of Pager.dbFileVers.
  30187. ** Do this before any decoding. */
  30188. if( pgno==1 ){
  30189. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  30190. }
  30191. /* Decode the page just read from disk */
  30192. CODEC1(pPager, pData, pPg->pgno, 3);
  30193. sqlite3PcacheRelease(pPg);
  30194. }
  30195. return rc;
  30196. }
  30197. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  30198. /*
  30199. ** This routine looks ahead into the main journal file and determines
  30200. ** whether or not the next record (the record that begins at file
  30201. ** offset pPager->journalOff) is a well-formed page record consisting
  30202. ** of a valid page number, pPage->pageSize bytes of content, followed
  30203. ** by a valid checksum.
  30204. **
  30205. ** The pager never needs to know this in order to do its job. This
  30206. ** routine is only used from with assert() and testcase() macros.
  30207. */
  30208. static int pagerNextJournalPageIsValid(Pager *pPager){
  30209. Pgno pgno; /* The page number of the page */
  30210. u32 cksum; /* The page checksum */
  30211. int rc; /* Return code from read operations */
  30212. sqlite3_file *fd; /* The file descriptor from which we are reading */
  30213. u8 *aData; /* Content of the page */
  30214. /* Read the page number header */
  30215. fd = pPager->jfd;
  30216. rc = read32bits(fd, pPager->journalOff, &pgno);
  30217. if( rc!=SQLITE_OK ){ return 0; } /*NO_TEST*/
  30218. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){ return 0; } /*NO_TEST*/
  30219. if( pgno>(Pgno)pPager->dbSize ){ return 0; } /*NO_TEST*/
  30220. /* Read the checksum */
  30221. rc = read32bits(fd, pPager->journalOff+pPager->pageSize+4, &cksum);
  30222. if( rc!=SQLITE_OK ){ return 0; } /*NO_TEST*/
  30223. /* Read the data and verify the checksum */
  30224. aData = (u8*)pPager->pTmpSpace;
  30225. rc = sqlite3OsRead(fd, aData, pPager->pageSize, pPager->journalOff+4);
  30226. if( rc!=SQLITE_OK ){ return 0; } /*NO_TEST*/
  30227. if( pager_cksum(pPager, aData)!=cksum ){ return 0; } /*NO_TEST*/
  30228. /* Reach this point only if the page is valid */
  30229. return 1;
  30230. }
  30231. #endif /* !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) */
  30232. /*
  30233. ** Parameter zMaster is the name of a master journal file. A single journal
  30234. ** file that referred to the master journal file has just been rolled back.
  30235. ** This routine checks if it is possible to delete the master journal file,
  30236. ** and does so if it is.
  30237. **
  30238. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  30239. ** available for use within this function.
  30240. **
  30241. **
  30242. ** The master journal file contains the names of all child journals.
  30243. ** To tell if a master journal can be deleted, check to each of the
  30244. ** children. If all children are either missing or do not refer to
  30245. ** a different master journal, then this master journal can be deleted.
  30246. */
  30247. static int pager_delmaster(Pager *pPager, const char *zMaster){
  30248. sqlite3_vfs *pVfs = pPager->pVfs;
  30249. int rc;
  30250. int master_open = 0;
  30251. sqlite3_file *pMaster;
  30252. sqlite3_file *pJournal;
  30253. char *zMasterJournal = 0; /* Contents of master journal file */
  30254. i64 nMasterJournal; /* Size of master journal file */
  30255. /* Open the master journal file exclusively in case some other process
  30256. ** is running this routine also. Not that it makes too much difference.
  30257. */
  30258. pMaster = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile * 2);
  30259. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  30260. if( !pMaster ){
  30261. rc = SQLITE_NOMEM;
  30262. }else{
  30263. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  30264. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  30265. }
  30266. if( rc!=SQLITE_OK ) goto delmaster_out;
  30267. master_open = 1;
  30268. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  30269. if( rc!=SQLITE_OK ) goto delmaster_out;
  30270. if( nMasterJournal>0 ){
  30271. char *zJournal;
  30272. char *zMasterPtr = 0;
  30273. int nMasterPtr = pPager->pVfs->mxPathname+1;
  30274. /* Load the entire master journal file into space obtained from
  30275. ** sqlite3_malloc() and pointed to by zMasterJournal.
  30276. */
  30277. zMasterJournal = (char *)sqlite3Malloc((int)nMasterJournal + nMasterPtr);
  30278. if( !zMasterJournal ){
  30279. rc = SQLITE_NOMEM;
  30280. goto delmaster_out;
  30281. }
  30282. zMasterPtr = &zMasterJournal[nMasterJournal];
  30283. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  30284. if( rc!=SQLITE_OK ) goto delmaster_out;
  30285. zJournal = zMasterJournal;
  30286. while( (zJournal-zMasterJournal)<nMasterJournal ){
  30287. int exists;
  30288. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  30289. if( rc!=SQLITE_OK ){
  30290. goto delmaster_out;
  30291. }
  30292. if( exists ){
  30293. /* One of the journals pointed to by the master journal exists.
  30294. ** Open it and check if it points at the master journal. If
  30295. ** so, return without deleting the master journal file.
  30296. */
  30297. int c;
  30298. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  30299. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  30300. if( rc!=SQLITE_OK ){
  30301. goto delmaster_out;
  30302. }
  30303. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  30304. sqlite3OsClose(pJournal);
  30305. if( rc!=SQLITE_OK ){
  30306. goto delmaster_out;
  30307. }
  30308. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  30309. if( c ){
  30310. /* We have a match. Do not delete the master journal file. */
  30311. goto delmaster_out;
  30312. }
  30313. }
  30314. zJournal += (sqlite3Strlen30(zJournal)+1);
  30315. }
  30316. }
  30317. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  30318. delmaster_out:
  30319. if( zMasterJournal ){
  30320. sqlite3_free(zMasterJournal);
  30321. }
  30322. if( master_open ){
  30323. sqlite3OsClose(pMaster);
  30324. }
  30325. sqlite3_free(pMaster);
  30326. return rc;
  30327. }
  30328. /*
  30329. ** If the main database file is open and an exclusive lock is held,
  30330. ** truncate the main file of the given pager to the specified number
  30331. ** of pages.
  30332. **
  30333. ** It might might be the case that the file on disk is smaller than nPage.
  30334. ** This can happen, for example, if we are in the middle of a transaction
  30335. ** which has extended the file size and the new pages are still all held
  30336. ** in cache, then an INSERT or UPDATE does a statement rollback. Some
  30337. ** operating system implementations can get confused if you try to
  30338. ** truncate a file to some size that is larger than it currently is,
  30339. ** so detect this case and write a single zero byte to the end of the new
  30340. ** file instead.
  30341. */
  30342. static int pager_truncate(Pager *pPager, Pgno nPage){
  30343. int rc = SQLITE_OK;
  30344. if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){
  30345. i64 currentSize, newSize;
  30346. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  30347. newSize = pPager->pageSize*(i64)nPage;
  30348. if( rc==SQLITE_OK && currentSize!=newSize ){
  30349. if( currentSize>newSize ){
  30350. rc = sqlite3OsTruncate(pPager->fd, newSize);
  30351. }else{
  30352. rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
  30353. }
  30354. if( rc==SQLITE_OK ){
  30355. pPager->dbFileSize = nPage;
  30356. }
  30357. }
  30358. }
  30359. return rc;
  30360. }
  30361. /*
  30362. ** Set the sectorSize for the given pager.
  30363. **
  30364. ** The sector size is at least as big as the sector size reported
  30365. ** by sqlite3OsSectorSize(). The minimum sector size is 512.
  30366. */
  30367. static void setSectorSize(Pager *pPager){
  30368. assert(pPager->fd->pMethods||pPager->tempFile);
  30369. if( !pPager->tempFile ){
  30370. /* Sector size doesn't matter for temporary files. Also, the file
  30371. ** may not have been opened yet, in whcih case the OsSectorSize()
  30372. ** call will segfault.
  30373. */
  30374. pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
  30375. }
  30376. if( pPager->sectorSize<512 ){
  30377. pPager->sectorSize = 512;
  30378. }
  30379. if( pPager->sectorSize>MAX_SECTOR_SIZE ){
  30380. pPager->sectorSize = MAX_SECTOR_SIZE;
  30381. }
  30382. }
  30383. /*
  30384. ** Playback the journal and thus restore the database file to
  30385. ** the state it was in before we started making changes.
  30386. **
  30387. ** The journal file format is as follows:
  30388. **
  30389. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  30390. ** (2) 4 byte big-endian integer which is the number of valid page records
  30391. ** in the journal. If this value is 0xffffffff, then compute the
  30392. ** number of page records from the journal size.
  30393. ** (3) 4 byte big-endian integer which is the initial value for the
  30394. ** sanity checksum.
  30395. ** (4) 4 byte integer which is the number of pages to truncate the
  30396. ** database to during a rollback.
  30397. ** (5) 4 byte big-endian integer which is the sector size. The header
  30398. ** is this many bytes in size.
  30399. ** (6) 4 byte big-endian integer which is the page case.
  30400. ** (7) 4 byte integer which is the number of bytes in the master journal
  30401. ** name. The value may be zero (indicate that there is no master
  30402. ** journal.)
  30403. ** (8) N bytes of the master journal name. The name will be nul-terminated
  30404. ** and might be shorter than the value read from (5). If the first byte
  30405. ** of the name is \000 then there is no master journal. The master
  30406. ** journal name is stored in UTF-8.
  30407. ** (9) Zero or more pages instances, each as follows:
  30408. ** + 4 byte page number.
  30409. ** + pPager->pageSize bytes of data.
  30410. ** + 4 byte checksum
  30411. **
  30412. ** When we speak of the journal header, we mean the first 8 items above.
  30413. ** Each entry in the journal is an instance of the 9th item.
  30414. **
  30415. ** Call the value from the second bullet "nRec". nRec is the number of
  30416. ** valid page entries in the journal. In most cases, you can compute the
  30417. ** value of nRec from the size of the journal file. But if a power
  30418. ** failure occurred while the journal was being written, it could be the
  30419. ** case that the size of the journal file had already been increased but
  30420. ** the extra entries had not yet made it safely to disk. In such a case,
  30421. ** the value of nRec computed from the file size would be too large. For
  30422. ** that reason, we always use the nRec value in the header.
  30423. **
  30424. ** If the nRec value is 0xffffffff it means that nRec should be computed
  30425. ** from the file size. This value is used when the user selects the
  30426. ** no-sync option for the journal. A power failure could lead to corruption
  30427. ** in this case. But for things like temporary table (which will be
  30428. ** deleted when the power is restored) we don't care.
  30429. **
  30430. ** If the file opened as the journal file is not a well-formed
  30431. ** journal file then all pages up to the first corrupted page are rolled
  30432. ** back (or no pages if the journal header is corrupted). The journal file
  30433. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  30434. ** been encountered.
  30435. **
  30436. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  30437. ** and an error code is returned.
  30438. */
  30439. static int pager_playback(Pager *pPager, int isHot){
  30440. sqlite3_vfs *pVfs = pPager->pVfs;
  30441. i64 szJ; /* Size of the journal file in bytes */
  30442. u32 nRec; /* Number of Records in the journal */
  30443. u32 u; /* Unsigned loop counter */
  30444. Pgno mxPg = 0; /* Size of the original file in pages */
  30445. int rc; /* Result code of a subroutine */
  30446. int res = 1; /* Value returned by sqlite3OsAccess() */
  30447. char *zMaster = 0; /* Name of master journal file if any */
  30448. /* Figure out how many records are in the journal. Abort early if
  30449. ** the journal is empty.
  30450. */
  30451. assert( pPager->journalOpen );
  30452. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  30453. if( rc!=SQLITE_OK || szJ==0 ){
  30454. goto end_playback;
  30455. }
  30456. /* Read the master journal name from the journal, if it is present.
  30457. ** If a master journal file name is specified, but the file is not
  30458. ** present on disk, then the journal is not hot and does not need to be
  30459. ** played back.
  30460. */
  30461. zMaster = pPager->pTmpSpace;
  30462. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  30463. if( rc==SQLITE_OK && zMaster[0] ){
  30464. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  30465. }
  30466. zMaster = 0;
  30467. if( rc!=SQLITE_OK || !res ){
  30468. goto end_playback;
  30469. }
  30470. pPager->journalOff = 0;
  30471. /* This loop terminates either when the readJournalHdr() call returns
  30472. ** SQLITE_DONE or an IO error occurs. */
  30473. while( 1 ){
  30474. /* Read the next journal header from the journal file. If there are
  30475. ** not enough bytes left in the journal file for a complete header, or
  30476. ** it is corrupted, then a process must of failed while writing it.
  30477. ** This indicates nothing more needs to be rolled back.
  30478. */
  30479. rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
  30480. if( rc!=SQLITE_OK ){
  30481. if( rc==SQLITE_DONE ){
  30482. rc = SQLITE_OK;
  30483. }
  30484. goto end_playback;
  30485. }
  30486. /* If nRec is 0xffffffff, then this journal was created by a process
  30487. ** working in no-sync mode. This means that the rest of the journal
  30488. ** file consists of pages, there are no more journal headers. Compute
  30489. ** the value of nRec based on this assumption.
  30490. */
  30491. if( nRec==0xffffffff ){
  30492. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  30493. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  30494. }
  30495. /* If nRec is 0 and this rollback is of a transaction created by this
  30496. ** process and if this is the final header in the journal, then it means
  30497. ** that this part of the journal was being filled but has not yet been
  30498. ** synced to disk. Compute the number of pages based on the remaining
  30499. ** size of the file.
  30500. **
  30501. ** The third term of the test was added to fix ticket #2565.
  30502. ** When rolling back a hot journal, nRec==0 always means that the next
  30503. ** chunk of the journal contains zero pages to be rolled back. But
  30504. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  30505. ** the journal, it means that the journal might contain additional
  30506. ** pages that need to be rolled back and that the number of pages
  30507. ** should be computed based on the journal file size.
  30508. */
  30509. testcase( nRec==0 && !isHot
  30510. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)!=pPager->journalOff
  30511. && ((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager))>0
  30512. && pagerNextJournalPageIsValid(pPager)
  30513. );
  30514. if( nRec==0 && !isHot &&
  30515. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  30516. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  30517. }
  30518. /* If this is the first header read from the journal, truncate the
  30519. ** database file back to its original size.
  30520. */
  30521. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  30522. rc = pager_truncate(pPager, mxPg);
  30523. if( rc!=SQLITE_OK ){
  30524. goto end_playback;
  30525. }
  30526. pPager->dbSize = mxPg;
  30527. }
  30528. /* Copy original pages out of the journal and back into the database file.
  30529. */
  30530. for(u=0; u<nRec; u++){
  30531. rc = pager_playback_one_page(pPager, 1, &pPager->journalOff, 0, 0);
  30532. if( rc!=SQLITE_OK ){
  30533. if( rc==SQLITE_DONE ){
  30534. rc = SQLITE_OK;
  30535. pPager->journalOff = szJ;
  30536. break;
  30537. }else{
  30538. /* If we are unable to rollback, then the database is probably
  30539. ** going to end up being corrupt. It is corrupt to us, anyhow.
  30540. ** Perhaps the next process to come along can fix it....
  30541. */
  30542. rc = SQLITE_CORRUPT_BKPT;
  30543. goto end_playback;
  30544. }
  30545. }
  30546. }
  30547. }
  30548. /*NOTREACHED*/
  30549. assert( 0 );
  30550. end_playback:
  30551. /* Following a rollback, the database file should be back in its original
  30552. ** state prior to the start of the transaction, so invoke the
  30553. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  30554. ** assertion that the transaction counter was modified.
  30555. */
  30556. assert(
  30557. pPager->fd->pMethods==0 ||
  30558. sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
  30559. );
  30560. if( rc==SQLITE_OK ){
  30561. zMaster = pPager->pTmpSpace;
  30562. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  30563. }
  30564. if( rc==SQLITE_OK ){
  30565. rc = pager_end_transaction(pPager, zMaster[0]!='\0');
  30566. }
  30567. if( rc==SQLITE_OK && zMaster[0] && res ){
  30568. /* If there was a master journal and this routine will return success,
  30569. ** see if it is possible to delete the master journal.
  30570. */
  30571. rc = pager_delmaster(pPager, zMaster);
  30572. }
  30573. /* The Pager.sectorSize variable may have been updated while rolling
  30574. ** back a journal created by a process with a different sector size
  30575. ** value. Reset it to the correct value for this process.
  30576. */
  30577. setSectorSize(pPager);
  30578. return rc;
  30579. }
  30580. /*
  30581. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  30582. ** the entire master journal file.
  30583. **
  30584. ** The case pSavepoint==NULL occurs when a ROLLBACK TO command is invoked
  30585. ** on a SAVEPOINT that is a transaction savepoint.
  30586. */
  30587. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  30588. i64 szJ; /* Effective size of the main journal */
  30589. i64 iHdrOff; /* End of first segment of main-journal records */
  30590. Pgno ii; /* Loop counter */
  30591. int rc = SQLITE_OK; /* Return code */
  30592. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  30593. /* Allocate a bitvec to use to store the set of pages rolled back */
  30594. if( pSavepoint ){
  30595. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  30596. if( !pDone ){
  30597. return SQLITE_NOMEM;
  30598. }
  30599. }
  30600. /* Truncate the database back to the size it was before the
  30601. ** savepoint being reverted was opened.
  30602. */
  30603. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  30604. assert( pPager->state>=PAGER_SHARED );
  30605. /* Use pPager->journalOff as the effective size of the main rollback
  30606. ** journal. The actual file might be larger than this in
  30607. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  30608. ** past pPager->journalOff is off-limits to us.
  30609. */
  30610. szJ = pPager->journalOff;
  30611. /* Begin by rolling back records from the main journal starting at
  30612. ** PagerSavepoint.iOffset and continuing to the next journal header.
  30613. ** There might be records in the main journal that have a page number
  30614. ** greater than the current database size (pPager->dbSize) but those
  30615. ** will be skipped automatically. Pages are added to pDone as they
  30616. ** are played back.
  30617. */
  30618. if( pSavepoint ){
  30619. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  30620. pPager->journalOff = pSavepoint->iOffset;
  30621. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  30622. rc = pager_playback_one_page(pPager, 1, &pPager->journalOff, 1, pDone);
  30623. assert( rc!=SQLITE_DONE );
  30624. }
  30625. }else{
  30626. pPager->journalOff = 0;
  30627. }
  30628. /* Continue rolling back records out of the main journal starting at
  30629. ** the first journal header seen and continuing until the effective end
  30630. ** of the main journal file. Continue to skip out-of-range pages and
  30631. ** continue adding pages rolled back to pDone.
  30632. */
  30633. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  30634. u32 nJRec = 0; /* Number of Journal Records */
  30635. u32 dummy;
  30636. rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
  30637. assert( rc!=SQLITE_DONE );
  30638. /*
  30639. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  30640. ** test is related to ticket #2565. See the discussion in the
  30641. ** pager_playback() function for additional information.
  30642. */
  30643. assert( !(nJRec==0
  30644. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)!=pPager->journalOff
  30645. && ((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager))>0
  30646. && pagerNextJournalPageIsValid(pPager))
  30647. );
  30648. if( nJRec==0
  30649. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  30650. ){
  30651. nJRec = (szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager);
  30652. }
  30653. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  30654. rc = pager_playback_one_page(pPager, 1, &pPager->journalOff, 1, pDone);
  30655. assert( rc!=SQLITE_DONE );
  30656. }
  30657. }
  30658. assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
  30659. /* Finally, rollback pages from the sub-journal. Page that were
  30660. ** previously rolled back out of the main journal (and are hence in pDone)
  30661. ** will be skipped. Out-of-range pages are also skipped.
  30662. */
  30663. if( pSavepoint ){
  30664. i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
  30665. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK&&ii<(u32)pPager->stmtNRec; ii++){
  30666. assert( offset == ii*(4+pPager->pageSize) );
  30667. rc = pager_playback_one_page(pPager, 0, &offset, 1, pDone);
  30668. assert( rc!=SQLITE_DONE );
  30669. }
  30670. }
  30671. sqlite3BitvecDestroy(pDone);
  30672. if( rc==SQLITE_OK ){
  30673. pPager->journalOff = szJ;
  30674. }
  30675. return rc;
  30676. }
  30677. /*
  30678. ** Change the maximum number of in-memory pages that are allowed.
  30679. */
  30680. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  30681. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  30682. }
  30683. /*
  30684. ** Adjust the robustness of the database to damage due to OS crashes
  30685. ** or power failures by changing the number of syncs()s when writing
  30686. ** the rollback journal. There are three levels:
  30687. **
  30688. ** OFF sqlite3OsSync() is never called. This is the default
  30689. ** for temporary and transient files.
  30690. **
  30691. ** NORMAL The journal is synced once before writes begin on the
  30692. ** database. This is normally adequate protection, but
  30693. ** it is theoretically possible, though very unlikely,
  30694. ** that an inopertune power failure could leave the journal
  30695. ** in a state which would cause damage to the database
  30696. ** when it is rolled back.
  30697. **
  30698. ** FULL The journal is synced twice before writes begin on the
  30699. ** database (with some additional information - the nRec field
  30700. ** of the journal header - being written in between the two
  30701. ** syncs). If we assume that writing a
  30702. ** single disk sector is atomic, then this mode provides
  30703. ** assurance that the journal will not be corrupted to the
  30704. ** point of causing damage to the database during rollback.
  30705. **
  30706. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  30707. ** and FULL=3.
  30708. */
  30709. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  30710. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
  30711. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  30712. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  30713. pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
  30714. if( pPager->noSync ) pPager->needSync = 0;
  30715. }
  30716. #endif
  30717. /*
  30718. ** The following global variable is incremented whenever the library
  30719. ** attempts to open a temporary file. This information is used for
  30720. ** testing and analysis only.
  30721. */
  30722. #ifdef SQLITE_TEST
  30723. SQLITE_API int sqlite3_opentemp_count = 0;
  30724. #endif
  30725. /*
  30726. ** Open a temporary file.
  30727. **
  30728. ** Write the file descriptor into *fd. Return SQLITE_OK on success or some
  30729. ** other error code if we fail. The OS will automatically delete the temporary
  30730. ** file when it is closed.
  30731. */
  30732. static int sqlite3PagerOpentemp(
  30733. Pager *pPager, /* The pager object */
  30734. sqlite3_file *pFile, /* Write the file descriptor here */
  30735. int vfsFlags /* Flags passed through to the VFS */
  30736. ){
  30737. int rc;
  30738. #ifdef SQLITE_TEST
  30739. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  30740. #endif
  30741. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  30742. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  30743. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  30744. assert( rc!=SQLITE_OK || pFile->pMethods );
  30745. return rc;
  30746. }
  30747. static int pagerStress(void *,PgHdr *);
  30748. /*
  30749. ** Create a new page cache and put a pointer to the page cache in *ppPager.
  30750. ** The file to be cached need not exist. The file is not locked until
  30751. ** the first call to sqlite3PagerGet() and is only held open until the
  30752. ** last page is released using sqlite3PagerUnref().
  30753. **
  30754. ** If zFilename is NULL then a randomly-named temporary file is created
  30755. ** and used as the file to be cached. The file will be deleted
  30756. ** automatically when it is closed.
  30757. **
  30758. ** If zFilename is ":memory:" then all information is held in cache.
  30759. ** It is never written to disk. This can be used to implement an
  30760. ** in-memory database.
  30761. */
  30762. SQLITE_PRIVATE int sqlite3PagerOpen(
  30763. sqlite3_vfs *pVfs, /* The virtual file system to use */
  30764. Pager **ppPager, /* Return the Pager structure here */
  30765. const char *zFilename, /* Name of the database file to open */
  30766. int nExtra, /* Extra bytes append to each in-memory page */
  30767. int flags, /* flags controlling this file */
  30768. int vfsFlags /* flags passed through to sqlite3_vfs.xOpen() */
  30769. ){
  30770. u8 *pPtr;
  30771. Pager *pPager = 0;
  30772. int rc = SQLITE_OK;
  30773. int i;
  30774. int tempFile = 0;
  30775. int memDb = 0;
  30776. int readOnly = 0;
  30777. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
  30778. int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
  30779. int journalFileSize;
  30780. int pcacheSize = sqlite3PcacheSize();
  30781. int szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;
  30782. char *zPathname = 0;
  30783. int nPathname = 0;
  30784. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  30785. journalFileSize = sqlite3JournalSize(pVfs);
  30786. }else{
  30787. journalFileSize = sqlite3MemJournalSize();
  30788. }
  30789. /* The default return is a NULL pointer */
  30790. *ppPager = 0;
  30791. /* Compute and store the full pathname in an allocated buffer pointed
  30792. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  30793. ** leave both nPathname and zPathname set to 0.
  30794. */
  30795. if( zFilename && zFilename[0] ){
  30796. nPathname = pVfs->mxPathname+1;
  30797. zPathname = sqlite3Malloc(nPathname*2);
  30798. if( zPathname==0 ){
  30799. return SQLITE_NOMEM;
  30800. }
  30801. #ifndef SQLITE_OMIT_MEMORYDB
  30802. if( strcmp(zFilename,":memory:")==0 ){
  30803. memDb = 1;
  30804. zPathname[0] = 0;
  30805. }else
  30806. #endif
  30807. {
  30808. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  30809. }
  30810. if( rc!=SQLITE_OK ){
  30811. sqlite3_free(zPathname);
  30812. return rc;
  30813. }
  30814. nPathname = sqlite3Strlen30(zPathname);
  30815. }
  30816. /* Allocate memory for the pager structure */
  30817. pPager = sqlite3MallocZero(
  30818. sizeof(*pPager) + /* Pager structure */
  30819. pcacheSize + /* PCache object */
  30820. journalFileSize + /* The journal file structure */
  30821. pVfs->szOsFile + /* The main db file */
  30822. journalFileSize * 2 + /* The two journal files */
  30823. 3*nPathname + 40 /* zFilename, zDirectory, zJournal */
  30824. );
  30825. if( !pPager ){
  30826. sqlite3_free(zPathname);
  30827. return SQLITE_NOMEM;
  30828. }
  30829. pPager->pPCache = (PCache *)&pPager[1];
  30830. pPtr = ((u8 *)&pPager[1]) + pcacheSize;
  30831. pPager->vfsFlags = vfsFlags;
  30832. pPager->fd = (sqlite3_file*)&pPtr[pVfs->szOsFile*0];
  30833. pPager->sjfd = (sqlite3_file*)&pPtr[pVfs->szOsFile];
  30834. pPager->jfd = (sqlite3_file*)&pPtr[pVfs->szOsFile+journalFileSize];
  30835. pPager->zFilename = (char*)&pPtr[pVfs->szOsFile+2*journalFileSize];
  30836. pPager->zDirectory = &pPager->zFilename[nPathname+1];
  30837. pPager->zJournal = &pPager->zDirectory[nPathname+1];
  30838. pPager->pVfs = pVfs;
  30839. if( zPathname ){
  30840. memcpy(pPager->zFilename, zPathname, nPathname+1);
  30841. sqlite3_free(zPathname);
  30842. }
  30843. /* Open the pager file.
  30844. */
  30845. if( zFilename && zFilename[0] && !memDb ){
  30846. if( nPathname>(pVfs->mxPathname - (int)sizeof("-journal")) ){
  30847. rc = SQLITE_CANTOPEN;
  30848. }else{
  30849. int fout = 0;
  30850. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd,
  30851. pPager->vfsFlags, &fout);
  30852. readOnly = (fout&SQLITE_OPEN_READONLY);
  30853. /* If the file was successfully opened for read/write access,
  30854. ** choose a default page size in case we have to create the
  30855. ** database file. The default page size is the maximum of:
  30856. **
  30857. ** + SQLITE_DEFAULT_PAGE_SIZE,
  30858. ** + The value returned by sqlite3OsSectorSize()
  30859. ** + The largest page size that can be written atomically.
  30860. */
  30861. if( rc==SQLITE_OK && !readOnly ){
  30862. setSectorSize(pPager);
  30863. if( szPageDflt<pPager->sectorSize ){
  30864. szPageDflt = pPager->sectorSize;
  30865. }
  30866. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  30867. {
  30868. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  30869. int ii;
  30870. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  30871. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  30872. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  30873. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  30874. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ) szPageDflt = ii;
  30875. }
  30876. }
  30877. #endif
  30878. if( szPageDflt>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  30879. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  30880. }
  30881. }
  30882. }
  30883. }else{
  30884. /* If a temporary file is requested, it is not opened immediately.
  30885. ** In this case we accept the default page size and delay actually
  30886. ** opening the file until the first call to OsWrite().
  30887. **
  30888. ** This branch is also run for an in-memory database. An in-memory
  30889. ** database is the same as a temp-file that is never written out to
  30890. ** disk and uses an in-memory rollback journal.
  30891. */
  30892. tempFile = 1;
  30893. pPager->state = PAGER_EXCLUSIVE;
  30894. }
  30895. if( pPager && rc==SQLITE_OK ){
  30896. pPager->pTmpSpace = sqlite3PageMalloc(szPageDflt);
  30897. }
  30898. /* If an error occured in either of the blocks above.
  30899. ** Free the Pager structure and close the file.
  30900. ** Since the pager is not allocated there is no need to set
  30901. ** any Pager.errMask variables.
  30902. */
  30903. if( !pPager || !pPager->pTmpSpace ){
  30904. sqlite3OsClose(pPager->fd);
  30905. sqlite3_free(pPager);
  30906. return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
  30907. }
  30908. nExtra = FORCE_ALIGNMENT(nExtra);
  30909. sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  30910. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  30911. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  30912. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  30913. /* Fill in Pager.zDirectory[] */
  30914. memcpy(pPager->zDirectory, pPager->zFilename, nPathname+1);
  30915. for(i=sqlite3Strlen30(pPager->zDirectory);
  30916. i>0 && pPager->zDirectory[i-1]!='/'; i--){}
  30917. if( i>0 ) pPager->zDirectory[i-1] = 0;
  30918. /* Fill in Pager.zJournal[] */
  30919. if( zPathname ){
  30920. memcpy(pPager->zJournal, pPager->zFilename, nPathname);
  30921. memcpy(&pPager->zJournal[nPathname], "-journal", 9);
  30922. }else{
  30923. pPager->zJournal = 0;
  30924. }
  30925. /* pPager->journalOpen = 0; */
  30926. pPager->useJournal = (u8)useJournal;
  30927. pPager->noReadlock = (noReadlock && readOnly) ?1:0;
  30928. /* pPager->stmtOpen = 0; */
  30929. /* pPager->stmtInUse = 0; */
  30930. /* pPager->nRef = 0; */
  30931. pPager->dbSizeValid = (u8)memDb;
  30932. pPager->pageSize = szPageDflt;
  30933. /* pPager->stmtSize = 0; */
  30934. /* pPager->stmtJSize = 0; */
  30935. /* pPager->nPage = 0; */
  30936. pPager->mxPage = 100;
  30937. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  30938. /* pPager->state = PAGER_UNLOCK; */
  30939. assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  30940. /* pPager->errMask = 0; */
  30941. pPager->tempFile = (u8)tempFile;
  30942. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  30943. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  30944. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  30945. pPager->exclusiveMode = (u8)tempFile;
  30946. pPager->memDb = (u8)memDb;
  30947. pPager->readOnly = (u8)readOnly;
  30948. /* pPager->needSync = 0; */
  30949. pPager->noSync = (pPager->tempFile || !useJournal) ?1:0;
  30950. pPager->fullSync = pPager->noSync ?0:1;
  30951. pPager->sync_flags = SQLITE_SYNC_NORMAL;
  30952. /* pPager->pFirst = 0; */
  30953. /* pPager->pFirstSynced = 0; */
  30954. /* pPager->pLast = 0; */
  30955. pPager->nExtra = nExtra;
  30956. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  30957. assert(pPager->fd->pMethods||tempFile);
  30958. setSectorSize(pPager);
  30959. if( memDb ){
  30960. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  30961. }
  30962. /* pPager->xBusyHandler = 0; */
  30963. /* pPager->pBusyHandlerArg = 0; */
  30964. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  30965. *ppPager = pPager;
  30966. return SQLITE_OK;
  30967. }
  30968. /*
  30969. ** Set the busy handler function.
  30970. */
  30971. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  30972. Pager *pPager,
  30973. int (*xBusyHandler)(void *),
  30974. void *pBusyHandlerArg
  30975. ){
  30976. pPager->xBusyHandler = xBusyHandler;
  30977. pPager->pBusyHandlerArg = pBusyHandlerArg;
  30978. }
  30979. /*
  30980. ** Set the reinitializer for this pager. If not NULL, the reinitializer
  30981. ** is called when the content of a page in cache is restored to its original
  30982. ** value as a result of a rollback. The callback gives higher-level code
  30983. ** an opportunity to restore the EXTRA section to agree with the restored
  30984. ** page data.
  30985. */
  30986. SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*)){
  30987. pPager->xReiniter = xReinit;
  30988. }
  30989. /*
  30990. ** Set the page size to *pPageSize. If the suggest new page size is
  30991. ** inappropriate, then an alternative page size is set to that
  30992. ** value before returning.
  30993. */
  30994. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
  30995. int rc = pPager->errCode;
  30996. if( rc==SQLITE_OK ){
  30997. u16 pageSize = *pPageSize;
  30998. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  30999. if( pageSize && pageSize!=pPager->pageSize
  31000. && (pPager->memDb==0 || pPager->dbSize==0)
  31001. && sqlite3PcacheRefCount(pPager->pPCache)==0
  31002. ){
  31003. char *pNew = (char *)sqlite3PageMalloc(pageSize);
  31004. if( !pNew ){
  31005. rc = SQLITE_NOMEM;
  31006. }else{
  31007. pager_reset(pPager);
  31008. pPager->pageSize = pageSize;
  31009. if( !pPager->memDb ) setSectorSize(pPager);
  31010. sqlite3PageFree(pPager->pTmpSpace);
  31011. pPager->pTmpSpace = pNew;
  31012. sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  31013. }
  31014. }
  31015. *pPageSize = (u16)pPager->pageSize;
  31016. }
  31017. return rc;
  31018. }
  31019. /*
  31020. ** Return a pointer to the "temporary page" buffer held internally
  31021. ** by the pager. This is a buffer that is big enough to hold the
  31022. ** entire content of a database page. This buffer is used internally
  31023. ** during rollback and will be overwritten whenever a rollback
  31024. ** occurs. But other modules are free to use it too, as long as
  31025. ** no rollbacks are happening.
  31026. */
  31027. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  31028. return pPager->pTmpSpace;
  31029. }
  31030. /*
  31031. ** Attempt to set the maximum database page count if mxPage is positive.
  31032. ** Make no changes if mxPage is zero or negative. And never reduce the
  31033. ** maximum page count below the current size of the database.
  31034. **
  31035. ** Regardless of mxPage, return the current maximum page count.
  31036. */
  31037. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  31038. if( mxPage>0 ){
  31039. pPager->mxPgno = mxPage;
  31040. }
  31041. sqlite3PagerPagecount(pPager, 0);
  31042. return pPager->mxPgno;
  31043. }
  31044. /*
  31045. ** The following set of routines are used to disable the simulated
  31046. ** I/O error mechanism. These routines are used to avoid simulated
  31047. ** errors in places where we do not care about errors.
  31048. **
  31049. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  31050. ** and generate no code.
  31051. */
  31052. #ifdef SQLITE_TEST
  31053. SQLITE_API extern int sqlite3_io_error_pending;
  31054. SQLITE_API extern int sqlite3_io_error_hit;
  31055. static int saved_cnt;
  31056. void disable_simulated_io_errors(void){
  31057. saved_cnt = sqlite3_io_error_pending;
  31058. sqlite3_io_error_pending = -1;
  31059. }
  31060. void enable_simulated_io_errors(void){
  31061. sqlite3_io_error_pending = saved_cnt;
  31062. }
  31063. #else
  31064. # define disable_simulated_io_errors()
  31065. # define enable_simulated_io_errors()
  31066. #endif
  31067. /*
  31068. ** Read the first N bytes from the beginning of the file into memory
  31069. ** that pDest points to.
  31070. **
  31071. ** No error checking is done. The rational for this is that this function
  31072. ** may be called even if the file does not exist or contain a header. In
  31073. ** these cases sqlite3OsRead() will return an error, to which the correct
  31074. ** response is to zero the memory at pDest and continue. A real IO error
  31075. ** will presumably recur and be picked up later (Todo: Think about this).
  31076. */
  31077. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  31078. int rc = SQLITE_OK;
  31079. memset(pDest, 0, N);
  31080. assert(pPager->fd->pMethods||pPager->tempFile);
  31081. if( pPager->fd->pMethods ){
  31082. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  31083. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  31084. if( rc==SQLITE_IOERR_SHORT_READ ){
  31085. rc = SQLITE_OK;
  31086. }
  31087. }
  31088. return rc;
  31089. }
  31090. /*
  31091. ** Return the total number of pages in the disk file associated with
  31092. ** pPager.
  31093. **
  31094. ** If the PENDING_BYTE lies on the page directly after the end of the
  31095. ** file, then consider this page part of the file too. For example, if
  31096. ** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
  31097. ** file is 4096 bytes, 5 is returned instead of 4.
  31098. */
  31099. SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  31100. i64 n = 0;
  31101. int rc;
  31102. assert( pPager!=0 );
  31103. if( pPager->errCode ){
  31104. rc = pPager->errCode;
  31105. return rc;
  31106. }
  31107. if( pPager->dbSizeValid ){
  31108. n = pPager->dbSize;
  31109. } else {
  31110. assert(pPager->fd->pMethods||pPager->tempFile);
  31111. if( (pPager->fd->pMethods)
  31112. && (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
  31113. pager_error(pPager, rc);
  31114. return rc;
  31115. }
  31116. if( n>0 && n<pPager->pageSize ){
  31117. n = 1;
  31118. }else{
  31119. n /= pPager->pageSize;
  31120. }
  31121. if( pPager->state!=PAGER_UNLOCK ){
  31122. pPager->dbSize = (Pgno)n;
  31123. pPager->dbFileSize = (Pgno)n;
  31124. pPager->dbSizeValid = 1;
  31125. }
  31126. }
  31127. if( n==(PENDING_BYTE/pPager->pageSize) ){
  31128. n++;
  31129. }
  31130. if( n>pPager->mxPgno ){
  31131. pPager->mxPgno = (Pgno)n;
  31132. }
  31133. if( pnPage ){
  31134. *pnPage = (int)n;
  31135. }
  31136. return SQLITE_OK;
  31137. }
  31138. /*
  31139. ** Forward declaration
  31140. */
  31141. static int syncJournal(Pager*);
  31142. /*
  31143. ** Try to obtain a lock on a file. Invoke the busy callback if the lock
  31144. ** is currently not available. Repeat until the busy callback returns
  31145. ** false or until the lock succeeds.
  31146. **
  31147. ** Return SQLITE_OK on success and an error code if we cannot obtain
  31148. ** the lock.
  31149. */
  31150. static int pager_wait_on_lock(Pager *pPager, int locktype){
  31151. int rc;
  31152. /* The OS lock values must be the same as the Pager lock values */
  31153. assert( PAGER_SHARED==SHARED_LOCK );
  31154. assert( PAGER_RESERVED==RESERVED_LOCK );
  31155. assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
  31156. /* If the file is currently unlocked then the size must be unknown */
  31157. assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
  31158. if( pPager->state>=locktype ){
  31159. rc = SQLITE_OK;
  31160. }else{
  31161. do {
  31162. rc = sqlite3OsLock(pPager->fd, locktype);
  31163. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  31164. if( rc==SQLITE_OK ){
  31165. pPager->state = (u8)locktype;
  31166. IOTRACE(("LOCK %p %d\n", pPager, locktype))
  31167. }
  31168. }
  31169. return rc;
  31170. }
  31171. #ifndef SQLITE_OMIT_AUTOVACUUM
  31172. /*
  31173. ** Truncate the in-memory database file image to nPage pages. This
  31174. ** function does not actually modify the database file on disk. It
  31175. ** just sets the internal state of the pager object so that the
  31176. ** truncation will be done when the current transaction is committed.
  31177. */
  31178. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  31179. assert( pPager->dbSizeValid );
  31180. assert( pPager->dbSize>=nPage );
  31181. pPager->dbSize = nPage;
  31182. }
  31183. /*
  31184. ** Return the current size of the database file image in pages. This
  31185. ** function differs from sqlite3PagerPagecount() in two ways:
  31186. **
  31187. ** a) It may only be called when at least one reference to a database
  31188. ** page is held. This guarantees that the database size is already
  31189. ** known and a call to sqlite3OsFileSize() is not required.
  31190. **
  31191. ** b) The return value is not adjusted for the locking page.
  31192. */
  31193. SQLITE_PRIVATE Pgno sqlite3PagerImageSize(Pager *pPager){
  31194. assert( pPager->dbSizeValid );
  31195. return pPager->dbSize;
  31196. }
  31197. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  31198. /*
  31199. ** Shutdown the page cache. Free all memory and close all files.
  31200. **
  31201. ** If a transaction was in progress when this routine is called, that
  31202. ** transaction is rolled back. All outstanding pages are invalidated
  31203. ** and their memory is freed. Any attempt to use a page associated
  31204. ** with this page cache after this function returns will likely
  31205. ** result in a coredump.
  31206. **
  31207. ** This function always succeeds. If a transaction is active an attempt
  31208. ** is made to roll it back. If an error occurs during the rollback
  31209. ** a hot journal may be left in the filesystem but no error is returned
  31210. ** to the caller.
  31211. */
  31212. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  31213. disable_simulated_io_errors();
  31214. sqlite3BeginBenignMalloc();
  31215. pPager->errCode = 0;
  31216. pPager->exclusiveMode = 0;
  31217. pager_reset(pPager);
  31218. if( !MEMDB ){
  31219. /* Set Pager.journalHdr to -1 for the benefit of the pager_playback()
  31220. ** call which may be made from within pagerUnlockAndRollback(). If it
  31221. ** is not -1, then the unsynced portion of an open journal file may
  31222. ** be played back into the database. If a power failure occurs while
  31223. ** this is happening, the database may become corrupt.
  31224. */
  31225. pPager->journalHdr = -1;
  31226. pagerUnlockAndRollback(pPager);
  31227. }
  31228. enable_simulated_io_errors();
  31229. sqlite3EndBenignMalloc();
  31230. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  31231. IOTRACE(("CLOSE %p\n", pPager))
  31232. if( pPager->journalOpen ){
  31233. sqlite3OsClose(pPager->jfd);
  31234. }
  31235. sqlite3BitvecDestroy(pPager->pInJournal);
  31236. sqlite3BitvecDestroy(pPager->pAlwaysRollback);
  31237. releaseAllSavepoint(pPager);
  31238. sqlite3OsClose(pPager->fd);
  31239. /* Temp files are automatically deleted by the OS
  31240. ** if( pPager->tempFile ){
  31241. ** sqlite3OsDelete(pPager->zFilename);
  31242. ** }
  31243. */
  31244. sqlite3PageFree(pPager->pTmpSpace);
  31245. sqlite3PcacheClose(pPager->pPCache);
  31246. sqlite3_free(pPager);
  31247. return SQLITE_OK;
  31248. }
  31249. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  31250. /*
  31251. ** Return the page number for the given page data.
  31252. */
  31253. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *p){
  31254. return p->pgno;
  31255. }
  31256. #endif
  31257. /*
  31258. ** Increment the reference count for a page. The input pointer is
  31259. ** a reference to the page data.
  31260. */
  31261. SQLITE_PRIVATE int sqlite3PagerRef(DbPage *pPg){
  31262. sqlite3PcacheRef(pPg);
  31263. return SQLITE_OK;
  31264. }
  31265. /*
  31266. ** Sync the journal. In other words, make sure all the pages that have
  31267. ** been written to the journal have actually reached the surface of the
  31268. ** disk. It is not safe to modify the original database file until after
  31269. ** the journal has been synced. If the original database is modified before
  31270. ** the journal is synced and a power failure occurs, the unsynced journal
  31271. ** data would be lost and we would be unable to completely rollback the
  31272. ** database changes. Database corruption would occur.
  31273. **
  31274. ** This routine also updates the nRec field in the header of the journal.
  31275. ** (See comments on the pager_playback() routine for additional information.)
  31276. ** If the sync mode is FULL, two syncs will occur. First the whole journal
  31277. ** is synced, then the nRec field is updated, then a second sync occurs.
  31278. **
  31279. ** For temporary databases, we do not care if we are able to rollback
  31280. ** after a power failure, so no sync occurs.
  31281. **
  31282. ** If the IOCAP_SEQUENTIAL flag is set for the persistent media on which
  31283. ** the database is stored, then OsSync() is never called on the journal
  31284. ** file. In this case all that is required is to update the nRec field in
  31285. ** the journal header.
  31286. **
  31287. ** This routine clears the needSync field of every page current held in
  31288. ** memory.
  31289. */
  31290. static int syncJournal(Pager *pPager){
  31291. int rc = SQLITE_OK;
  31292. /* Sync the journal before modifying the main database
  31293. ** (assuming there is a journal and it needs to be synced.)
  31294. */
  31295. if( pPager->needSync ){
  31296. assert( !pPager->tempFile );
  31297. if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  31298. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  31299. assert( pPager->journalOpen );
  31300. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  31301. i64 jrnlOff = journalHdrOffset(pPager);
  31302. u8 zMagic[8];
  31303. /* This block deals with an obscure problem. If the last connection
  31304. ** that wrote to this database was operating in persistent-journal
  31305. ** mode, then the journal file may at this point actually be larger
  31306. ** than Pager.journalOff bytes. If the next thing in the journal
  31307. ** file happens to be a journal-header (written as part of the
  31308. ** previous connections transaction), and a crash or power-failure
  31309. ** occurs after nRec is updated but before this connection writes
  31310. ** anything else to the journal file (or commits/rolls back its
  31311. ** transaction), then SQLite may become confused when doing the
  31312. ** hot-journal rollback following recovery. It may roll back all
  31313. ** of this connections data, then proceed to rolling back the old,
  31314. ** out-of-date data that follows it. Database corruption.
  31315. **
  31316. ** To work around this, if the journal file does appear to contain
  31317. ** a valid header following Pager.journalOff, then write a 0x00
  31318. ** byte to the start of it to prevent it from being recognized.
  31319. */
  31320. rc = sqlite3OsRead(pPager->jfd, zMagic, 8, jrnlOff);
  31321. if( rc==SQLITE_OK && 0==memcmp(zMagic, aJournalMagic, 8) ){
  31322. static const u8 zerobyte = 0;
  31323. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, jrnlOff);
  31324. }
  31325. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  31326. return rc;
  31327. }
  31328. /* Write the nRec value into the journal file header. If in
  31329. ** full-synchronous mode, sync the journal first. This ensures that
  31330. ** all data has really hit the disk before nRec is updated to mark
  31331. ** it as a candidate for rollback.
  31332. **
  31333. ** This is not required if the persistent media supports the
  31334. ** SAFE_APPEND property. Because in this case it is not possible
  31335. ** for garbage data to be appended to the file, the nRec field
  31336. ** is populated with 0xFFFFFFFF when the journal header is written
  31337. ** and never needs to be updated.
  31338. */
  31339. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  31340. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  31341. IOTRACE(("JSYNC %p\n", pPager))
  31342. rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
  31343. if( rc!=0 ) return rc;
  31344. }
  31345. jrnlOff = pPager->journalHdr + sizeof(aJournalMagic);
  31346. IOTRACE(("JHDR %p %lld %d\n", pPager, jrnlOff, 4));
  31347. rc = write32bits(pPager->jfd, jrnlOff, pPager->nRec);
  31348. if( rc ) return rc;
  31349. }
  31350. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  31351. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  31352. IOTRACE(("JSYNC %p\n", pPager))
  31353. rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags|
  31354. (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  31355. );
  31356. if( rc!=0 ) return rc;
  31357. }
  31358. pPager->journalStarted = 1;
  31359. }
  31360. pPager->needSync = 0;
  31361. /* Erase the needSync flag from every page.
  31362. */
  31363. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  31364. }
  31365. return rc;
  31366. }
  31367. /*
  31368. ** Given a list of pages (connected by the PgHdr.pDirty pointer) write
  31369. ** every one of those pages out to the database file. No calls are made
  31370. ** to the page-cache to mark the pages as clean. It is the responsibility
  31371. ** of the caller to use PcacheCleanAll() or PcacheMakeClean() to mark
  31372. ** the pages as clean.
  31373. */
  31374. static int pager_write_pagelist(PgHdr *pList){
  31375. Pager *pPager;
  31376. int rc;
  31377. if( pList==0 ) return SQLITE_OK;
  31378. pPager = pList->pPager;
  31379. /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
  31380. ** database file. If there is already an EXCLUSIVE lock, the following
  31381. ** calls to sqlite3OsLock() are no-ops.
  31382. **
  31383. ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
  31384. ** through an intermediate state PENDING. A PENDING lock prevents new
  31385. ** readers from attaching to the database but is unsufficient for us to
  31386. ** write. The idea of a PENDING lock is to prevent new readers from
  31387. ** coming in while we wait for existing readers to clear.
  31388. **
  31389. ** While the pager is in the RESERVED state, the original database file
  31390. ** is unchanged and we can rollback without having to playback the
  31391. ** journal into the original database file. Once we transition to
  31392. ** EXCLUSIVE, it means the database file has been changed and any rollback
  31393. ** will require a journal playback.
  31394. */
  31395. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  31396. if( rc!=SQLITE_OK ){
  31397. return rc;
  31398. }
  31399. while( pList ){
  31400. /* If the file has not yet been opened, open it now. */
  31401. if( !pPager->fd->pMethods ){
  31402. assert(pPager->tempFile);
  31403. rc = sqlite3PagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  31404. if( rc ) return rc;
  31405. }
  31406. /* If there are dirty pages in the page cache with page numbers greater
  31407. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  31408. ** make the file smaller (presumably by auto-vacuum code). Do not write
  31409. ** any such pages to the file.
  31410. */
  31411. if( pList->pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  31412. i64 offset = (pList->pgno-1)*(i64)pPager->pageSize;
  31413. char *pData = CODEC2(pPager, pList->pData, pList->pgno, 6);
  31414. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  31415. PAGERID(pPager), pList->pgno, pager_pagehash(pList)));
  31416. IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
  31417. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  31418. PAGER_INCR(sqlite3_pager_writedb_count);
  31419. PAGER_INCR(pPager->nWrite);
  31420. if( pList->pgno==1 ){
  31421. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  31422. }
  31423. if( pList->pgno>pPager->dbFileSize ){
  31424. pPager->dbFileSize = pList->pgno;
  31425. }
  31426. }
  31427. #ifndef NDEBUG
  31428. else{
  31429. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno));
  31430. }
  31431. #endif
  31432. if( rc ) return rc;
  31433. #ifdef SQLITE_CHECK_PAGES
  31434. pList->pageHash = pager_pagehash(pList);
  31435. #endif
  31436. pList = pList->pDirty;
  31437. }
  31438. return SQLITE_OK;
  31439. }
  31440. /*
  31441. ** Add the page to the sub-journal. It is the callers responsibility to
  31442. ** use subjRequiresPage() to check that it is really required before
  31443. ** calling this function.
  31444. */
  31445. static int subjournalPage(PgHdr *pPg){
  31446. int rc;
  31447. void *pData = pPg->pData;
  31448. Pager *pPager = pPg->pPager;
  31449. i64 offset = pPager->stmtNRec*(4+pPager->pageSize);
  31450. char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
  31451. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  31452. assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  31453. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  31454. if( rc==SQLITE_OK ){
  31455. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  31456. }
  31457. if( rc==SQLITE_OK ){
  31458. pPager->stmtNRec++;
  31459. assert( pPager->nSavepoint>0 );
  31460. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  31461. }
  31462. return rc;
  31463. }
  31464. /*
  31465. ** This function is called by the pcache layer when it has reached some
  31466. ** soft memory limit. The argument is a pointer to a purgeable Pager
  31467. ** object. This function attempts to make a single dirty page that has no
  31468. ** outstanding references (if one exists) clean so that it can be recycled
  31469. ** by the pcache layer.
  31470. */
  31471. static int pagerStress(void *p, PgHdr *pPg){
  31472. Pager *pPager = (Pager *)p;
  31473. int rc = SQLITE_OK;
  31474. if( pPager->doNotSync ){
  31475. return SQLITE_OK;
  31476. }
  31477. assert( pPg->flags&PGHDR_DIRTY );
  31478. if( pPager->errCode==SQLITE_OK ){
  31479. if( pPg->flags&PGHDR_NEED_SYNC ){
  31480. rc = syncJournal(pPager);
  31481. if( rc==SQLITE_OK && pPager->fullSync &&
  31482. !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
  31483. !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  31484. ){
  31485. pPager->nRec = 0;
  31486. rc = writeJournalHdr(pPager);
  31487. }
  31488. }
  31489. if( rc==SQLITE_OK ){
  31490. pPg->pDirty = 0;
  31491. if( pPg->pgno>pPager->dbSize && subjRequiresPage(pPg) ){
  31492. rc = subjournalPage(pPg);
  31493. }
  31494. if( rc==SQLITE_OK ){
  31495. rc = pager_write_pagelist(pPg);
  31496. }
  31497. }
  31498. if( rc!=SQLITE_OK ){
  31499. pager_error(pPager, rc);
  31500. }
  31501. }
  31502. if( rc==SQLITE_OK ){
  31503. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  31504. sqlite3PcacheMakeClean(pPg);
  31505. }
  31506. return rc;
  31507. }
  31508. /*
  31509. ** Return 1 if there is a hot journal on the given pager.
  31510. ** A hot journal is one that needs to be played back.
  31511. **
  31512. ** If the current size of the database file is 0 but a journal file
  31513. ** exists, that is probably an old journal left over from a prior
  31514. ** database with the same name. Just delete the journal.
  31515. **
  31516. ** Return negative if unable to determine the status of the journal.
  31517. **
  31518. ** This routine does not open the journal file to examine its
  31519. ** content. Hence, the journal might contain the name of a master
  31520. ** journal file that has been deleted, and hence not be hot. Or
  31521. ** the header of the journal might be zeroed out. This routine
  31522. ** does not discover these cases of a non-hot journal - if the
  31523. ** journal file exists and is not empty this routine assumes it
  31524. ** is hot. The pager_playback() routine will discover that the
  31525. ** journal file is not really hot and will no-op.
  31526. */
  31527. static int hasHotJournal(Pager *pPager, int *pExists){
  31528. sqlite3_vfs *pVfs = pPager->pVfs;
  31529. int rc = SQLITE_OK;
  31530. int exists = 0;
  31531. int locked = 0;
  31532. assert( pPager!=0 );
  31533. assert( pPager->useJournal );
  31534. assert( pPager->fd->pMethods );
  31535. *pExists = 0;
  31536. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  31537. if( rc==SQLITE_OK && exists ){
  31538. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  31539. }
  31540. if( rc==SQLITE_OK && exists && !locked ){
  31541. int nPage;
  31542. rc = sqlite3PagerPagecount(pPager, &nPage);
  31543. if( rc==SQLITE_OK ){
  31544. if( nPage==0 ){
  31545. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  31546. }else{
  31547. *pExists = 1;
  31548. }
  31549. }
  31550. }
  31551. return rc;
  31552. }
  31553. /*
  31554. ** Read the content of page pPg out of the database file.
  31555. */
  31556. static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
  31557. int rc;
  31558. i64 offset;
  31559. assert( MEMDB==0 );
  31560. assert(pPager->fd->pMethods||pPager->tempFile);
  31561. if( !pPager->fd->pMethods ){
  31562. return SQLITE_IOERR_SHORT_READ;
  31563. }
  31564. offset = (pgno-1)*(i64)pPager->pageSize;
  31565. rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, offset);
  31566. PAGER_INCR(sqlite3_pager_readdb_count);
  31567. PAGER_INCR(pPager->nRead);
  31568. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  31569. if( pgno==1 ){
  31570. memcpy(&pPager->dbFileVers, &((u8*)pPg->pData)[24],
  31571. sizeof(pPager->dbFileVers));
  31572. }
  31573. CODEC1(pPager, pPg->pData, pPg->pgno, 3);
  31574. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  31575. PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
  31576. return rc;
  31577. }
  31578. /*
  31579. ** This function is called to obtain the shared lock required before
  31580. ** data may be read from the pager cache. If the shared lock has already
  31581. ** been obtained, this function is a no-op.
  31582. **
  31583. ** Immediately after obtaining the shared lock (if required), this function
  31584. ** checks for a hot-journal file. If one is found, an emergency rollback
  31585. ** is performed immediately.
  31586. */
  31587. static int pagerSharedLock(Pager *pPager){
  31588. int rc = SQLITE_OK;
  31589. int isErrorReset = 0;
  31590. /* If this database is opened for exclusive access, has no outstanding
  31591. ** page references and is in an error-state, now is the chance to clear
  31592. ** the error. Discard the contents of the pager-cache and treat any
  31593. ** open journal file as a hot-journal.
  31594. */
  31595. if( !MEMDB && pPager->exclusiveMode
  31596. && sqlite3PcacheRefCount(pPager->pPCache)==0 && pPager->errCode
  31597. ){
  31598. if( pPager->journalOpen ){
  31599. isErrorReset = 1;
  31600. }
  31601. pPager->errCode = SQLITE_OK;
  31602. pager_reset(pPager);
  31603. }
  31604. /* If the pager is still in an error state, do not proceed. The error
  31605. ** state will be cleared at some point in the future when all page
  31606. ** references are dropped and the cache can be discarded.
  31607. */
  31608. if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
  31609. return pPager->errCode;
  31610. }
  31611. if( pPager->state==PAGER_UNLOCK || isErrorReset ){
  31612. sqlite3_vfs *pVfs = pPager->pVfs;
  31613. int isHotJournal = 0;
  31614. assert( !MEMDB );
  31615. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  31616. if( !pPager->noReadlock ){
  31617. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  31618. if( rc!=SQLITE_OK ){
  31619. assert( pPager->state==PAGER_UNLOCK );
  31620. return pager_error(pPager, rc);
  31621. }
  31622. }else if( pPager->state==PAGER_UNLOCK ){
  31623. pPager->state = PAGER_SHARED;
  31624. }
  31625. assert( pPager->state>=SHARED_LOCK );
  31626. /* If a journal file exists, and there is no RESERVED lock on the
  31627. ** database file, then it either needs to be played back or deleted.
  31628. */
  31629. if( !isErrorReset ){
  31630. rc = hasHotJournal(pPager, &isHotJournal);
  31631. if( rc!=SQLITE_OK ){
  31632. goto failed;
  31633. }
  31634. }
  31635. if( isErrorReset || isHotJournal ){
  31636. /* Get an EXCLUSIVE lock on the database file. At this point it is
  31637. ** important that a RESERVED lock is not obtained on the way to the
  31638. ** EXCLUSIVE lock. If it were, another process might open the
  31639. ** database file, detect the RESERVED lock, and conclude that the
  31640. ** database is safe to read while this process is still rolling it
  31641. ** back.
  31642. **
  31643. ** Because the intermediate RESERVED lock is not requested, the
  31644. ** second process will get to this point in the code and fail to
  31645. ** obtain its own EXCLUSIVE lock on the database file.
  31646. */
  31647. if( pPager->state<EXCLUSIVE_LOCK ){
  31648. rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
  31649. if( rc!=SQLITE_OK ){
  31650. rc = pager_error(pPager, rc);
  31651. goto failed;
  31652. }
  31653. pPager->state = PAGER_EXCLUSIVE;
  31654. }
  31655. /* Open the journal for read/write access. This is because in
  31656. ** exclusive-access mode the file descriptor will be kept open and
  31657. ** possibly used for a transaction later on. On some systems, the
  31658. ** OsTruncate() call used in exclusive-access mode also requires
  31659. ** a read/write file handle.
  31660. */
  31661. if( !isErrorReset && pPager->journalOpen==0 ){
  31662. int res;
  31663. rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
  31664. if( rc==SQLITE_OK ){
  31665. if( res ){
  31666. int fout = 0;
  31667. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  31668. assert( !pPager->tempFile );
  31669. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  31670. assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
  31671. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  31672. rc = SQLITE_CANTOPEN;
  31673. sqlite3OsClose(pPager->jfd);
  31674. }
  31675. }else{
  31676. /* If the journal does not exist, that means some other process
  31677. ** has already rolled it back */
  31678. rc = SQLITE_BUSY;
  31679. }
  31680. }
  31681. }
  31682. if( rc!=SQLITE_OK ){
  31683. goto failed;
  31684. }
  31685. pPager->journalOpen = 1;
  31686. pPager->journalStarted = 0;
  31687. pPager->journalOff = 0;
  31688. pPager->setMaster = 0;
  31689. pPager->journalHdr = 0;
  31690. /* Playback and delete the journal. Drop the database write
  31691. ** lock and reacquire the read lock. Purge the cache before
  31692. ** playing back the hot-journal so that we don't end up with
  31693. ** an inconsistent cache.
  31694. */
  31695. sqlite3PcacheClear(pPager->pPCache);
  31696. rc = pager_playback(pPager, 1);
  31697. if( rc!=SQLITE_OK ){
  31698. rc = pager_error(pPager, rc);
  31699. goto failed;
  31700. }
  31701. assert(pPager->state==PAGER_SHARED ||
  31702. (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
  31703. );
  31704. }
  31705. if( sqlite3PcachePagecount(pPager->pPCache)>0 ){
  31706. /* The shared-lock has just been acquired on the database file
  31707. ** and there are already pages in the cache (from a previous
  31708. ** read or write transaction). Check to see if the database
  31709. ** has been modified. If the database has changed, flush the
  31710. ** cache.
  31711. **
  31712. ** Database changes is detected by looking at 15 bytes beginning
  31713. ** at offset 24 into the file. The first 4 of these 16 bytes are
  31714. ** a 32-bit counter that is incremented with each change. The
  31715. ** other bytes change randomly with each file change when
  31716. ** a codec is in use.
  31717. **
  31718. ** There is a vanishingly small chance that a change will not be
  31719. ** detected. The chance of an undetected change is so small that
  31720. ** it can be neglected.
  31721. */
  31722. char dbFileVers[sizeof(pPager->dbFileVers)];
  31723. sqlite3PagerPagecount(pPager, 0);
  31724. if( pPager->errCode ){
  31725. rc = pPager->errCode;
  31726. goto failed;
  31727. }
  31728. assert( pPager->dbSizeValid );
  31729. if( pPager->dbSize>0 ){
  31730. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  31731. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  31732. if( rc!=SQLITE_OK ){
  31733. goto failed;
  31734. }
  31735. }else{
  31736. memset(dbFileVers, 0, sizeof(dbFileVers));
  31737. }
  31738. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  31739. pager_reset(pPager);
  31740. }
  31741. }
  31742. assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
  31743. }
  31744. failed:
  31745. if( rc!=SQLITE_OK ){
  31746. /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
  31747. pager_unlock(pPager);
  31748. }
  31749. return rc;
  31750. }
  31751. /*
  31752. ** Make sure we have the content for a page. If the page was
  31753. ** previously acquired with noContent==1, then the content was
  31754. ** just initialized to zeros instead of being read from disk.
  31755. ** But now we need the real data off of disk. So make sure we
  31756. ** have it. Read it in if we do not have it already.
  31757. */
  31758. static int pager_get_content(PgHdr *pPg){
  31759. if( pPg->flags&PGHDR_NEED_READ ){
  31760. int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
  31761. if( rc==SQLITE_OK ){
  31762. pPg->flags &= ~PGHDR_NEED_READ;
  31763. }else{
  31764. return rc;
  31765. }
  31766. }
  31767. return SQLITE_OK;
  31768. }
  31769. /*
  31770. ** If the reference count has reached zero, and the pager is not in the
  31771. ** middle of a write transaction or opened in exclusive mode, unlock it.
  31772. */
  31773. static void pagerUnlockIfUnused(Pager *pPager){
  31774. if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
  31775. && (!pPager->exclusiveMode || pPager->journalOff>0)
  31776. ){
  31777. pagerUnlockAndRollback(pPager);
  31778. }
  31779. }
  31780. /*
  31781. ** Drop a page from the cache using sqlite3PcacheDrop().
  31782. **
  31783. ** If this means there are now no pages with references to them, a rollback
  31784. ** occurs and the lock on the database is removed.
  31785. */
  31786. static void pagerDropPage(DbPage *pPg){
  31787. Pager *pPager = pPg->pPager;
  31788. sqlite3PcacheDrop(pPg);
  31789. pagerUnlockIfUnused(pPager);
  31790. }
  31791. /*
  31792. ** Acquire a page.
  31793. **
  31794. ** A read lock on the disk file is obtained when the first page is acquired.
  31795. ** This read lock is dropped when the last page is released.
  31796. **
  31797. ** This routine works for any page number greater than 0. If the database
  31798. ** file is smaller than the requested page, then no actual disk
  31799. ** read occurs and the memory image of the page is initialized to
  31800. ** all zeros. The extra data appended to a page is always initialized
  31801. ** to zeros the first time a page is loaded into memory.
  31802. **
  31803. ** The acquisition might fail for several reasons. In all cases,
  31804. ** an appropriate error code is returned and *ppPage is set to NULL.
  31805. **
  31806. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  31807. ** to find a page in the in-memory cache first. If the page is not already
  31808. ** in memory, this routine goes to disk to read it in whereas Lookup()
  31809. ** just returns 0. This routine acquires a read-lock the first time it
  31810. ** has to go to disk, and could also playback an old journal if necessary.
  31811. ** Since Lookup() never goes to disk, it never has to deal with locks
  31812. ** or journal files.
  31813. **
  31814. ** If noContent is false, the page contents are actually read from disk.
  31815. ** If noContent is true, it means that we do not care about the contents
  31816. ** of the page at this time, so do not do a disk read. Just fill in the
  31817. ** page content with zeros. But mark the fact that we have not read the
  31818. ** content by setting the PgHdr.needRead flag. Later on, if
  31819. ** sqlite3PagerWrite() is called on this page or if this routine is
  31820. ** called again with noContent==0, that means that the content is needed
  31821. ** and the disk read should occur at that point.
  31822. */
  31823. SQLITE_PRIVATE int sqlite3PagerAcquire(
  31824. Pager *pPager, /* The pager open on the database file */
  31825. Pgno pgno, /* Page number to fetch */
  31826. DbPage **ppPage, /* Write a pointer to the page here */
  31827. int noContent /* Do not bother reading content from disk if true */
  31828. ){
  31829. PgHdr *pPg = 0;
  31830. int rc;
  31831. assert( pPager->state==PAGER_UNLOCK
  31832. || sqlite3PcacheRefCount(pPager->pPCache)>0
  31833. || pgno==1
  31834. );
  31835. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  31836. ** number greater than this, or zero, is requested.
  31837. */
  31838. if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  31839. return SQLITE_CORRUPT_BKPT;
  31840. }
  31841. /* Make sure we have not hit any critical errors.
  31842. */
  31843. assert( pPager!=0 );
  31844. *ppPage = 0;
  31845. /* If this is the first page accessed, then get a SHARED lock
  31846. ** on the database file. pagerSharedLock() is a no-op if
  31847. ** a database lock is already held.
  31848. */
  31849. rc = pagerSharedLock(pPager);
  31850. if( rc!=SQLITE_OK ){
  31851. return rc;
  31852. }
  31853. assert( pPager->state!=PAGER_UNLOCK );
  31854. rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, &pPg);
  31855. if( rc!=SQLITE_OK ){
  31856. return rc;
  31857. }
  31858. if( pPg->pPager==0 ){
  31859. /* The pager cache has created a new page. Its content needs to
  31860. ** be initialized.
  31861. */
  31862. int nMax;
  31863. PAGER_INCR(pPager->nMiss);
  31864. pPg->pPager = pPager;
  31865. memset(pPg->pExtra, 0, pPager->nExtra);
  31866. rc = sqlite3PagerPagecount(pPager, &nMax);
  31867. if( rc!=SQLITE_OK ){
  31868. sqlite3PagerUnref(pPg);
  31869. return rc;
  31870. }
  31871. if( nMax<(int)pgno || MEMDB || noContent ){
  31872. if( pgno>pPager->mxPgno ){
  31873. sqlite3PagerUnref(pPg);
  31874. return SQLITE_FULL;
  31875. }
  31876. memset(pPg->pData, 0, pPager->pageSize);
  31877. if( noContent ){
  31878. pPg->flags |= PGHDR_NEED_READ;
  31879. }
  31880. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  31881. }else{
  31882. rc = readDbPage(pPager, pPg, pgno);
  31883. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  31884. /* sqlite3PagerUnref(pPg); */
  31885. pagerDropPage(pPg);
  31886. return rc;
  31887. }
  31888. }
  31889. #ifdef SQLITE_CHECK_PAGES
  31890. pPg->pageHash = pager_pagehash(pPg);
  31891. #endif
  31892. }else{
  31893. /* The requested page is in the page cache. */
  31894. assert(sqlite3PcacheRefCount(pPager->pPCache)>0 || pgno==1);
  31895. PAGER_INCR(pPager->nHit);
  31896. if( !noContent ){
  31897. rc = pager_get_content(pPg);
  31898. if( rc ){
  31899. sqlite3PagerUnref(pPg);
  31900. return rc;
  31901. }
  31902. }
  31903. }
  31904. *ppPage = pPg;
  31905. return SQLITE_OK;
  31906. }
  31907. /*
  31908. ** Acquire a page if it is already in the in-memory cache. Do
  31909. ** not read the page from disk. Return a pointer to the page,
  31910. ** or 0 if the page is not in cache.
  31911. **
  31912. ** See also sqlite3PagerGet(). The difference between this routine
  31913. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  31914. ** in the page if the page is not already in cache. This routine
  31915. ** returns NULL if the page is not in cache or if a disk I/O error
  31916. ** has ever happened.
  31917. */
  31918. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  31919. PgHdr *pPg = 0;
  31920. assert( pPager!=0 );
  31921. assert( pgno!=0 );
  31922. if( (pPager->state!=PAGER_UNLOCK)
  31923. && (pPager->errCode==SQLITE_OK || pPager->errCode==SQLITE_FULL)
  31924. ){
  31925. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  31926. }
  31927. return pPg;
  31928. }
  31929. /*
  31930. ** Release a page.
  31931. **
  31932. ** If the number of references to the page drop to zero, then the
  31933. ** page is added to the LRU list. When all references to all pages
  31934. ** are released, a rollback occurs and the lock on the database is
  31935. ** removed.
  31936. */
  31937. SQLITE_PRIVATE int sqlite3PagerUnref(DbPage *pPg){
  31938. if( pPg ){
  31939. Pager *pPager = pPg->pPager;
  31940. sqlite3PcacheRelease(pPg);
  31941. pagerUnlockIfUnused(pPager);
  31942. }
  31943. return SQLITE_OK;
  31944. }
  31945. /*
  31946. ** If the main journal file has already been opened, ensure that the
  31947. ** sub-journal file is open too. If the main journal is not open,
  31948. ** this function is a no-op.
  31949. **
  31950. ** SQLITE_OK is returned if everything goes according to plan. An
  31951. ** SQLITE_IOERR_XXX error code is returned if the call to
  31952. ** sqlite3OsOpen() fails.
  31953. */
  31954. static int openSubJournal(Pager *pPager){
  31955. int rc = SQLITE_OK;
  31956. if( pPager->journalOpen && !pPager->sjfd->pMethods ){
  31957. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  31958. sqlite3MemJournalOpen(pPager->sjfd);
  31959. }else{
  31960. rc = sqlite3PagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  31961. }
  31962. }
  31963. return rc;
  31964. }
  31965. /*
  31966. ** Create a journal file for pPager. There should already be a RESERVED
  31967. ** or EXCLUSIVE lock on the database file when this routine is called.
  31968. **
  31969. ** Return SQLITE_OK if everything. Return an error code and release the
  31970. ** write lock if anything goes wrong.
  31971. */
  31972. static int pager_open_journal(Pager *pPager){
  31973. sqlite3_vfs *pVfs = pPager->pVfs;
  31974. int flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE);
  31975. int rc;
  31976. assert( pPager->state>=PAGER_RESERVED );
  31977. assert( pPager->useJournal );
  31978. assert( pPager->pInJournal==0 );
  31979. sqlite3PagerPagecount(pPager, 0);
  31980. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  31981. if( pPager->pInJournal==0 ){
  31982. rc = SQLITE_NOMEM;
  31983. goto failed_to_open_journal;
  31984. }
  31985. if( pPager->journalOpen==0 ){
  31986. if( pPager->tempFile ){
  31987. flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
  31988. }else{
  31989. flags |= (SQLITE_OPEN_MAIN_JOURNAL);
  31990. }
  31991. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  31992. sqlite3MemJournalOpen(pPager->jfd);
  31993. rc = SQLITE_OK;
  31994. }else{
  31995. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  31996. rc = sqlite3JournalOpen(
  31997. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  31998. );
  31999. #else
  32000. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  32001. #endif
  32002. }
  32003. assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
  32004. pPager->journalOff = 0;
  32005. pPager->setMaster = 0;
  32006. pPager->journalHdr = 0;
  32007. if( rc!=SQLITE_OK ){
  32008. if( rc==SQLITE_NOMEM ){
  32009. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  32010. }
  32011. goto failed_to_open_journal;
  32012. }
  32013. }
  32014. pPager->journalOpen = 1;
  32015. pPager->journalStarted = 0;
  32016. pPager->needSync = 0;
  32017. pPager->nRec = 0;
  32018. if( pPager->errCode ){
  32019. rc = pPager->errCode;
  32020. goto failed_to_open_journal;
  32021. }
  32022. pPager->dbOrigSize = pPager->dbSize;
  32023. rc = writeJournalHdr(pPager);
  32024. if( pPager->nSavepoint && rc==SQLITE_OK ){
  32025. rc = openSubJournal(pPager);
  32026. }
  32027. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_NOMEM ){
  32028. rc = pager_end_transaction(pPager, 0);
  32029. if( rc==SQLITE_OK ){
  32030. rc = SQLITE_FULL;
  32031. }
  32032. }
  32033. return rc;
  32034. failed_to_open_journal:
  32035. sqlite3BitvecDestroy(pPager->pInJournal);
  32036. pPager->pInJournal = 0;
  32037. return rc;
  32038. }
  32039. /*
  32040. ** Acquire a write-lock on the database. The lock is removed when
  32041. ** the any of the following happen:
  32042. **
  32043. ** * sqlite3PagerCommitPhaseTwo() is called.
  32044. ** * sqlite3PagerRollback() is called.
  32045. ** * sqlite3PagerClose() is called.
  32046. ** * sqlite3PagerUnref() is called to on every outstanding page.
  32047. **
  32048. ** The first parameter to this routine is a pointer to any open page of the
  32049. ** database file. Nothing changes about the page - it is used merely to
  32050. ** acquire a pointer to the Pager structure and as proof that there is
  32051. ** already a read-lock on the database.
  32052. **
  32053. ** The second parameter indicates how much space in bytes to reserve for a
  32054. ** master journal file-name at the start of the journal when it is created.
  32055. **
  32056. ** A journal file is opened if this is not a temporary file. For temporary
  32057. ** files, the opening of the journal file is deferred until there is an
  32058. ** actual need to write to the journal.
  32059. **
  32060. ** If the database is already reserved for writing, this routine is a no-op.
  32061. **
  32062. ** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
  32063. ** immediately instead of waiting until we try to flush the cache. The
  32064. ** exFlag is ignored if a transaction is already active.
  32065. */
  32066. SQLITE_PRIVATE int sqlite3PagerBegin(DbPage *pPg, int exFlag){
  32067. Pager *pPager = pPg->pPager;
  32068. int rc = SQLITE_OK;
  32069. assert( pPg->nRef>0 );
  32070. assert( pPager->state!=PAGER_UNLOCK );
  32071. if( pPager->state==PAGER_SHARED ){
  32072. assert( pPager->pInJournal==0 );
  32073. assert( !MEMDB );
  32074. rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
  32075. if( rc==SQLITE_OK ){
  32076. pPager->state = PAGER_RESERVED;
  32077. if( exFlag ){
  32078. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  32079. }
  32080. }
  32081. if( rc!=SQLITE_OK ){
  32082. return rc;
  32083. }
  32084. pPager->dirtyCache = 0;
  32085. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  32086. if( pPager->useJournal && !pPager->tempFile
  32087. && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  32088. rc = pager_open_journal(pPager);
  32089. }
  32090. }else if( pPager->journalOpen && pPager->journalOff==0 ){
  32091. /* This happens when the pager was in exclusive-access mode the last
  32092. ** time a (read or write) transaction was successfully concluded
  32093. ** by this connection. Instead of deleting the journal file it was
  32094. ** kept open and either was truncated to 0 bytes or its header was
  32095. ** overwritten with zeros.
  32096. */
  32097. assert( pPager->nRec==0 );
  32098. assert( pPager->dbOrigSize==0 );
  32099. assert( pPager->pInJournal==0 );
  32100. sqlite3PagerPagecount(pPager, 0);
  32101. pPager->pInJournal = sqlite3BitvecCreate( pPager->dbSize );
  32102. if( !pPager->pInJournal ){
  32103. rc = SQLITE_NOMEM;
  32104. }else{
  32105. pPager->dbOrigSize = pPager->dbSize;
  32106. rc = writeJournalHdr(pPager);
  32107. }
  32108. }
  32109. assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
  32110. return rc;
  32111. }
  32112. /*
  32113. ** Mark a data page as writeable. The page is written into the journal
  32114. ** if it is not there already. This routine must be called before making
  32115. ** changes to a page.
  32116. **
  32117. ** The first time this routine is called, the pager creates a new
  32118. ** journal and acquires a RESERVED lock on the database. If the RESERVED
  32119. ** lock could not be acquired, this routine returns SQLITE_BUSY. The
  32120. ** calling routine must check for that return value and be careful not to
  32121. ** change any page data until this routine returns SQLITE_OK.
  32122. **
  32123. ** If the journal file could not be written because the disk is full,
  32124. ** then this routine returns SQLITE_FULL and does an immediate rollback.
  32125. ** All subsequent write attempts also return SQLITE_FULL until there
  32126. ** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
  32127. ** reset.
  32128. */
  32129. static int pager_write(PgHdr *pPg){
  32130. void *pData = pPg->pData;
  32131. Pager *pPager = pPg->pPager;
  32132. int rc = SQLITE_OK;
  32133. /* Check for errors
  32134. */
  32135. if( pPager->errCode ){
  32136. return pPager->errCode;
  32137. }
  32138. if( pPager->readOnly ){
  32139. return SQLITE_PERM;
  32140. }
  32141. assert( !pPager->setMaster );
  32142. CHECK_PAGE(pPg);
  32143. /* If this page was previously acquired with noContent==1, that means
  32144. ** we didn't really read in the content of the page. This can happen
  32145. ** (for example) when the page is being moved to the freelist. But
  32146. ** now we are (perhaps) moving the page off of the freelist for
  32147. ** reuse and we need to know its original content so that content
  32148. ** can be stored in the rollback journal. So do the read at this
  32149. ** time.
  32150. */
  32151. rc = pager_get_content(pPg);
  32152. if( rc ){
  32153. return rc;
  32154. }
  32155. /* Mark the page as dirty. If the page has already been written
  32156. ** to the journal then we can return right away.
  32157. */
  32158. sqlite3PcacheMakeDirty(pPg);
  32159. if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
  32160. pPager->dirtyCache = 1;
  32161. pPager->dbModified = 1;
  32162. }else{
  32163. /* If we get this far, it means that the page needs to be
  32164. ** written to the transaction journal or the ckeckpoint journal
  32165. ** or both.
  32166. **
  32167. ** First check to see that the transaction journal exists and
  32168. ** create it if it does not.
  32169. */
  32170. assert( pPager->state!=PAGER_UNLOCK );
  32171. rc = sqlite3PagerBegin(pPg, 0);
  32172. if( rc!=SQLITE_OK ){
  32173. return rc;
  32174. }
  32175. assert( pPager->state>=PAGER_RESERVED );
  32176. if( !pPager->journalOpen && pPager->useJournal
  32177. && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  32178. rc = pager_open_journal(pPager);
  32179. if( rc!=SQLITE_OK ) return rc;
  32180. }
  32181. pPager->dirtyCache = 1;
  32182. pPager->dbModified = 1;
  32183. /* The transaction journal now exists and we have a RESERVED or an
  32184. ** EXCLUSIVE lock on the main database file. Write the current page to
  32185. ** the transaction journal if it is not there already.
  32186. */
  32187. if( !pageInJournal(pPg) && pPager->journalOpen ){
  32188. if( pPg->pgno<=pPager->dbOrigSize ){
  32189. u32 cksum;
  32190. char *pData2;
  32191. /* We should never write to the journal file the page that
  32192. ** contains the database locks. The following assert verifies
  32193. ** that we do not. */
  32194. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  32195. pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
  32196. cksum = pager_cksum(pPager, (u8*)pData2);
  32197. rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
  32198. if( rc==SQLITE_OK ){
  32199. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
  32200. pPager->journalOff + 4);
  32201. pPager->journalOff += pPager->pageSize+4;
  32202. }
  32203. if( rc==SQLITE_OK ){
  32204. rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
  32205. pPager->journalOff += 4;
  32206. }
  32207. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  32208. pPager->journalOff, pPager->pageSize));
  32209. PAGER_INCR(sqlite3_pager_writej_count);
  32210. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  32211. PAGERID(pPager), pPg->pgno,
  32212. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  32213. /* Even if an IO or diskfull error occurred while journalling the
  32214. ** page in the block above, set the need-sync flag for the page.
  32215. ** Otherwise, when the transaction is rolled back, the logic in
  32216. ** playback_one_page() will think that the page needs to be restored
  32217. ** in the database file. And if an IO error occurs while doing so,
  32218. ** then corruption may follow.
  32219. */
  32220. if( !pPager->noSync ){
  32221. pPg->flags |= PGHDR_NEED_SYNC;
  32222. pPager->needSync = 1;
  32223. }
  32224. /* An error has occured writing to the journal file. The
  32225. ** transaction will be rolled back by the layer above.
  32226. */
  32227. if( rc!=SQLITE_OK ){
  32228. return rc;
  32229. }
  32230. pPager->nRec++;
  32231. assert( pPager->pInJournal!=0 );
  32232. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  32233. testcase( rc==SQLITE_NOMEM );
  32234. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  32235. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  32236. if( rc!=SQLITE_OK ){
  32237. assert( rc==SQLITE_NOMEM );
  32238. return rc;
  32239. }
  32240. }else{
  32241. if( !pPager->journalStarted && !pPager->noSync ){
  32242. pPg->flags |= PGHDR_NEED_SYNC;
  32243. pPager->needSync = 1;
  32244. }
  32245. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  32246. PAGERID(pPager), pPg->pgno,
  32247. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  32248. }
  32249. }
  32250. /* If the statement journal is open and the page is not in it,
  32251. ** then write the current page to the statement journal. Note that
  32252. ** the statement journal format differs from the standard journal format
  32253. ** in that it omits the checksums and the header.
  32254. */
  32255. if( subjRequiresPage(pPg) ){
  32256. rc = subjournalPage(pPg);
  32257. }
  32258. }
  32259. /* Update the database size and return.
  32260. */
  32261. assert( pPager->state>=PAGER_SHARED );
  32262. if( pPager->dbSize<pPg->pgno ){
  32263. pPager->dbSize = pPg->pgno;
  32264. if( pPager->dbSize==(PAGER_MJ_PGNO(pPager)-1) ){
  32265. pPager->dbSize++;
  32266. }
  32267. }
  32268. return rc;
  32269. }
  32270. /*
  32271. ** This function is used to mark a data-page as writable. It uses
  32272. ** pager_write() to open a journal file (if it is not already open)
  32273. ** and write the page *pData to the journal.
  32274. **
  32275. ** The difference between this function and pager_write() is that this
  32276. ** function also deals with the special case where 2 or more pages
  32277. ** fit on a single disk sector. In this case all co-resident pages
  32278. ** must have been written to the journal file before returning.
  32279. */
  32280. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  32281. int rc = SQLITE_OK;
  32282. PgHdr *pPg = pDbPage;
  32283. Pager *pPager = pPg->pPager;
  32284. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  32285. if( nPagePerSector>1 ){
  32286. Pgno nPageCount; /* Total number of pages in database file */
  32287. Pgno pg1; /* First page of the sector pPg is located on. */
  32288. int nPage; /* Number of pages starting at pg1 to journal */
  32289. int ii;
  32290. int needSync = 0;
  32291. /* Set the doNotSync flag to 1. This is because we cannot allow a journal
  32292. ** header to be written between the pages journaled by this function.
  32293. */
  32294. assert( !MEMDB );
  32295. assert( pPager->doNotSync==0 );
  32296. pPager->doNotSync = 1;
  32297. /* This trick assumes that both the page-size and sector-size are
  32298. ** an integer power of 2. It sets variable pg1 to the identifier
  32299. ** of the first page of the sector pPg is located on.
  32300. */
  32301. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  32302. sqlite3PagerPagecount(pPager, (int *)&nPageCount);
  32303. if( pPg->pgno>nPageCount ){
  32304. nPage = (pPg->pgno - pg1)+1;
  32305. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  32306. nPage = nPageCount+1-pg1;
  32307. }else{
  32308. nPage = nPagePerSector;
  32309. }
  32310. assert(nPage>0);
  32311. assert(pg1<=pPg->pgno);
  32312. assert((pg1+nPage)>pPg->pgno);
  32313. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  32314. Pgno pg = pg1+ii;
  32315. PgHdr *pPage;
  32316. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  32317. if( pg!=PAGER_MJ_PGNO(pPager) ){
  32318. rc = sqlite3PagerGet(pPager, pg, &pPage);
  32319. if( rc==SQLITE_OK ){
  32320. rc = pager_write(pPage);
  32321. if( pPage->flags&PGHDR_NEED_SYNC ){
  32322. needSync = 1;
  32323. assert(pPager->needSync);
  32324. }
  32325. sqlite3PagerUnref(pPage);
  32326. }
  32327. }
  32328. }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
  32329. if( pPage->flags&PGHDR_NEED_SYNC ){
  32330. needSync = 1;
  32331. }
  32332. sqlite3PagerUnref(pPage);
  32333. }
  32334. }
  32335. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  32336. ** starting at pg1, then it needs to be set for all of them. Because
  32337. ** writing to any of these nPage pages may damage the others, the
  32338. ** journal file must contain sync()ed copies of all of them
  32339. ** before any of them can be written out to the database file.
  32340. */
  32341. if( needSync ){
  32342. assert( !MEMDB && pPager->noSync==0 );
  32343. for(ii=0; ii<nPage && needSync; ii++){
  32344. PgHdr *pPage = pager_lookup(pPager, pg1+ii);
  32345. if( pPage ){
  32346. pPage->flags |= PGHDR_NEED_SYNC;
  32347. sqlite3PagerUnref(pPage);
  32348. }
  32349. }
  32350. assert(pPager->needSync);
  32351. }
  32352. assert( pPager->doNotSync==1 );
  32353. pPager->doNotSync = 0;
  32354. }else{
  32355. rc = pager_write(pDbPage);
  32356. }
  32357. return rc;
  32358. }
  32359. /*
  32360. ** Return TRUE if the page given in the argument was previously passed
  32361. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  32362. ** to change the content of the page.
  32363. */
  32364. #ifndef NDEBUG
  32365. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  32366. return pPg->flags&PGHDR_DIRTY;
  32367. }
  32368. #endif
  32369. /*
  32370. ** A call to this routine tells the pager that it is not necessary to
  32371. ** write the information on page pPg back to the disk, even though
  32372. ** that page might be marked as dirty. This happens, for example, when
  32373. ** the page has been added as a leaf of the freelist and so its
  32374. ** content no longer matters.
  32375. **
  32376. ** The overlying software layer calls this routine when all of the data
  32377. ** on the given page is unused. The pager marks the page as clean so
  32378. ** that it does not get written to disk.
  32379. **
  32380. ** Tests show that this optimization, together with the
  32381. ** sqlite3PagerDontRollback() below, more than double the speed
  32382. ** of large INSERT operations and quadruple the speed of large DELETEs.
  32383. **
  32384. ** When this routine is called, set the bit corresponding to pDbPage in
  32385. ** the Pager.pAlwaysRollback bitvec. Subsequent calls to
  32386. ** sqlite3PagerDontRollback() for the same page will thereafter be ignored.
  32387. ** This is necessary to avoid a problem where a page with data is added to
  32388. ** the freelist during one part of a transaction then removed from the
  32389. ** freelist during a later part of the same transaction and reused for some
  32390. ** other purpose. When it is first added to the freelist, this routine is
  32391. ** called. When reused, the sqlite3PagerDontRollback() routine is called.
  32392. ** But because the page contains critical data, we still need to be sure it
  32393. ** gets rolled back in spite of the sqlite3PagerDontRollback() call.
  32394. */
  32395. SQLITE_PRIVATE int sqlite3PagerDontWrite(DbPage *pDbPage){
  32396. PgHdr *pPg = pDbPage;
  32397. Pager *pPager = pPg->pPager;
  32398. int rc;
  32399. if( pPg->pgno>pPager->dbOrigSize ){
  32400. return SQLITE_OK;
  32401. }
  32402. if( pPager->pAlwaysRollback==0 ){
  32403. assert( pPager->pInJournal );
  32404. pPager->pAlwaysRollback = sqlite3BitvecCreate(pPager->dbOrigSize);
  32405. if( !pPager->pAlwaysRollback ){
  32406. return SQLITE_NOMEM;
  32407. }
  32408. }
  32409. rc = sqlite3BitvecSet(pPager->pAlwaysRollback, pPg->pgno);
  32410. if( rc==SQLITE_OK && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  32411. assert( pPager->state>=PAGER_SHARED );
  32412. if( pPager->dbSize==pPg->pgno && pPager->dbOrigSize<pPager->dbSize ){
  32413. /* If this pages is the last page in the file and the file has grown
  32414. ** during the current transaction, then do NOT mark the page as clean.
  32415. ** When the database file grows, we must make sure that the last page
  32416. ** gets written at least once so that the disk file will be the correct
  32417. ** size. If you do not write this page and the size of the file
  32418. ** on the disk ends up being too small, that can lead to database
  32419. ** corruption during the next transaction.
  32420. */
  32421. }else{
  32422. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  32423. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  32424. pPg->flags |= PGHDR_DONT_WRITE;
  32425. #ifdef SQLITE_CHECK_PAGES
  32426. pPg->pageHash = pager_pagehash(pPg);
  32427. #endif
  32428. }
  32429. }
  32430. return rc;
  32431. }
  32432. /*
  32433. ** A call to this routine tells the pager that if a rollback occurs,
  32434. ** it is not necessary to restore the data on the given page. This
  32435. ** means that the pager does not have to record the given page in the
  32436. ** rollback journal.
  32437. **
  32438. ** If we have not yet actually read the content of this page (if
  32439. ** the PgHdr.needRead flag is set) then this routine acts as a promise
  32440. ** that we will never need to read the page content in the future.
  32441. ** so the needRead flag can be cleared at this point.
  32442. */
  32443. SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){
  32444. Pager *pPager = pPg->pPager;
  32445. TESTONLY( int rc; ) /* Return value from sqlite3BitvecSet() */
  32446. assert( pPager->state>=PAGER_RESERVED );
  32447. /* If the journal file is not open, or DontWrite() has been called on
  32448. ** this page (DontWrite() sets the Pager.pAlwaysRollback bit), then this
  32449. ** function is a no-op.
  32450. */
  32451. if( pPager->journalOpen==0
  32452. || sqlite3BitvecTest(pPager->pAlwaysRollback, pPg->pgno)
  32453. || pPg->pgno>pPager->dbOrigSize
  32454. ){
  32455. return;
  32456. }
  32457. #ifdef SQLITE_SECURE_DELETE
  32458. if( sqlite3BitvecTest(pPager->pInJournal, pPg->pgno)!=0
  32459. || pPg->pgno>pPager->dbOrigSize ){
  32460. return;
  32461. }
  32462. #endif
  32463. /* If SECURE_DELETE is disabled, then there is no way that this
  32464. ** routine can be called on a page for which sqlite3PagerDontWrite()
  32465. ** has not been previously called during the same transaction.
  32466. ** And if DontWrite() has previously been called, the following
  32467. ** conditions must be met.
  32468. **
  32469. ** (Later:) Not true. If the database is corrupted by having duplicate
  32470. ** pages on the freelist (ex: corrupt9.test) then the following is not
  32471. ** necessarily true:
  32472. */
  32473. /* assert( !pPg->inJournal && (int)pPg->pgno <= pPager->dbOrigSize ); */
  32474. assert( pPager->pInJournal!=0 );
  32475. pPg->flags &= ~PGHDR_NEED_READ;
  32476. /* Failure to set the bits in the InJournal bit-vectors is benign.
  32477. ** It merely means that we might do some extra work to journal a page
  32478. ** that does not need to be journaled. Nevertheless, be sure to test the
  32479. ** case where a malloc error occurs while trying to set a bit in a
  32480. ** bit vector.
  32481. */
  32482. sqlite3BeginBenignMalloc();
  32483. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  32484. testcase( rc==SQLITE_NOMEM );
  32485. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pPg->pgno);
  32486. testcase( rc==SQLITE_NOMEM );
  32487. sqlite3EndBenignMalloc();
  32488. PAGERTRACE(("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  32489. IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
  32490. }
  32491. /*
  32492. ** This routine is called to increment the database file change-counter,
  32493. ** stored at byte 24 of the pager file.
  32494. */
  32495. static int pager_incr_changecounter(Pager *pPager, int isDirect){
  32496. PgHdr *pPgHdr;
  32497. u32 change_counter;
  32498. int rc = SQLITE_OK;
  32499. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  32500. assert( isDirect==0 ); /* isDirect is only true for atomic writes */
  32501. #endif
  32502. if( !pPager->changeCountDone && pPager->dbSize>0 ){
  32503. /* Open page 1 of the file for writing. */
  32504. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  32505. if( rc!=SQLITE_OK ) return rc;
  32506. if( !isDirect ){
  32507. rc = sqlite3PagerWrite(pPgHdr);
  32508. if( rc!=SQLITE_OK ){
  32509. sqlite3PagerUnref(pPgHdr);
  32510. return rc;
  32511. }
  32512. }
  32513. /* Increment the value just read and write it back to byte 24. */
  32514. change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
  32515. change_counter++;
  32516. put32bits(((char*)pPgHdr->pData)+24, change_counter);
  32517. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  32518. if( isDirect && pPager->fd->pMethods ){
  32519. const void *zBuf = pPgHdr->pData;
  32520. assert( pPager->dbFileSize>0 );
  32521. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  32522. }
  32523. #endif
  32524. /* Release the page reference. */
  32525. sqlite3PagerUnref(pPgHdr);
  32526. pPager->changeCountDone = 1;
  32527. }
  32528. return rc;
  32529. }
  32530. /*
  32531. ** Sync the pager file to disk.
  32532. */
  32533. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  32534. int rc;
  32535. if( MEMDB ){
  32536. rc = SQLITE_OK;
  32537. }else{
  32538. rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
  32539. }
  32540. return rc;
  32541. }
  32542. /*
  32543. ** Sync the database file for the pager pPager. zMaster points to the name
  32544. ** of a master journal file that should be written into the individual
  32545. ** journal file. zMaster may be NULL, which is interpreted as no master
  32546. ** journal (a single database transaction).
  32547. **
  32548. ** This routine ensures that the journal is synced, all dirty pages written
  32549. ** to the database file and the database file synced. The only thing that
  32550. ** remains to commit the transaction is to delete the journal file (or
  32551. ** master journal file if specified).
  32552. **
  32553. ** Note that if zMaster==NULL, this does not overwrite a previous value
  32554. ** passed to an sqlite3PagerCommitPhaseOne() call.
  32555. **
  32556. ** If the final parameter - noSync - is true, then the database file itself
  32557. ** is not synced. The caller must call sqlite3PagerSync() directly to
  32558. ** sync the database file before calling CommitPhaseTwo() to delete the
  32559. ** journal file in this case.
  32560. */
  32561. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  32562. Pager *pPager,
  32563. const char *zMaster,
  32564. int noSync
  32565. ){
  32566. int rc = SQLITE_OK;
  32567. if( pPager->errCode ){
  32568. return pPager->errCode;
  32569. }
  32570. /* If no changes have been made, we can leave the transaction early.
  32571. */
  32572. if( pPager->dbModified==0 &&
  32573. (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
  32574. pPager->exclusiveMode!=0) ){
  32575. assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
  32576. return SQLITE_OK;
  32577. }
  32578. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  32579. pPager->zFilename, zMaster, pPager->dbSize));
  32580. /* If this is an in-memory db, or no pages have been written to, or this
  32581. ** function has already been called, it is a no-op.
  32582. */
  32583. if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
  32584. PgHdr *pPg;
  32585. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  32586. /* The atomic-write optimization can be used if all of the
  32587. ** following are true:
  32588. **
  32589. ** + The file-system supports the atomic-write property for
  32590. ** blocks of size page-size, and
  32591. ** + This commit is not part of a multi-file transaction, and
  32592. ** + Exactly one page has been modified and store in the journal file.
  32593. **
  32594. ** If the optimization can be used, then the journal file will never
  32595. ** be created for this transaction.
  32596. */
  32597. int useAtomicWrite;
  32598. pPg = sqlite3PcacheDirtyList(pPager->pPCache);
  32599. useAtomicWrite = (
  32600. !zMaster &&
  32601. pPager->journalOpen &&
  32602. pPager->journalOff==jrnlBufferSize(pPager) &&
  32603. pPager->dbSize>=pPager->dbFileSize &&
  32604. (pPg==0 || pPg->pDirty==0)
  32605. );
  32606. assert( pPager->journalOpen || pPager->journalMode==PAGER_JOURNALMODE_OFF );
  32607. if( useAtomicWrite ){
  32608. /* Update the nRec field in the journal file. */
  32609. int offset = pPager->journalHdr + sizeof(aJournalMagic);
  32610. assert(pPager->nRec==1);
  32611. rc = write32bits(pPager->jfd, offset, pPager->nRec);
  32612. /* Update the db file change counter. The following call will modify
  32613. ** the in-memory representation of page 1 to include the updated
  32614. ** change counter and then write page 1 directly to the database
  32615. ** file. Because of the atomic-write property of the host file-system,
  32616. ** this is safe.
  32617. */
  32618. if( rc==SQLITE_OK ){
  32619. rc = pager_incr_changecounter(pPager, 1);
  32620. }
  32621. }else{
  32622. rc = sqlite3JournalCreate(pPager->jfd);
  32623. }
  32624. if( !useAtomicWrite && rc==SQLITE_OK )
  32625. #endif
  32626. /* If a master journal file name has already been written to the
  32627. ** journal file, then no sync is required. This happens when it is
  32628. ** written, then the process fails to upgrade from a RESERVED to an
  32629. ** EXCLUSIVE lock. The next time the process tries to commit the
  32630. ** transaction the m-j name will have already been written.
  32631. */
  32632. if( !pPager->setMaster ){
  32633. rc = pager_incr_changecounter(pPager, 0);
  32634. if( rc!=SQLITE_OK ) goto sync_exit;
  32635. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  32636. #ifndef SQLITE_OMIT_AUTOVACUUM
  32637. if( pPager->dbSize<pPager->dbOrigSize ){
  32638. /* If this transaction has made the database smaller, then all pages
  32639. ** being discarded by the truncation must be written to the journal
  32640. ** file.
  32641. */
  32642. Pgno i;
  32643. Pgno iSkip = PAGER_MJ_PGNO(pPager);
  32644. Pgno dbSize = pPager->dbSize;
  32645. pPager->dbSize = pPager->dbOrigSize;
  32646. for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
  32647. if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
  32648. rc = sqlite3PagerGet(pPager, i, &pPg);
  32649. if( rc!=SQLITE_OK ) goto sync_exit;
  32650. rc = sqlite3PagerWrite(pPg);
  32651. sqlite3PagerUnref(pPg);
  32652. if( rc!=SQLITE_OK ) goto sync_exit;
  32653. }
  32654. }
  32655. pPager->dbSize = dbSize;
  32656. }
  32657. #endif
  32658. rc = writeMasterJournal(pPager, zMaster);
  32659. if( rc!=SQLITE_OK ) goto sync_exit;
  32660. rc = syncJournal(pPager);
  32661. }
  32662. }
  32663. if( rc!=SQLITE_OK ) goto sync_exit;
  32664. /* Write all dirty pages to the database file */
  32665. pPg = sqlite3PcacheDirtyList(pPager->pPCache);
  32666. rc = pager_write_pagelist(pPg);
  32667. if( rc!=SQLITE_OK ){
  32668. assert( rc!=SQLITE_IOERR_BLOCKED );
  32669. /* The error might have left the dirty list all fouled up here,
  32670. ** but that does not matter because if the if the dirty list did
  32671. ** get corrupted, then the transaction will roll back and
  32672. ** discard the dirty list. There is an assert in
  32673. ** pager_get_all_dirty_pages() that verifies that no attempt
  32674. ** is made to use an invalid dirty list.
  32675. */
  32676. goto sync_exit;
  32677. }
  32678. sqlite3PcacheCleanAll(pPager->pPCache);
  32679. if( pPager->dbSize<pPager->dbFileSize ){
  32680. assert( pPager->state>=PAGER_EXCLUSIVE );
  32681. rc = pager_truncate(pPager, pPager->dbSize);
  32682. if( rc!=SQLITE_OK ) goto sync_exit;
  32683. }
  32684. /* Sync the database file. */
  32685. if( !pPager->noSync && !noSync ){
  32686. rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
  32687. }
  32688. IOTRACE(("DBSYNC %p\n", pPager))
  32689. pPager->state = PAGER_SYNCED;
  32690. }
  32691. sync_exit:
  32692. if( rc==SQLITE_IOERR_BLOCKED ){
  32693. /* pager_incr_changecounter() may attempt to obtain an exclusive
  32694. * lock to spill the cache and return IOERR_BLOCKED. But since
  32695. * there is no chance the cache is inconsistent, it is
  32696. * better to return SQLITE_BUSY.
  32697. */
  32698. rc = SQLITE_BUSY;
  32699. }
  32700. return rc;
  32701. }
  32702. /*
  32703. ** Commit all changes to the database and release the write lock.
  32704. **
  32705. ** If the commit fails for any reason, a rollback attempt is made
  32706. ** and an error code is returned. If the commit worked, SQLITE_OK
  32707. ** is returned.
  32708. */
  32709. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  32710. int rc = SQLITE_OK;
  32711. if( pPager->errCode ){
  32712. return pPager->errCode;
  32713. }
  32714. if( pPager->state<PAGER_RESERVED ){
  32715. return SQLITE_ERROR;
  32716. }
  32717. if( pPager->dbModified==0 &&
  32718. (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
  32719. pPager->exclusiveMode!=0) ){
  32720. assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
  32721. return SQLITE_OK;
  32722. }
  32723. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  32724. assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dirtyCache );
  32725. rc = pager_end_transaction(pPager, pPager->setMaster);
  32726. rc = pager_error(pPager, rc);
  32727. return rc;
  32728. }
  32729. /*
  32730. ** Rollback all changes. The database falls back to PAGER_SHARED mode.
  32731. ** All in-memory cache pages revert to their original data contents.
  32732. ** The journal is deleted.
  32733. **
  32734. ** This routine cannot fail unless some other process is not following
  32735. ** the correct locking protocol or unless some other
  32736. ** process is writing trash into the journal file (SQLITE_CORRUPT) or
  32737. ** unless a prior malloc() failed (SQLITE_NOMEM). Appropriate error
  32738. ** codes are returned for all these occasions. Otherwise,
  32739. ** SQLITE_OK is returned.
  32740. */
  32741. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  32742. int rc = SQLITE_OK;
  32743. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  32744. if( !pPager->dirtyCache || !pPager->journalOpen ){
  32745. rc = pager_end_transaction(pPager, pPager->setMaster);
  32746. }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
  32747. if( pPager->state>=PAGER_EXCLUSIVE ){
  32748. pager_playback(pPager, 0);
  32749. }
  32750. rc = pPager->errCode;
  32751. }else{
  32752. if( pPager->state==PAGER_RESERVED ){
  32753. int rc2;
  32754. rc = pager_playback(pPager, 0);
  32755. rc2 = pager_end_transaction(pPager, pPager->setMaster);
  32756. if( rc==SQLITE_OK ){
  32757. rc = rc2;
  32758. }
  32759. }else{
  32760. rc = pager_playback(pPager, 0);
  32761. }
  32762. if( !MEMDB ){
  32763. pPager->dbSizeValid = 0;
  32764. }
  32765. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  32766. ** cache. So call pager_error() on the way out to make any error
  32767. ** persistent.
  32768. */
  32769. rc = pager_error(pPager, rc);
  32770. }
  32771. return rc;
  32772. }
  32773. /*
  32774. ** Return TRUE if the database file is opened read-only. Return FALSE
  32775. ** if the database is (in theory) writable.
  32776. */
  32777. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  32778. return pPager->readOnly;
  32779. }
  32780. /*
  32781. ** Return the number of references to the pager.
  32782. */
  32783. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  32784. return sqlite3PcacheRefCount(pPager->pPCache);
  32785. }
  32786. /*
  32787. ** Return the number of references to the specified page.
  32788. */
  32789. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  32790. return sqlite3PcachePageRefcount(pPage);
  32791. }
  32792. #ifdef SQLITE_TEST
  32793. /*
  32794. ** This routine is used for testing and analysis only.
  32795. */
  32796. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  32797. static int a[11];
  32798. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  32799. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  32800. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  32801. a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
  32802. a[4] = pPager->state;
  32803. a[5] = pPager->errCode;
  32804. a[6] = pPager->nHit;
  32805. a[7] = pPager->nMiss;
  32806. a[8] = 0; /* Used to be pPager->nOvfl */
  32807. a[9] = pPager->nRead;
  32808. a[10] = pPager->nWrite;
  32809. return a;
  32810. }
  32811. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  32812. return MEMDB;
  32813. }
  32814. #endif
  32815. /*
  32816. ** Ensure that there are at least nSavepoint savepoints open.
  32817. */
  32818. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  32819. int rc = SQLITE_OK;
  32820. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  32821. int ii;
  32822. PagerSavepoint *aNew;
  32823. /* Either there is no active journal or the sub-journal is open or
  32824. ** the journal is always stored in memory */
  32825. assert( pPager->nSavepoint==0 || pPager->sjfd->pMethods ||
  32826. pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  32827. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  32828. ** if the allocation fails. Otherwise, zero the new portion in case a
  32829. ** malloc failure occurs while populating it in the for(...) loop below.
  32830. */
  32831. aNew = (PagerSavepoint *)sqlite3Realloc(
  32832. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  32833. );
  32834. if( !aNew ){
  32835. return SQLITE_NOMEM;
  32836. }
  32837. memset(&aNew[pPager->nSavepoint], 0,
  32838. (nSavepoint - pPager->nSavepoint) * sizeof(PagerSavepoint)
  32839. );
  32840. pPager->aSavepoint = aNew;
  32841. ii = pPager->nSavepoint;
  32842. pPager->nSavepoint = nSavepoint;
  32843. /* Populate the PagerSavepoint structures just allocated. */
  32844. for(/* no-op */; ii<nSavepoint; ii++){
  32845. assert( pPager->dbSizeValid );
  32846. aNew[ii].nOrig = pPager->dbSize;
  32847. if( pPager->journalOpen && pPager->journalOff>0 ){
  32848. aNew[ii].iOffset = pPager->journalOff;
  32849. }else{
  32850. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  32851. }
  32852. aNew[ii].iSubRec = pPager->stmtNRec;
  32853. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  32854. if( !aNew[ii].pInSavepoint ){
  32855. return SQLITE_NOMEM;
  32856. }
  32857. }
  32858. /* Open the sub-journal, if it is not already opened. */
  32859. rc = openSubJournal(pPager);
  32860. }
  32861. return rc;
  32862. }
  32863. /*
  32864. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  32865. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  32866. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  32867. ** that have occured since savepoint iSavepoint was created.
  32868. **
  32869. ** In either case, all savepoints with an index greater than iSavepoint
  32870. ** are destroyed.
  32871. **
  32872. ** If there are less than (iSavepoint+1) active savepoints when this
  32873. ** function is called it is a no-op.
  32874. */
  32875. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  32876. int rc = SQLITE_OK;
  32877. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  32878. if( iSavepoint<pPager->nSavepoint ){
  32879. int ii;
  32880. int nNew = iSavepoint + (op==SAVEPOINT_ROLLBACK);
  32881. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  32882. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  32883. }
  32884. pPager->nSavepoint = nNew;
  32885. if( op==SAVEPOINT_ROLLBACK && pPager->jfd->pMethods ){
  32886. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  32887. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  32888. assert(rc!=SQLITE_DONE);
  32889. }
  32890. /* If this is a release of the outermost savepoint, truncate
  32891. ** the sub-journal. */
  32892. if( nNew==0 && op==SAVEPOINT_RELEASE && pPager->sjfd->pMethods ){
  32893. assert( rc==SQLITE_OK );
  32894. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  32895. pPager->stmtNRec = 0;
  32896. }
  32897. }
  32898. return rc;
  32899. }
  32900. /*
  32901. ** Return the full pathname of the database file.
  32902. */
  32903. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
  32904. return pPager->zFilename;
  32905. }
  32906. /*
  32907. ** Return the VFS structure for the pager.
  32908. */
  32909. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  32910. return pPager->pVfs;
  32911. }
  32912. /*
  32913. ** Return the file handle for the database file associated
  32914. ** with the pager. This might return NULL if the file has
  32915. ** not yet been opened.
  32916. */
  32917. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  32918. return pPager->fd;
  32919. }
  32920. /*
  32921. ** Return the directory of the database file.
  32922. */
  32923. SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager *pPager){
  32924. return pPager->zDirectory;
  32925. }
  32926. /*
  32927. ** Return the full pathname of the journal file.
  32928. */
  32929. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  32930. return pPager->zJournal;
  32931. }
  32932. /*
  32933. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  32934. ** if fsync()s are executed normally.
  32935. */
  32936. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  32937. return pPager->noSync;
  32938. }
  32939. #ifdef SQLITE_HAS_CODEC
  32940. /*
  32941. ** Set the codec for this pager
  32942. */
  32943. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  32944. Pager *pPager,
  32945. void *(*xCodec)(void*,void*,Pgno,int),
  32946. void *pCodecArg
  32947. ){
  32948. pPager->xCodec = xCodec;
  32949. pPager->pCodecArg = pCodecArg;
  32950. }
  32951. #endif
  32952. #ifndef SQLITE_OMIT_AUTOVACUUM
  32953. /*
  32954. ** Move the page pPg to location pgno in the file.
  32955. **
  32956. ** There must be no references to the page previously located at
  32957. ** pgno (which we call pPgOld) though that page is allowed to be
  32958. ** in cache. If the page previously located at pgno is not already
  32959. ** in the rollback journal, it is not put there by by this routine.
  32960. **
  32961. ** References to the page pPg remain valid. Updating any
  32962. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  32963. ** allocated along with the page) is the responsibility of the caller.
  32964. **
  32965. ** A transaction must be active when this routine is called. It used to be
  32966. ** required that a statement transaction was not active, but this restriction
  32967. ** has been removed (CREATE INDEX needs to move a page when a statement
  32968. ** transaction is active).
  32969. **
  32970. ** If the fourth argument, isCommit, is non-zero, then this page is being
  32971. ** moved as part of a database reorganization just before the transaction
  32972. ** is being committed. In this case, it is guaranteed that the database page
  32973. ** pPg refers to will not be written to again within this transaction.
  32974. */
  32975. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  32976. PgHdr *pPgOld; /* The page being overwritten. */
  32977. Pgno needSyncPgno = 0;
  32978. int rc;
  32979. assert( pPg->nRef>0 );
  32980. /* If the page being moved is dirty and has not been saved by the latest
  32981. ** savepoint, then save the current contents of the page into the
  32982. ** sub-journal now. This is required to handle the following scenario:
  32983. **
  32984. ** BEGIN;
  32985. ** <journal page X, then modify it in memory>
  32986. ** SAVEPOINT one;
  32987. ** <Move page X to location Y>
  32988. ** ROLLBACK TO one;
  32989. **
  32990. ** If page X were not written to the sub-journal here, it would not
  32991. ** be possible to restore its contents when the "ROLLBACK TO one"
  32992. ** statement were processed.
  32993. */
  32994. if( pPg->flags&PGHDR_DIRTY
  32995. && subjRequiresPage(pPg)
  32996. && SQLITE_OK!=(rc = subjournalPage(pPg))
  32997. ){
  32998. return rc;
  32999. }
  33000. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  33001. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  33002. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  33003. pager_get_content(pPg);
  33004. /* If the journal needs to be sync()ed before page pPg->pgno can
  33005. ** be written to, store pPg->pgno in local variable needSyncPgno.
  33006. **
  33007. ** If the isCommit flag is set, there is no need to remember that
  33008. ** the journal needs to be sync()ed before database page pPg->pgno
  33009. ** can be written to. The caller has already promised not to write to it.
  33010. */
  33011. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  33012. needSyncPgno = pPg->pgno;
  33013. assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  33014. assert( pPg->flags&PGHDR_DIRTY );
  33015. assert( pPager->needSync );
  33016. }
  33017. /* If the cache contains a page with page-number pgno, remove it
  33018. ** from its hash chain. Also, if the PgHdr.needSync was set for
  33019. ** page pgno before the 'move' operation, it needs to be retained
  33020. ** for the page moved there.
  33021. */
  33022. pPg->flags &= ~PGHDR_NEED_SYNC;
  33023. pPgOld = pager_lookup(pPager, pgno);
  33024. assert( !pPgOld || pPgOld->nRef==1 );
  33025. if( pPgOld ){
  33026. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  33027. }
  33028. sqlite3PcacheMove(pPg, pgno);
  33029. if( pPgOld ){
  33030. sqlite3PcacheDrop(pPgOld);
  33031. }
  33032. sqlite3PcacheMakeDirty(pPg);
  33033. pPager->dirtyCache = 1;
  33034. pPager->dbModified = 1;
  33035. if( needSyncPgno ){
  33036. /* If needSyncPgno is non-zero, then the journal file needs to be
  33037. ** sync()ed before any data is written to database file page needSyncPgno.
  33038. ** Currently, no such page exists in the page-cache and the
  33039. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  33040. ** loading the page into the pager-cache and setting the PgHdr.needSync
  33041. ** flag.
  33042. **
  33043. ** If the attempt to load the page into the page-cache fails, (due
  33044. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  33045. ** array. Otherwise, if the page is loaded and written again in
  33046. ** this transaction, it may be written to the database file before
  33047. ** it is synced into the journal file. This way, it may end up in
  33048. ** the journal file twice, but that is not a problem.
  33049. **
  33050. ** The sqlite3PagerGet() call may cause the journal to sync. So make
  33051. ** sure the Pager.needSync flag is set too.
  33052. */
  33053. PgHdr *pPgHdr;
  33054. assert( pPager->needSync );
  33055. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  33056. if( rc!=SQLITE_OK ){
  33057. if( pPager->pInJournal && needSyncPgno<=pPager->dbOrigSize ){
  33058. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno);
  33059. }
  33060. return rc;
  33061. }
  33062. pPager->needSync = 1;
  33063. assert( pPager->noSync==0 && !MEMDB );
  33064. pPgHdr->flags |= PGHDR_NEED_SYNC;
  33065. sqlite3PcacheMakeDirty(pPgHdr);
  33066. sqlite3PagerUnref(pPgHdr);
  33067. }
  33068. return SQLITE_OK;
  33069. }
  33070. #endif
  33071. /*
  33072. ** Return a pointer to the data for the specified page.
  33073. */
  33074. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  33075. assert( pPg->nRef>0 || pPg->pPager->memDb );
  33076. return pPg->pData;
  33077. }
  33078. /*
  33079. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  33080. ** allocated along with the specified page.
  33081. */
  33082. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  33083. Pager *pPager = pPg->pPager;
  33084. return (pPager?pPg->pExtra:0);
  33085. }
  33086. /*
  33087. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  33088. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  33089. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  33090. ** the locking-mode is set to the value specified.
  33091. **
  33092. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  33093. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  33094. ** locking-mode.
  33095. */
  33096. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  33097. assert( eMode==PAGER_LOCKINGMODE_QUERY
  33098. || eMode==PAGER_LOCKINGMODE_NORMAL
  33099. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  33100. assert( PAGER_LOCKINGMODE_QUERY<0 );
  33101. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  33102. if( eMode>=0 && !pPager->tempFile ){
  33103. pPager->exclusiveMode = (u8)eMode;
  33104. }
  33105. return (int)pPager->exclusiveMode;
  33106. }
  33107. /*
  33108. ** Get/set the journal-mode for this pager. Parameter eMode must be one of:
  33109. **
  33110. ** PAGER_JOURNALMODE_QUERY
  33111. ** PAGER_JOURNALMODE_DELETE
  33112. ** PAGER_JOURNALMODE_TRUNCATE
  33113. ** PAGER_JOURNALMODE_PERSIST
  33114. ** PAGER_JOURNALMODE_OFF
  33115. **
  33116. ** If the parameter is not _QUERY, then the journal-mode is set to the
  33117. ** value specified.
  33118. **
  33119. ** The returned indicate the current (possibly updated)
  33120. ** journal-mode.
  33121. */
  33122. SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
  33123. if( !MEMDB ){
  33124. assert( eMode==PAGER_JOURNALMODE_QUERY
  33125. || eMode==PAGER_JOURNALMODE_DELETE
  33126. || eMode==PAGER_JOURNALMODE_TRUNCATE
  33127. || eMode==PAGER_JOURNALMODE_PERSIST
  33128. || eMode==PAGER_JOURNALMODE_OFF
  33129. || eMode==PAGER_JOURNALMODE_MEMORY );
  33130. assert( PAGER_JOURNALMODE_QUERY<0 );
  33131. if( eMode>=0 ){
  33132. pPager->journalMode = (u8)eMode;
  33133. }else{
  33134. assert( eMode==PAGER_JOURNALMODE_QUERY );
  33135. }
  33136. }
  33137. return (int)pPager->journalMode;
  33138. }
  33139. /*
  33140. ** Get/set the size-limit used for persistent journal files.
  33141. */
  33142. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  33143. if( iLimit>=-1 ){
  33144. pPager->journalSizeLimit = iLimit;
  33145. }
  33146. return pPager->journalSizeLimit;
  33147. }
  33148. #endif /* SQLITE_OMIT_DISKIO */
  33149. /************** End of pager.c ***********************************************/
  33150. /************** Begin file btmutex.c *****************************************/
  33151. /*
  33152. ** 2007 August 27
  33153. **
  33154. ** The author disclaims copyright to this source code. In place of
  33155. ** a legal notice, here is a blessing:
  33156. **
  33157. ** May you do good and not evil.
  33158. ** May you find forgiveness for yourself and forgive others.
  33159. ** May you share freely, never taking more than you give.
  33160. **
  33161. *************************************************************************
  33162. **
  33163. ** $Id: btmutex.c,v 1.12 2008/11/17 19:18:55 danielk1977 Exp $
  33164. **
  33165. ** This file contains code used to implement mutexes on Btree objects.
  33166. ** This code really belongs in btree.c. But btree.c is getting too
  33167. ** big and we want to break it down some. This packaged seemed like
  33168. ** a good breakout.
  33169. */
  33170. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  33171. /************** Begin file btreeInt.h ****************************************/
  33172. /*
  33173. ** 2004 April 6
  33174. **
  33175. ** The author disclaims copyright to this source code. In place of
  33176. ** a legal notice, here is a blessing:
  33177. **
  33178. ** May you do good and not evil.
  33179. ** May you find forgiveness for yourself and forgive others.
  33180. ** May you share freely, never taking more than you give.
  33181. **
  33182. *************************************************************************
  33183. ** $Id: btreeInt.h,v 1.38 2008/12/27 15:23:13 danielk1977 Exp $
  33184. **
  33185. ** This file implements a external (disk-based) database using BTrees.
  33186. ** For a detailed discussion of BTrees, refer to
  33187. **
  33188. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  33189. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  33190. ** Publishing Company, Reading, Massachusetts.
  33191. **
  33192. ** The basic idea is that each page of the file contains N database
  33193. ** entries and N+1 pointers to subpages.
  33194. **
  33195. ** ----------------------------------------------------------------
  33196. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  33197. ** ----------------------------------------------------------------
  33198. **
  33199. ** All of the keys on the page that Ptr(0) points to have values less
  33200. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  33201. ** values greater than Key(0) and less than Key(1). All of the keys
  33202. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  33203. ** so forth.
  33204. **
  33205. ** Finding a particular key requires reading O(log(M)) pages from the
  33206. ** disk where M is the number of entries in the tree.
  33207. **
  33208. ** In this implementation, a single file can hold one or more separate
  33209. ** BTrees. Each BTree is identified by the index of its root page. The
  33210. ** key and data for any entry are combined to form the "payload". A
  33211. ** fixed amount of payload can be carried directly on the database
  33212. ** page. If the payload is larger than the preset amount then surplus
  33213. ** bytes are stored on overflow pages. The payload for an entry
  33214. ** and the preceding pointer are combined to form a "Cell". Each
  33215. ** page has a small header which contains the Ptr(N) pointer and other
  33216. ** information such as the size of key and data.
  33217. **
  33218. ** FORMAT DETAILS
  33219. **
  33220. ** The file is divided into pages. The first page is called page 1,
  33221. ** the second is page 2, and so forth. A page number of zero indicates
  33222. ** "no such page". The page size can be anything between 512 and 65536.
  33223. ** Each page can be either a btree page, a freelist page or an overflow
  33224. ** page.
  33225. **
  33226. ** The first page is always a btree page. The first 100 bytes of the first
  33227. ** page contain a special header (the "file header") that describes the file.
  33228. ** The format of the file header is as follows:
  33229. **
  33230. ** OFFSET SIZE DESCRIPTION
  33231. ** 0 16 Header string: "SQLite format 3\000"
  33232. ** 16 2 Page size in bytes.
  33233. ** 18 1 File format write version
  33234. ** 19 1 File format read version
  33235. ** 20 1 Bytes of unused space at the end of each page
  33236. ** 21 1 Max embedded payload fraction
  33237. ** 22 1 Min embedded payload fraction
  33238. ** 23 1 Min leaf payload fraction
  33239. ** 24 4 File change counter
  33240. ** 28 4 Reserved for future use
  33241. ** 32 4 First freelist page
  33242. ** 36 4 Number of freelist pages in the file
  33243. ** 40 60 15 4-byte meta values passed to higher layers
  33244. **
  33245. ** All of the integer values are big-endian (most significant byte first).
  33246. **
  33247. ** The file change counter is incremented when the database is changed
  33248. ** This counter allows other processes to know when the file has changed
  33249. ** and thus when they need to flush their cache.
  33250. **
  33251. ** The max embedded payload fraction is the amount of the total usable
  33252. ** space in a page that can be consumed by a single cell for standard
  33253. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  33254. ** is to limit the maximum cell size so that at least 4 cells will fit
  33255. ** on one page. Thus the default max embedded payload fraction is 64.
  33256. **
  33257. ** If the payload for a cell is larger than the max payload, then extra
  33258. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  33259. ** as many bytes as possible are moved into the overflow pages without letting
  33260. ** the cell size drop below the min embedded payload fraction.
  33261. **
  33262. ** The min leaf payload fraction is like the min embedded payload fraction
  33263. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  33264. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  33265. ** not specified in the header.
  33266. **
  33267. ** Each btree pages is divided into three sections: The header, the
  33268. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  33269. ** file header that occurs before the page header.
  33270. **
  33271. ** |----------------|
  33272. ** | file header | 100 bytes. Page 1 only.
  33273. ** |----------------|
  33274. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  33275. ** |----------------|
  33276. ** | cell pointer | | 2 bytes per cell. Sorted order.
  33277. ** | array | | Grows downward
  33278. ** | | v
  33279. ** |----------------|
  33280. ** | unallocated |
  33281. ** | space |
  33282. ** |----------------| ^ Grows upwards
  33283. ** | cell content | | Arbitrary order interspersed with freeblocks.
  33284. ** | area | | and free space fragments.
  33285. ** |----------------|
  33286. **
  33287. ** The page headers looks like this:
  33288. **
  33289. ** OFFSET SIZE DESCRIPTION
  33290. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  33291. ** 1 2 byte offset to the first freeblock
  33292. ** 3 2 number of cells on this page
  33293. ** 5 2 first byte of the cell content area
  33294. ** 7 1 number of fragmented free bytes
  33295. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  33296. **
  33297. ** The flags define the format of this btree page. The leaf flag means that
  33298. ** this page has no children. The zerodata flag means that this page carries
  33299. ** only keys and no data. The intkey flag means that the key is a integer
  33300. ** which is stored in the key size entry of the cell header rather than in
  33301. ** the payload area.
  33302. **
  33303. ** The cell pointer array begins on the first byte after the page header.
  33304. ** The cell pointer array contains zero or more 2-byte numbers which are
  33305. ** offsets from the beginning of the page to the cell content in the cell
  33306. ** content area. The cell pointers occur in sorted order. The system strives
  33307. ** to keep free space after the last cell pointer so that new cells can
  33308. ** be easily added without having to defragment the page.
  33309. **
  33310. ** Cell content is stored at the very end of the page and grows toward the
  33311. ** beginning of the page.
  33312. **
  33313. ** Unused space within the cell content area is collected into a linked list of
  33314. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  33315. ** to the first freeblock is given in the header. Freeblocks occur in
  33316. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  33317. ** any group of 3 or fewer unused bytes in the cell content area cannot
  33318. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  33319. ** a fragment. The total number of bytes in all fragments is recorded.
  33320. ** in the page header at offset 7.
  33321. **
  33322. ** SIZE DESCRIPTION
  33323. ** 2 Byte offset of the next freeblock
  33324. ** 2 Bytes in this freeblock
  33325. **
  33326. ** Cells are of variable length. Cells are stored in the cell content area at
  33327. ** the end of the page. Pointers to the cells are in the cell pointer array
  33328. ** that immediately follows the page header. Cells is not necessarily
  33329. ** contiguous or in order, but cell pointers are contiguous and in order.
  33330. **
  33331. ** Cell content makes use of variable length integers. A variable
  33332. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  33333. ** byte are used. The integer consists of all bytes that have bit 8 set and
  33334. ** the first byte with bit 8 clear. The most significant byte of the integer
  33335. ** appears first. A variable-length integer may not be more than 9 bytes long.
  33336. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  33337. ** allows a 64-bit integer to be encoded in 9 bytes.
  33338. **
  33339. ** 0x00 becomes 0x00000000
  33340. ** 0x7f becomes 0x0000007f
  33341. ** 0x81 0x00 becomes 0x00000080
  33342. ** 0x82 0x00 becomes 0x00000100
  33343. ** 0x80 0x7f becomes 0x0000007f
  33344. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  33345. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  33346. **
  33347. ** Variable length integers are used for rowids and to hold the number of
  33348. ** bytes of key and data in a btree cell.
  33349. **
  33350. ** The content of a cell looks like this:
  33351. **
  33352. ** SIZE DESCRIPTION
  33353. ** 4 Page number of the left child. Omitted if leaf flag is set.
  33354. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  33355. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  33356. ** * Payload
  33357. ** 4 First page of the overflow chain. Omitted if no overflow
  33358. **
  33359. ** Overflow pages form a linked list. Each page except the last is completely
  33360. ** filled with data (pagesize - 4 bytes). The last page can have as little
  33361. ** as 1 byte of data.
  33362. **
  33363. ** SIZE DESCRIPTION
  33364. ** 4 Page number of next overflow page
  33365. ** * Data
  33366. **
  33367. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  33368. ** file header points to the first in a linked list of trunk page. Each trunk
  33369. ** page points to multiple leaf pages. The content of a leaf page is
  33370. ** unspecified. A trunk page looks like this:
  33371. **
  33372. ** SIZE DESCRIPTION
  33373. ** 4 Page number of next trunk page
  33374. ** 4 Number of leaf pointers on this page
  33375. ** * zero or more pages numbers of leaves
  33376. */
  33377. /* Round up a number to the next larger multiple of 8. This is used
  33378. ** to force 8-byte alignment on 64-bit architectures.
  33379. */
  33380. #define ROUND8(x) ((x+7)&~7)
  33381. /* The following value is the maximum cell size assuming a maximum page
  33382. ** size give above.
  33383. */
  33384. #define MX_CELL_SIZE(pBt) (pBt->pageSize-8)
  33385. /* The maximum number of cells on a single page of the database. This
  33386. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  33387. ** plus 2 bytes for the index to the cell in the page header). Such
  33388. ** small cells will be rare, but they are possible.
  33389. */
  33390. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  33391. /* Forward declarations */
  33392. typedef struct MemPage MemPage;
  33393. typedef struct BtLock BtLock;
  33394. /*
  33395. ** This is a magic string that appears at the beginning of every
  33396. ** SQLite database in order to identify the file as a real database.
  33397. **
  33398. ** You can change this value at compile-time by specifying a
  33399. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  33400. ** header must be exactly 16 bytes including the zero-terminator so
  33401. ** the string itself should be 15 characters long. If you change
  33402. ** the header, then your custom library will not be able to read
  33403. ** databases generated by the standard tools and the standard tools
  33404. ** will not be able to read databases created by your custom library.
  33405. */
  33406. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  33407. # define SQLITE_FILE_HEADER "SQLite format 3"
  33408. #endif
  33409. /*
  33410. ** Page type flags. An ORed combination of these flags appear as the
  33411. ** first byte of on-disk image of every BTree page.
  33412. */
  33413. #define PTF_INTKEY 0x01
  33414. #define PTF_ZERODATA 0x02
  33415. #define PTF_LEAFDATA 0x04
  33416. #define PTF_LEAF 0x08
  33417. /*
  33418. ** As each page of the file is loaded into memory, an instance of the following
  33419. ** structure is appended and initialized to zero. This structure stores
  33420. ** information about the page that is decoded from the raw file page.
  33421. **
  33422. ** The pParent field points back to the parent page. This allows us to
  33423. ** walk up the BTree from any leaf to the root. Care must be taken to
  33424. ** unref() the parent page pointer when this page is no longer referenced.
  33425. ** The pageDestructor() routine handles that chore.
  33426. **
  33427. ** Access to all fields of this structure is controlled by the mutex
  33428. ** stored in MemPage.pBt->mutex.
  33429. */
  33430. struct MemPage {
  33431. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  33432. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  33433. u8 intKey; /* True if intkey flag is set */
  33434. u8 leaf; /* True if leaf flag is set */
  33435. u8 hasData; /* True if this page stores data */
  33436. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  33437. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  33438. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  33439. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  33440. u16 cellOffset; /* Index in aData of first cell pointer */
  33441. u16 nFree; /* Number of free bytes on the page */
  33442. u16 nCell; /* Number of cells on this page, local and ovfl */
  33443. u16 maskPage; /* Mask for page offset */
  33444. struct _OvflCell { /* Cells that will not fit on aData[] */
  33445. u8 *pCell; /* Pointers to the body of the overflow cell */
  33446. u16 idx; /* Insert this cell before idx-th non-overflow cell */
  33447. } aOvfl[5];
  33448. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  33449. u8 *aData; /* Pointer to disk image of the page data */
  33450. DbPage *pDbPage; /* Pager page handle */
  33451. Pgno pgno; /* Page number for this page */
  33452. };
  33453. /*
  33454. ** The in-memory image of a disk page has the auxiliary information appended
  33455. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  33456. ** that extra information.
  33457. */
  33458. #define EXTRA_SIZE sizeof(MemPage)
  33459. /* A Btree handle
  33460. **
  33461. ** A database connection contains a pointer to an instance of
  33462. ** this object for every database file that it has open. This structure
  33463. ** is opaque to the database connection. The database connection cannot
  33464. ** see the internals of this structure and only deals with pointers to
  33465. ** this structure.
  33466. **
  33467. ** For some database files, the same underlying database cache might be
  33468. ** shared between multiple connections. In that case, each contection
  33469. ** has it own pointer to this object. But each instance of this object
  33470. ** points to the same BtShared object. The database cache and the
  33471. ** schema associated with the database file are all contained within
  33472. ** the BtShared object.
  33473. **
  33474. ** All fields in this structure are accessed under sqlite3.mutex.
  33475. ** The pBt pointer itself may not be changed while there exists cursors
  33476. ** in the referenced BtShared that point back to this Btree since those
  33477. ** cursors have to do go through this Btree to find their BtShared and
  33478. ** they often do so without holding sqlite3.mutex.
  33479. */
  33480. struct Btree {
  33481. sqlite3 *db; /* The database connection holding this btree */
  33482. BtShared *pBt; /* Sharable content of this btree */
  33483. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  33484. u8 sharable; /* True if we can share pBt with another db */
  33485. u8 locked; /* True if db currently has pBt locked */
  33486. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  33487. Btree *pNext; /* List of other sharable Btrees from the same db */
  33488. Btree *pPrev; /* Back pointer of the same list */
  33489. };
  33490. /*
  33491. ** Btree.inTrans may take one of the following values.
  33492. **
  33493. ** If the shared-data extension is enabled, there may be multiple users
  33494. ** of the Btree structure. At most one of these may open a write transaction,
  33495. ** but any number may have active read transactions.
  33496. */
  33497. #define TRANS_NONE 0
  33498. #define TRANS_READ 1
  33499. #define TRANS_WRITE 2
  33500. /*
  33501. ** An instance of this object represents a single database file.
  33502. **
  33503. ** A single database file can be in use as the same time by two
  33504. ** or more database connections. When two or more connections are
  33505. ** sharing the same database file, each connection has it own
  33506. ** private Btree object for the file and each of those Btrees points
  33507. ** to this one BtShared object. BtShared.nRef is the number of
  33508. ** connections currently sharing this database file.
  33509. **
  33510. ** Fields in this structure are accessed under the BtShared.mutex
  33511. ** mutex, except for nRef and pNext which are accessed under the
  33512. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  33513. ** may not be modified once it is initially set as long as nRef>0.
  33514. ** The pSchema field may be set once under BtShared.mutex and
  33515. ** thereafter is unchanged as long as nRef>0.
  33516. */
  33517. struct BtShared {
  33518. Pager *pPager; /* The page cache */
  33519. sqlite3 *db; /* Database connection currently using this Btree */
  33520. BtCursor *pCursor; /* A list of all open cursors */
  33521. MemPage *pPage1; /* First page of the database */
  33522. u8 inStmt; /* True if we are in a statement subtransaction */
  33523. u8 readOnly; /* True if the underlying file is readonly */
  33524. u8 pageSizeFixed; /* True if the page size can no longer be changed */
  33525. #ifndef SQLITE_OMIT_AUTOVACUUM
  33526. u8 autoVacuum; /* True if auto-vacuum is enabled */
  33527. u8 incrVacuum; /* True if incr-vacuum is enabled */
  33528. #endif
  33529. u16 pageSize; /* Total number of bytes on a page */
  33530. u16 usableSize; /* Number of usable bytes on each page */
  33531. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  33532. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  33533. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  33534. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  33535. u8 inTransaction; /* Transaction state */
  33536. int nTransaction; /* Number of open transactions (read + write) */
  33537. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  33538. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  33539. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
  33540. #ifndef SQLITE_OMIT_SHARED_CACHE
  33541. int nRef; /* Number of references to this structure */
  33542. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  33543. BtLock *pLock; /* List of locks held on this shared-btree struct */
  33544. Btree *pExclusive; /* Btree with an EXCLUSIVE lock on the whole db */
  33545. #endif
  33546. u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
  33547. };
  33548. /*
  33549. ** An instance of the following structure is used to hold information
  33550. ** about a cell. The parseCellPtr() function fills in this structure
  33551. ** based on information extract from the raw disk page.
  33552. */
  33553. typedef struct CellInfo CellInfo;
  33554. struct CellInfo {
  33555. u8 *pCell; /* Pointer to the start of cell content */
  33556. i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
  33557. u32 nData; /* Number of bytes of data */
  33558. u32 nPayload; /* Total amount of payload */
  33559. u16 nHeader; /* Size of the cell content header in bytes */
  33560. u16 nLocal; /* Amount of payload held locally */
  33561. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  33562. u16 nSize; /* Size of the cell content on the main b-tree page */
  33563. };
  33564. /*
  33565. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  33566. ** this will be declared corrupt. This value is calculated based on a
  33567. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  33568. ** root-node and 3 for all other internal nodes.
  33569. **
  33570. ** If a tree that appears to be taller than this is encountered, it is
  33571. ** assumed that the database is corrupt.
  33572. */
  33573. #define BTCURSOR_MAX_DEPTH 20
  33574. /*
  33575. ** A cursor is a pointer to a particular entry within a particular
  33576. ** b-tree within a database file.
  33577. **
  33578. ** The entry is identified by its MemPage and the index in
  33579. ** MemPage.aCell[] of the entry.
  33580. **
  33581. ** When a single database file can shared by two more database connections,
  33582. ** but cursors cannot be shared. Each cursor is associated with a
  33583. ** particular database connection identified BtCursor.pBtree.db.
  33584. **
  33585. ** Fields in this structure are accessed under the BtShared.mutex
  33586. ** found at self->pBt->mutex.
  33587. */
  33588. struct BtCursor {
  33589. Btree *pBtree; /* The Btree to which this cursor belongs */
  33590. BtShared *pBt; /* The BtShared this cursor points to */
  33591. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  33592. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  33593. Pgno pgnoRoot; /* The root page of this tree */
  33594. CellInfo info; /* A parse of the cell we are pointing at */
  33595. u8 wrFlag; /* True if writable */
  33596. u8 atLast; /* Cursor pointing to the last entry */
  33597. u8 validNKey; /* True if info.nKey is valid */
  33598. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  33599. void *pKey; /* Saved key that was cursor's last known position */
  33600. i64 nKey; /* Size of pKey, or last integer key */
  33601. int skip; /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
  33602. #ifndef SQLITE_OMIT_INCRBLOB
  33603. u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
  33604. Pgno *aOverflow; /* Cache of overflow page locations */
  33605. #endif
  33606. #ifndef NDEBUG
  33607. u8 pagesShuffled; /* True if Btree pages are rearranged by balance()*/
  33608. #endif
  33609. i16 iPage; /* Index of current page in apPage */
  33610. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  33611. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  33612. };
  33613. /*
  33614. ** Potential values for BtCursor.eState.
  33615. **
  33616. ** CURSOR_VALID:
  33617. ** Cursor points to a valid entry. getPayload() etc. may be called.
  33618. **
  33619. ** CURSOR_INVALID:
  33620. ** Cursor does not point to a valid entry. This can happen (for example)
  33621. ** because the table is empty or because BtreeCursorFirst() has not been
  33622. ** called.
  33623. **
  33624. ** CURSOR_REQUIRESEEK:
  33625. ** The table that this cursor was opened on still exists, but has been
  33626. ** modified since the cursor was last used. The cursor position is saved
  33627. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  33628. ** this state, restoreCursorPosition() can be called to attempt to
  33629. ** seek the cursor to the saved position.
  33630. **
  33631. ** CURSOR_FAULT:
  33632. ** A unrecoverable error (an I/O error or a malloc failure) has occurred
  33633. ** on a different connection that shares the BtShared cache with this
  33634. ** cursor. The error has left the cache in an inconsistent state.
  33635. ** Do nothing else with this cursor. Any attempt to use the cursor
  33636. ** should return the error code stored in BtCursor.skip
  33637. */
  33638. #define CURSOR_INVALID 0
  33639. #define CURSOR_VALID 1
  33640. #define CURSOR_REQUIRESEEK 2
  33641. #define CURSOR_FAULT 3
  33642. /* The database page the PENDING_BYTE occupies. This page is never used.
  33643. ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
  33644. ** should possibly be consolidated (presumably in pager.h).
  33645. **
  33646. ** If disk I/O is omitted (meaning that the database is stored purely
  33647. ** in memory) then there is no pending byte.
  33648. */
  33649. #ifdef SQLITE_OMIT_DISKIO
  33650. # define PENDING_BYTE_PAGE(pBt) 0x7fffffff
  33651. #else
  33652. # define PENDING_BYTE_PAGE(pBt) ((Pgno)((PENDING_BYTE/(pBt)->pageSize)+1))
  33653. #endif
  33654. /*
  33655. ** A linked list of the following structures is stored at BtShared.pLock.
  33656. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  33657. ** is opened on the table with root page BtShared.iTable. Locks are removed
  33658. ** from this list when a transaction is committed or rolled back, or when
  33659. ** a btree handle is closed.
  33660. */
  33661. struct BtLock {
  33662. Btree *pBtree; /* Btree handle holding this lock */
  33663. Pgno iTable; /* Root page of table */
  33664. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  33665. BtLock *pNext; /* Next in BtShared.pLock list */
  33666. };
  33667. /* Candidate values for BtLock.eLock */
  33668. #define READ_LOCK 1
  33669. #define WRITE_LOCK 2
  33670. /*
  33671. ** These macros define the location of the pointer-map entry for a
  33672. ** database page. The first argument to each is the number of usable
  33673. ** bytes on each page of the database (often 1024). The second is the
  33674. ** page number to look up in the pointer map.
  33675. **
  33676. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  33677. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  33678. ** the offset of the requested map entry.
  33679. **
  33680. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  33681. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  33682. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  33683. ** this test.
  33684. */
  33685. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  33686. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  33687. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  33688. /*
  33689. ** The pointer map is a lookup table that identifies the parent page for
  33690. ** each child page in the database file. The parent page is the page that
  33691. ** contains a pointer to the child. Every page in the database contains
  33692. ** 0 or 1 parent pages. (In this context 'database page' refers
  33693. ** to any page that is not part of the pointer map itself.) Each pointer map
  33694. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  33695. ** The PTRMAP_XXX identifiers below are the valid types.
  33696. **
  33697. ** The purpose of the pointer map is to facility moving pages from one
  33698. ** position in the file to another as part of autovacuum. When a page
  33699. ** is moved, the pointer in its parent must be updated to point to the
  33700. ** new location. The pointer map is used to locate the parent page quickly.
  33701. **
  33702. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  33703. ** used in this case.
  33704. **
  33705. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  33706. ** is not used in this case.
  33707. **
  33708. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  33709. ** overflow pages. The page number identifies the page that
  33710. ** contains the cell with a pointer to this overflow page.
  33711. **
  33712. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  33713. ** overflow pages. The page-number identifies the previous
  33714. ** page in the overflow page list.
  33715. **
  33716. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  33717. ** identifies the parent page in the btree.
  33718. */
  33719. #define PTRMAP_ROOTPAGE 1
  33720. #define PTRMAP_FREEPAGE 2
  33721. #define PTRMAP_OVERFLOW1 3
  33722. #define PTRMAP_OVERFLOW2 4
  33723. #define PTRMAP_BTREE 5
  33724. /* A bunch of assert() statements to check the transaction state variables
  33725. ** of handle p (type Btree*) are internally consistent.
  33726. */
  33727. #define btreeIntegrity(p) \
  33728. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  33729. assert( p->pBt->inTransaction>=p->inTrans );
  33730. /*
  33731. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  33732. ** if the database supports auto-vacuum or not. Because it is used
  33733. ** within an expression that is an argument to another macro
  33734. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  33735. ** So, this macro is defined instead.
  33736. */
  33737. #ifndef SQLITE_OMIT_AUTOVACUUM
  33738. #define ISAUTOVACUUM (pBt->autoVacuum)
  33739. #else
  33740. #define ISAUTOVACUUM 0
  33741. #endif
  33742. /*
  33743. ** This structure is passed around through all the sanity checking routines
  33744. ** in order to keep track of some global state information.
  33745. */
  33746. typedef struct IntegrityCk IntegrityCk;
  33747. struct IntegrityCk {
  33748. BtShared *pBt; /* The tree being checked out */
  33749. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  33750. Pgno nPage; /* Number of pages in the database */
  33751. int *anRef; /* Number of times each page is referenced */
  33752. int mxErr; /* Stop accumulating errors when this reaches zero */
  33753. int nErr; /* Number of messages written to zErrMsg so far */
  33754. int mallocFailed; /* A memory allocation error has occurred */
  33755. StrAccum errMsg; /* Accumulate the error message text here */
  33756. };
  33757. /*
  33758. ** Read or write a two- and four-byte big-endian integer values.
  33759. */
  33760. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  33761. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  33762. #define get4byte sqlite3Get4byte
  33763. #define put4byte sqlite3Put4byte
  33764. /*
  33765. ** Internal routines that should be accessed by the btree layer only.
  33766. */
  33767. SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
  33768. SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage);
  33769. SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
  33770. SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
  33771. SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur);
  33772. SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
  33773. SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
  33774. SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);
  33775. /************** End of btreeInt.h ********************************************/
  33776. /************** Continuing where we left off in btmutex.c ********************/
  33777. #if SQLITE_THREADSAFE && !defined(SQLITE_OMIT_SHARED_CACHE)
  33778. /*
  33779. ** Enter a mutex on the given BTree object.
  33780. **
  33781. ** If the object is not sharable, then no mutex is ever required
  33782. ** and this routine is a no-op. The underlying mutex is non-recursive.
  33783. ** But we keep a reference count in Btree.wantToLock so the behavior
  33784. ** of this interface is recursive.
  33785. **
  33786. ** To avoid deadlocks, multiple Btrees are locked in the same order
  33787. ** by all database connections. The p->pNext is a list of other
  33788. ** Btrees belonging to the same database connection as the p Btree
  33789. ** which need to be locked after p. If we cannot get a lock on
  33790. ** p, then first unlock all of the others on p->pNext, then wait
  33791. ** for the lock to become available on p, then relock all of the
  33792. ** subsequent Btrees that desire a lock.
  33793. */
  33794. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  33795. Btree *pLater;
  33796. /* Some basic sanity checking on the Btree. The list of Btrees
  33797. ** connected by pNext and pPrev should be in sorted order by
  33798. ** Btree.pBt value. All elements of the list should belong to
  33799. ** the same connection. Only shared Btrees are on the list. */
  33800. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  33801. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  33802. assert( p->pNext==0 || p->pNext->db==p->db );
  33803. assert( p->pPrev==0 || p->pPrev->db==p->db );
  33804. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  33805. /* Check for locking consistency */
  33806. assert( !p->locked || p->wantToLock>0 );
  33807. assert( p->sharable || p->wantToLock==0 );
  33808. /* We should already hold a lock on the database connection */
  33809. assert( sqlite3_mutex_held(p->db->mutex) );
  33810. if( !p->sharable ) return;
  33811. p->wantToLock++;
  33812. if( p->locked ) return;
  33813. /* In most cases, we should be able to acquire the lock we
  33814. ** want without having to go throught the ascending lock
  33815. ** procedure that follows. Just be sure not to block.
  33816. */
  33817. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  33818. p->locked = 1;
  33819. return;
  33820. }
  33821. /* To avoid deadlock, first release all locks with a larger
  33822. ** BtShared address. Then acquire our lock. Then reacquire
  33823. ** the other BtShared locks that we used to hold in ascending
  33824. ** order.
  33825. */
  33826. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  33827. assert( pLater->sharable );
  33828. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  33829. assert( !pLater->locked || pLater->wantToLock>0 );
  33830. if( pLater->locked ){
  33831. sqlite3_mutex_leave(pLater->pBt->mutex);
  33832. pLater->locked = 0;
  33833. }
  33834. }
  33835. sqlite3_mutex_enter(p->pBt->mutex);
  33836. p->locked = 1;
  33837. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  33838. if( pLater->wantToLock ){
  33839. sqlite3_mutex_enter(pLater->pBt->mutex);
  33840. pLater->locked = 1;
  33841. }
  33842. }
  33843. }
  33844. /*
  33845. ** Exit the recursive mutex on a Btree.
  33846. */
  33847. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  33848. if( p->sharable ){
  33849. assert( p->wantToLock>0 );
  33850. p->wantToLock--;
  33851. if( p->wantToLock==0 ){
  33852. assert( p->locked );
  33853. sqlite3_mutex_leave(p->pBt->mutex);
  33854. p->locked = 0;
  33855. }
  33856. }
  33857. }
  33858. #ifndef NDEBUG
  33859. /*
  33860. ** Return true if the BtShared mutex is held on the btree.
  33861. **
  33862. ** This routine makes no determination one why or another if the
  33863. ** database connection mutex is held.
  33864. **
  33865. ** This routine is used only from within assert() statements.
  33866. */
  33867. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  33868. return (p->sharable==0 ||
  33869. (p->locked && p->wantToLock && sqlite3_mutex_held(p->pBt->mutex)));
  33870. }
  33871. #endif
  33872. #ifndef SQLITE_OMIT_INCRBLOB
  33873. /*
  33874. ** Enter and leave a mutex on a Btree given a cursor owned by that
  33875. ** Btree. These entry points are used by incremental I/O and can be
  33876. ** omitted if that module is not used.
  33877. */
  33878. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  33879. sqlite3BtreeEnter(pCur->pBtree);
  33880. }
  33881. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  33882. sqlite3BtreeLeave(pCur->pBtree);
  33883. }
  33884. #endif /* SQLITE_OMIT_INCRBLOB */
  33885. /*
  33886. ** Enter the mutex on every Btree associated with a database
  33887. ** connection. This is needed (for example) prior to parsing
  33888. ** a statement since we will be comparing table and column names
  33889. ** against all schemas and we do not want those schemas being
  33890. ** reset out from under us.
  33891. **
  33892. ** There is a corresponding leave-all procedures.
  33893. **
  33894. ** Enter the mutexes in accending order by BtShared pointer address
  33895. ** to avoid the possibility of deadlock when two threads with
  33896. ** two or more btrees in common both try to lock all their btrees
  33897. ** at the same instant.
  33898. */
  33899. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  33900. int i;
  33901. Btree *p, *pLater;
  33902. assert( sqlite3_mutex_held(db->mutex) );
  33903. for(i=0; i<db->nDb; i++){
  33904. p = db->aDb[i].pBt;
  33905. if( p && p->sharable ){
  33906. p->wantToLock++;
  33907. if( !p->locked ){
  33908. assert( p->wantToLock==1 );
  33909. while( p->pPrev ) p = p->pPrev;
  33910. while( p->locked && p->pNext ) p = p->pNext;
  33911. for(pLater = p->pNext; pLater; pLater=pLater->pNext){
  33912. if( pLater->locked ){
  33913. sqlite3_mutex_leave(pLater->pBt->mutex);
  33914. pLater->locked = 0;
  33915. }
  33916. }
  33917. while( p ){
  33918. sqlite3_mutex_enter(p->pBt->mutex);
  33919. p->locked++;
  33920. p = p->pNext;
  33921. }
  33922. }
  33923. }
  33924. }
  33925. }
  33926. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  33927. int i;
  33928. Btree *p;
  33929. assert( sqlite3_mutex_held(db->mutex) );
  33930. for(i=0; i<db->nDb; i++){
  33931. p = db->aDb[i].pBt;
  33932. if( p && p->sharable ){
  33933. assert( p->wantToLock>0 );
  33934. p->wantToLock--;
  33935. if( p->wantToLock==0 ){
  33936. assert( p->locked );
  33937. sqlite3_mutex_leave(p->pBt->mutex);
  33938. p->locked = 0;
  33939. }
  33940. }
  33941. }
  33942. }
  33943. #ifndef NDEBUG
  33944. /*
  33945. ** Return true if the current thread holds the database connection
  33946. ** mutex and all required BtShared mutexes.
  33947. **
  33948. ** This routine is used inside assert() statements only.
  33949. */
  33950. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  33951. int i;
  33952. if( !sqlite3_mutex_held(db->mutex) ){
  33953. return 0;
  33954. }
  33955. for(i=0; i<db->nDb; i++){
  33956. Btree *p;
  33957. p = db->aDb[i].pBt;
  33958. if( p && p->sharable &&
  33959. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  33960. return 0;
  33961. }
  33962. }
  33963. return 1;
  33964. }
  33965. #endif /* NDEBUG */
  33966. /*
  33967. ** Add a new Btree pointer to a BtreeMutexArray.
  33968. ** if the pointer can possibly be shared with
  33969. ** another database connection.
  33970. **
  33971. ** The pointers are kept in sorted order by pBtree->pBt. That
  33972. ** way when we go to enter all the mutexes, we can enter them
  33973. ** in order without every having to backup and retry and without
  33974. ** worrying about deadlock.
  33975. **
  33976. ** The number of shared btrees will always be small (usually 0 or 1)
  33977. ** so an insertion sort is an adequate algorithm here.
  33978. */
  33979. SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
  33980. int i, j;
  33981. BtShared *pBt;
  33982. if( pBtree==0 || pBtree->sharable==0 ) return;
  33983. #ifndef NDEBUG
  33984. {
  33985. for(i=0; i<pArray->nMutex; i++){
  33986. assert( pArray->aBtree[i]!=pBtree );
  33987. }
  33988. }
  33989. #endif
  33990. assert( pArray->nMutex>=0 );
  33991. assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
  33992. pBt = pBtree->pBt;
  33993. for(i=0; i<pArray->nMutex; i++){
  33994. assert( pArray->aBtree[i]!=pBtree );
  33995. if( pArray->aBtree[i]->pBt>pBt ){
  33996. for(j=pArray->nMutex; j>i; j--){
  33997. pArray->aBtree[j] = pArray->aBtree[j-1];
  33998. }
  33999. pArray->aBtree[i] = pBtree;
  34000. pArray->nMutex++;
  34001. return;
  34002. }
  34003. }
  34004. pArray->aBtree[pArray->nMutex++] = pBtree;
  34005. }
  34006. /*
  34007. ** Enter the mutex of every btree in the array. This routine is
  34008. ** called at the beginning of sqlite3VdbeExec(). The mutexes are
  34009. ** exited at the end of the same function.
  34010. */
  34011. SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
  34012. int i;
  34013. for(i=0; i<pArray->nMutex; i++){
  34014. Btree *p = pArray->aBtree[i];
  34015. /* Some basic sanity checking */
  34016. assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
  34017. assert( !p->locked || p->wantToLock>0 );
  34018. /* We should already hold a lock on the database connection */
  34019. assert( sqlite3_mutex_held(p->db->mutex) );
  34020. p->wantToLock++;
  34021. if( !p->locked && p->sharable ){
  34022. sqlite3_mutex_enter(p->pBt->mutex);
  34023. p->locked = 1;
  34024. }
  34025. }
  34026. }
  34027. /*
  34028. ** Leave the mutex of every btree in the group.
  34029. */
  34030. SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
  34031. int i;
  34032. for(i=0; i<pArray->nMutex; i++){
  34033. Btree *p = pArray->aBtree[i];
  34034. /* Some basic sanity checking */
  34035. assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
  34036. assert( p->locked || !p->sharable );
  34037. assert( p->wantToLock>0 );
  34038. /* We should already hold a lock on the database connection */
  34039. assert( sqlite3_mutex_held(p->db->mutex) );
  34040. p->wantToLock--;
  34041. if( p->wantToLock==0 && p->locked ){
  34042. sqlite3_mutex_leave(p->pBt->mutex);
  34043. p->locked = 0;
  34044. }
  34045. }
  34046. }
  34047. #endif /* SQLITE_THREADSAFE && !SQLITE_OMIT_SHARED_CACHE */
  34048. /************** End of btmutex.c *********************************************/
  34049. /************** Begin file btree.c *******************************************/
  34050. /*
  34051. ** 2004 April 6
  34052. **
  34053. ** The author disclaims copyright to this source code. In place of
  34054. ** a legal notice, here is a blessing:
  34055. **
  34056. ** May you do good and not evil.
  34057. ** May you find forgiveness for yourself and forgive others.
  34058. ** May you share freely, never taking more than you give.
  34059. **
  34060. *************************************************************************
  34061. ** $Id: btree.c,v 1.558 2009/01/10 16:15:21 drh Exp $
  34062. **
  34063. ** This file implements a external (disk-based) database using BTrees.
  34064. ** See the header comment on "btreeInt.h" for additional information.
  34065. ** Including a description of file format and an overview of operation.
  34066. */
  34067. /*
  34068. ** The header string that appears at the beginning of every
  34069. ** SQLite database.
  34070. */
  34071. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  34072. /*
  34073. ** Set this global variable to 1 to enable tracing using the TRACE
  34074. ** macro.
  34075. */
  34076. #if 0
  34077. int sqlite3BtreeTrace=0; /* True to enable tracing */
  34078. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  34079. #else
  34080. # define TRACE(X)
  34081. #endif
  34082. #ifndef SQLITE_OMIT_SHARED_CACHE
  34083. /*
  34084. ** A list of BtShared objects that are eligible for participation
  34085. ** in shared cache. This variable has file scope during normal builds,
  34086. ** but the test harness needs to access it so we make it global for
  34087. ** test builds.
  34088. */
  34089. #ifdef SQLITE_TEST
  34090. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  34091. #else
  34092. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  34093. #endif
  34094. #endif /* SQLITE_OMIT_SHARED_CACHE */
  34095. #ifndef SQLITE_OMIT_SHARED_CACHE
  34096. /*
  34097. ** Enable or disable the shared pager and schema features.
  34098. **
  34099. ** This routine has no effect on existing database connections.
  34100. ** The shared cache setting effects only future calls to
  34101. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  34102. */
  34103. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  34104. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  34105. return SQLITE_OK;
  34106. }
  34107. #endif
  34108. /*
  34109. ** Forward declaration
  34110. */
  34111. static int checkReadLocks(Btree*, Pgno, BtCursor*, i64);
  34112. #ifdef SQLITE_OMIT_SHARED_CACHE
  34113. /*
  34114. ** The functions queryTableLock(), lockTable() and unlockAllTables()
  34115. ** manipulate entries in the BtShared.pLock linked list used to store
  34116. ** shared-cache table level locks. If the library is compiled with the
  34117. ** shared-cache feature disabled, then there is only ever one user
  34118. ** of each BtShared structure and so this locking is not necessary.
  34119. ** So define the lock related functions as no-ops.
  34120. */
  34121. #define queryTableLock(a,b,c) SQLITE_OK
  34122. #define lockTable(a,b,c) SQLITE_OK
  34123. #define unlockAllTables(a)
  34124. #endif
  34125. #ifndef SQLITE_OMIT_SHARED_CACHE
  34126. /*
  34127. ** Query to see if btree handle p may obtain a lock of type eLock
  34128. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  34129. ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
  34130. ** SQLITE_LOCKED if not.
  34131. */
  34132. static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
  34133. BtShared *pBt = p->pBt;
  34134. BtLock *pIter;
  34135. assert( sqlite3BtreeHoldsMutex(p) );
  34136. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  34137. assert( p->db!=0 );
  34138. /* This is a no-op if the shared-cache is not enabled */
  34139. if( !p->sharable ){
  34140. return SQLITE_OK;
  34141. }
  34142. /* If some other connection is holding an exclusive lock, the
  34143. ** requested lock may not be obtained.
  34144. */
  34145. if( pBt->pExclusive && pBt->pExclusive!=p ){
  34146. return SQLITE_LOCKED;
  34147. }
  34148. /* This (along with lockTable()) is where the ReadUncommitted flag is
  34149. ** dealt with. If the caller is querying for a read-lock and the flag is
  34150. ** set, it is unconditionally granted - even if there are write-locks
  34151. ** on the table. If a write-lock is requested, the ReadUncommitted flag
  34152. ** is not considered.
  34153. **
  34154. ** In function lockTable(), if a read-lock is demanded and the
  34155. ** ReadUncommitted flag is set, no entry is added to the locks list
  34156. ** (BtShared.pLock).
  34157. **
  34158. ** To summarize: If the ReadUncommitted flag is set, then read cursors do
  34159. ** not create or respect table locks. The locking procedure for a
  34160. ** write-cursor does not change.
  34161. */
  34162. if(
  34163. 0==(p->db->flags&SQLITE_ReadUncommitted) ||
  34164. eLock==WRITE_LOCK ||
  34165. iTab==MASTER_ROOT
  34166. ){
  34167. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  34168. if( pIter->pBtree!=p && pIter->iTable==iTab &&
  34169. (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
  34170. return SQLITE_LOCKED;
  34171. }
  34172. }
  34173. }
  34174. return SQLITE_OK;
  34175. }
  34176. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  34177. #ifndef SQLITE_OMIT_SHARED_CACHE
  34178. /*
  34179. ** Add a lock on the table with root-page iTable to the shared-btree used
  34180. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  34181. ** WRITE_LOCK.
  34182. **
  34183. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
  34184. ** SQLITE_NOMEM may also be returned.
  34185. */
  34186. static int lockTable(Btree *p, Pgno iTable, u8 eLock){
  34187. BtShared *pBt = p->pBt;
  34188. BtLock *pLock = 0;
  34189. BtLock *pIter;
  34190. assert( sqlite3BtreeHoldsMutex(p) );
  34191. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  34192. assert( p->db!=0 );
  34193. /* This is a no-op if the shared-cache is not enabled */
  34194. if( !p->sharable ){
  34195. return SQLITE_OK;
  34196. }
  34197. assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
  34198. /* If the read-uncommitted flag is set and a read-lock is requested,
  34199. ** return early without adding an entry to the BtShared.pLock list. See
  34200. ** comment in function queryTableLock() for more info on handling
  34201. ** the ReadUncommitted flag.
  34202. */
  34203. if(
  34204. (p->db->flags&SQLITE_ReadUncommitted) &&
  34205. (eLock==READ_LOCK) &&
  34206. iTable!=MASTER_ROOT
  34207. ){
  34208. return SQLITE_OK;
  34209. }
  34210. /* First search the list for an existing lock on this table. */
  34211. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  34212. if( pIter->iTable==iTable && pIter->pBtree==p ){
  34213. pLock = pIter;
  34214. break;
  34215. }
  34216. }
  34217. /* If the above search did not find a BtLock struct associating Btree p
  34218. ** with table iTable, allocate one and link it into the list.
  34219. */
  34220. if( !pLock ){
  34221. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  34222. if( !pLock ){
  34223. return SQLITE_NOMEM;
  34224. }
  34225. pLock->iTable = iTable;
  34226. pLock->pBtree = p;
  34227. pLock->pNext = pBt->pLock;
  34228. pBt->pLock = pLock;
  34229. }
  34230. /* Set the BtLock.eLock variable to the maximum of the current lock
  34231. ** and the requested lock. This means if a write-lock was already held
  34232. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  34233. */
  34234. assert( WRITE_LOCK>READ_LOCK );
  34235. if( eLock>pLock->eLock ){
  34236. pLock->eLock = eLock;
  34237. }
  34238. return SQLITE_OK;
  34239. }
  34240. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  34241. #ifndef SQLITE_OMIT_SHARED_CACHE
  34242. /*
  34243. ** Release all the table locks (locks obtained via calls to the lockTable()
  34244. ** procedure) held by Btree handle p.
  34245. */
  34246. static void unlockAllTables(Btree *p){
  34247. BtShared *pBt = p->pBt;
  34248. BtLock **ppIter = &pBt->pLock;
  34249. assert( sqlite3BtreeHoldsMutex(p) );
  34250. assert( p->sharable || 0==*ppIter );
  34251. while( *ppIter ){
  34252. BtLock *pLock = *ppIter;
  34253. assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
  34254. if( pLock->pBtree==p ){
  34255. *ppIter = pLock->pNext;
  34256. sqlite3_free(pLock);
  34257. }else{
  34258. ppIter = &pLock->pNext;
  34259. }
  34260. }
  34261. if( pBt->pExclusive==p ){
  34262. pBt->pExclusive = 0;
  34263. }
  34264. }
  34265. #endif /* SQLITE_OMIT_SHARED_CACHE */
  34266. static void releasePage(MemPage *pPage); /* Forward reference */
  34267. /*
  34268. ** Verify that the cursor holds a mutex on the BtShared
  34269. */
  34270. #ifndef NDEBUG
  34271. static int cursorHoldsMutex(BtCursor *p){
  34272. return sqlite3_mutex_held(p->pBt->mutex);
  34273. }
  34274. #endif
  34275. #ifndef SQLITE_OMIT_INCRBLOB
  34276. /*
  34277. ** Invalidate the overflow page-list cache for cursor pCur, if any.
  34278. */
  34279. static void invalidateOverflowCache(BtCursor *pCur){
  34280. assert( cursorHoldsMutex(pCur) );
  34281. sqlite3_free(pCur->aOverflow);
  34282. pCur->aOverflow = 0;
  34283. }
  34284. /*
  34285. ** Invalidate the overflow page-list cache for all cursors opened
  34286. ** on the shared btree structure pBt.
  34287. */
  34288. static void invalidateAllOverflowCache(BtShared *pBt){
  34289. BtCursor *p;
  34290. assert( sqlite3_mutex_held(pBt->mutex) );
  34291. for(p=pBt->pCursor; p; p=p->pNext){
  34292. invalidateOverflowCache(p);
  34293. }
  34294. }
  34295. #else
  34296. #define invalidateOverflowCache(x)
  34297. #define invalidateAllOverflowCache(x)
  34298. #endif
  34299. /*
  34300. ** Save the current cursor position in the variables BtCursor.nKey
  34301. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  34302. */
  34303. static int saveCursorPosition(BtCursor *pCur){
  34304. int rc;
  34305. assert( CURSOR_VALID==pCur->eState );
  34306. assert( 0==pCur->pKey );
  34307. assert( cursorHoldsMutex(pCur) );
  34308. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  34309. /* If this is an intKey table, then the above call to BtreeKeySize()
  34310. ** stores the integer key in pCur->nKey. In this case this value is
  34311. ** all that is required. Otherwise, if pCur is not open on an intKey
  34312. ** table, then malloc space for and store the pCur->nKey bytes of key
  34313. ** data.
  34314. */
  34315. if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
  34316. void *pKey = sqlite3Malloc( (int)pCur->nKey );
  34317. if( pKey ){
  34318. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  34319. if( rc==SQLITE_OK ){
  34320. pCur->pKey = pKey;
  34321. }else{
  34322. sqlite3_free(pKey);
  34323. }
  34324. }else{
  34325. rc = SQLITE_NOMEM;
  34326. }
  34327. }
  34328. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  34329. if( rc==SQLITE_OK ){
  34330. int i;
  34331. for(i=0; i<=pCur->iPage; i++){
  34332. releasePage(pCur->apPage[i]);
  34333. pCur->apPage[i] = 0;
  34334. }
  34335. pCur->iPage = -1;
  34336. pCur->eState = CURSOR_REQUIRESEEK;
  34337. }
  34338. invalidateOverflowCache(pCur);
  34339. return rc;
  34340. }
  34341. /*
  34342. ** Save the positions of all cursors except pExcept open on the table
  34343. ** with root-page iRoot. Usually, this is called just before cursor
  34344. ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
  34345. */
  34346. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  34347. BtCursor *p;
  34348. assert( sqlite3_mutex_held(pBt->mutex) );
  34349. assert( pExcept==0 || pExcept->pBt==pBt );
  34350. for(p=pBt->pCursor; p; p=p->pNext){
  34351. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
  34352. p->eState==CURSOR_VALID ){
  34353. int rc = saveCursorPosition(p);
  34354. if( SQLITE_OK!=rc ){
  34355. return rc;
  34356. }
  34357. }
  34358. }
  34359. return SQLITE_OK;
  34360. }
  34361. /*
  34362. ** Clear the current cursor position.
  34363. */
  34364. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  34365. assert( cursorHoldsMutex(pCur) );
  34366. sqlite3_free(pCur->pKey);
  34367. pCur->pKey = 0;
  34368. pCur->eState = CURSOR_INVALID;
  34369. }
  34370. /*
  34371. ** Restore the cursor to the position it was in (or as close to as possible)
  34372. ** when saveCursorPosition() was called. Note that this call deletes the
  34373. ** saved position info stored by saveCursorPosition(), so there can be
  34374. ** at most one effective restoreCursorPosition() call after each
  34375. ** saveCursorPosition().
  34376. */
  34377. SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
  34378. int rc;
  34379. assert( cursorHoldsMutex(pCur) );
  34380. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  34381. if( pCur->eState==CURSOR_FAULT ){
  34382. return pCur->skip;
  34383. }
  34384. pCur->eState = CURSOR_INVALID;
  34385. rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
  34386. if( rc==SQLITE_OK ){
  34387. sqlite3_free(pCur->pKey);
  34388. pCur->pKey = 0;
  34389. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  34390. }
  34391. return rc;
  34392. }
  34393. #define restoreCursorPosition(p) \
  34394. (p->eState>=CURSOR_REQUIRESEEK ? \
  34395. sqlite3BtreeRestoreCursorPosition(p) : \
  34396. SQLITE_OK)
  34397. /*
  34398. ** Determine whether or not a cursor has moved from the position it
  34399. ** was last placed at. Cursors can move when the row they are pointing
  34400. ** at is deleted out from under them.
  34401. **
  34402. ** This routine returns an error code if something goes wrong. The
  34403. ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
  34404. */
  34405. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  34406. int rc;
  34407. rc = restoreCursorPosition(pCur);
  34408. if( rc ){
  34409. *pHasMoved = 1;
  34410. return rc;
  34411. }
  34412. if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
  34413. *pHasMoved = 1;
  34414. }else{
  34415. *pHasMoved = 0;
  34416. }
  34417. return SQLITE_OK;
  34418. }
  34419. #ifndef SQLITE_OMIT_AUTOVACUUM
  34420. /*
  34421. ** Given a page number of a regular database page, return the page
  34422. ** number for the pointer-map page that contains the entry for the
  34423. ** input page number.
  34424. */
  34425. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  34426. int nPagesPerMapPage;
  34427. Pgno iPtrMap, ret;
  34428. assert( sqlite3_mutex_held(pBt->mutex) );
  34429. nPagesPerMapPage = (pBt->usableSize/5)+1;
  34430. iPtrMap = (pgno-2)/nPagesPerMapPage;
  34431. ret = (iPtrMap*nPagesPerMapPage) + 2;
  34432. if( ret==PENDING_BYTE_PAGE(pBt) ){
  34433. ret++;
  34434. }
  34435. return ret;
  34436. }
  34437. /*
  34438. ** Write an entry into the pointer map.
  34439. **
  34440. ** This routine updates the pointer map entry for page number 'key'
  34441. ** so that it maps to type 'eType' and parent page number 'pgno'.
  34442. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  34443. */
  34444. static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
  34445. DbPage *pDbPage; /* The pointer map page */
  34446. u8 *pPtrmap; /* The pointer map data */
  34447. Pgno iPtrmap; /* The pointer map page number */
  34448. int offset; /* Offset in pointer map page */
  34449. int rc;
  34450. assert( sqlite3_mutex_held(pBt->mutex) );
  34451. /* The master-journal page number must never be used as a pointer map page */
  34452. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  34453. assert( pBt->autoVacuum );
  34454. if( key==0 ){
  34455. return SQLITE_CORRUPT_BKPT;
  34456. }
  34457. iPtrmap = PTRMAP_PAGENO(pBt, key);
  34458. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  34459. if( rc!=SQLITE_OK ){
  34460. return rc;
  34461. }
  34462. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  34463. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  34464. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  34465. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  34466. rc = sqlite3PagerWrite(pDbPage);
  34467. if( rc==SQLITE_OK ){
  34468. pPtrmap[offset] = eType;
  34469. put4byte(&pPtrmap[offset+1], parent);
  34470. }
  34471. }
  34472. sqlite3PagerUnref(pDbPage);
  34473. return rc;
  34474. }
  34475. /*
  34476. ** Read an entry from the pointer map.
  34477. **
  34478. ** This routine retrieves the pointer map entry for page 'key', writing
  34479. ** the type and parent page number to *pEType and *pPgno respectively.
  34480. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  34481. */
  34482. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  34483. DbPage *pDbPage; /* The pointer map page */
  34484. int iPtrmap; /* Pointer map page index */
  34485. u8 *pPtrmap; /* Pointer map page data */
  34486. int offset; /* Offset of entry in pointer map */
  34487. int rc;
  34488. assert( sqlite3_mutex_held(pBt->mutex) );
  34489. iPtrmap = PTRMAP_PAGENO(pBt, key);
  34490. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  34491. if( rc!=0 ){
  34492. return rc;
  34493. }
  34494. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  34495. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  34496. assert( pEType!=0 );
  34497. *pEType = pPtrmap[offset];
  34498. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  34499. sqlite3PagerUnref(pDbPage);
  34500. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  34501. return SQLITE_OK;
  34502. }
  34503. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  34504. #define ptrmapPut(w,x,y,z) SQLITE_OK
  34505. #define ptrmapGet(w,x,y,z) SQLITE_OK
  34506. #define ptrmapPutOvfl(y,z) SQLITE_OK
  34507. #endif
  34508. /*
  34509. ** Given a btree page and a cell index (0 means the first cell on
  34510. ** the page, 1 means the second cell, and so forth) return a pointer
  34511. ** to the cell content.
  34512. **
  34513. ** This routine works only for pages that do not contain overflow cells.
  34514. */
  34515. #define findCell(P,I) \
  34516. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
  34517. /*
  34518. ** This a more complex version of findCell() that works for
  34519. ** pages that do contain overflow cells. See insert
  34520. */
  34521. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  34522. int i;
  34523. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34524. for(i=pPage->nOverflow-1; i>=0; i--){
  34525. int k;
  34526. struct _OvflCell *pOvfl;
  34527. pOvfl = &pPage->aOvfl[i];
  34528. k = pOvfl->idx;
  34529. if( k<=iCell ){
  34530. if( k==iCell ){
  34531. return pOvfl->pCell;
  34532. }
  34533. iCell--;
  34534. }
  34535. }
  34536. return findCell(pPage, iCell);
  34537. }
  34538. /*
  34539. ** Parse a cell content block and fill in the CellInfo structure. There
  34540. ** are two versions of this function. sqlite3BtreeParseCell() takes a
  34541. ** cell index as the second argument and sqlite3BtreeParseCellPtr()
  34542. ** takes a pointer to the body of the cell as its second argument.
  34543. **
  34544. ** Within this file, the parseCell() macro can be called instead of
  34545. ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
  34546. */
  34547. SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
  34548. MemPage *pPage, /* Page containing the cell */
  34549. u8 *pCell, /* Pointer to the cell text. */
  34550. CellInfo *pInfo /* Fill in this structure */
  34551. ){
  34552. u16 n; /* Number bytes in cell content header */
  34553. u32 nPayload; /* Number of bytes of cell payload */
  34554. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34555. pInfo->pCell = pCell;
  34556. assert( pPage->leaf==0 || pPage->leaf==1 );
  34557. n = pPage->childPtrSize;
  34558. assert( n==4-4*pPage->leaf );
  34559. if( pPage->intKey ){
  34560. if( pPage->hasData ){
  34561. n += getVarint32(&pCell[n], nPayload);
  34562. }else{
  34563. nPayload = 0;
  34564. }
  34565. n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
  34566. pInfo->nData = nPayload;
  34567. }else{
  34568. pInfo->nData = 0;
  34569. n += getVarint32(&pCell[n], nPayload);
  34570. pInfo->nKey = nPayload;
  34571. }
  34572. pInfo->nPayload = nPayload;
  34573. pInfo->nHeader = n;
  34574. if( likely(nPayload<=pPage->maxLocal) ){
  34575. /* This is the (easy) common case where the entire payload fits
  34576. ** on the local page. No overflow is required.
  34577. */
  34578. int nSize; /* Total size of cell content in bytes */
  34579. nSize = nPayload + n;
  34580. pInfo->nLocal = (u16)nPayload;
  34581. pInfo->iOverflow = 0;
  34582. if( (nSize & ~3)==0 ){
  34583. nSize = 4; /* Minimum cell size is 4 */
  34584. }
  34585. pInfo->nSize = (u16)nSize;
  34586. }else{
  34587. /* If the payload will not fit completely on the local page, we have
  34588. ** to decide how much to store locally and how much to spill onto
  34589. ** overflow pages. The strategy is to minimize the amount of unused
  34590. ** space on overflow pages while keeping the amount of local storage
  34591. ** in between minLocal and maxLocal.
  34592. **
  34593. ** Warning: changing the way overflow payload is distributed in any
  34594. ** way will result in an incompatible file format.
  34595. */
  34596. int minLocal; /* Minimum amount of payload held locally */
  34597. int maxLocal; /* Maximum amount of payload held locally */
  34598. int surplus; /* Overflow payload available for local storage */
  34599. minLocal = pPage->minLocal;
  34600. maxLocal = pPage->maxLocal;
  34601. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  34602. if( surplus <= maxLocal ){
  34603. pInfo->nLocal = (u16)surplus;
  34604. }else{
  34605. pInfo->nLocal = (u16)minLocal;
  34606. }
  34607. pInfo->iOverflow = (u16)(pInfo->nLocal + n);
  34608. pInfo->nSize = pInfo->iOverflow + 4;
  34609. }
  34610. }
  34611. #define parseCell(pPage, iCell, pInfo) \
  34612. sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  34613. SQLITE_PRIVATE void sqlite3BtreeParseCell(
  34614. MemPage *pPage, /* Page containing the cell */
  34615. int iCell, /* The cell index. First cell is 0 */
  34616. CellInfo *pInfo /* Fill in this structure */
  34617. ){
  34618. parseCell(pPage, iCell, pInfo);
  34619. }
  34620. /*
  34621. ** Compute the total number of bytes that a Cell needs in the cell
  34622. ** data area of the btree-page. The return number includes the cell
  34623. ** data header and the local payload, but not any overflow page or
  34624. ** the space used by the cell pointer.
  34625. */
  34626. #ifndef NDEBUG
  34627. static u16 cellSize(MemPage *pPage, int iCell){
  34628. CellInfo info;
  34629. sqlite3BtreeParseCell(pPage, iCell, &info);
  34630. return info.nSize;
  34631. }
  34632. #endif
  34633. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  34634. CellInfo info;
  34635. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  34636. return info.nSize;
  34637. }
  34638. #ifndef SQLITE_OMIT_AUTOVACUUM
  34639. /*
  34640. ** If the cell pCell, part of page pPage contains a pointer
  34641. ** to an overflow page, insert an entry into the pointer-map
  34642. ** for the overflow page.
  34643. */
  34644. static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
  34645. CellInfo info;
  34646. assert( pCell!=0 );
  34647. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  34648. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  34649. if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
  34650. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  34651. return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
  34652. }
  34653. return SQLITE_OK;
  34654. }
  34655. /*
  34656. ** If the cell with index iCell on page pPage contains a pointer
  34657. ** to an overflow page, insert an entry into the pointer-map
  34658. ** for the overflow page.
  34659. */
  34660. static int ptrmapPutOvfl(MemPage *pPage, int iCell){
  34661. u8 *pCell;
  34662. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34663. pCell = findOverflowCell(pPage, iCell);
  34664. return ptrmapPutOvflPtr(pPage, pCell);
  34665. }
  34666. #endif
  34667. /*
  34668. ** Defragment the page given. All Cells are moved to the
  34669. ** end of the page and all free space is collected into one
  34670. ** big FreeBlk that occurs in between the header and cell
  34671. ** pointer array and the cell content area.
  34672. */
  34673. static int defragmentPage(MemPage *pPage){
  34674. int i; /* Loop counter */
  34675. int pc; /* Address of a i-th cell */
  34676. int addr; /* Offset of first byte after cell pointer array */
  34677. int hdr; /* Offset to the page header */
  34678. int size; /* Size of a cell */
  34679. int usableSize; /* Number of usable bytes on a page */
  34680. int cellOffset; /* Offset to the cell pointer array */
  34681. int cbrk; /* Offset to the cell content area */
  34682. int nCell; /* Number of cells on the page */
  34683. unsigned char *data; /* The page data */
  34684. unsigned char *temp; /* Temp area for cell content */
  34685. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34686. assert( pPage->pBt!=0 );
  34687. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  34688. assert( pPage->nOverflow==0 );
  34689. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34690. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  34691. data = pPage->aData;
  34692. hdr = pPage->hdrOffset;
  34693. cellOffset = pPage->cellOffset;
  34694. nCell = pPage->nCell;
  34695. assert( nCell==get2byte(&data[hdr+3]) );
  34696. usableSize = pPage->pBt->usableSize;
  34697. cbrk = get2byte(&data[hdr+5]);
  34698. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  34699. cbrk = usableSize;
  34700. for(i=0; i<nCell; i++){
  34701. u8 *pAddr; /* The i-th cell pointer */
  34702. pAddr = &data[cellOffset + i*2];
  34703. pc = get2byte(pAddr);
  34704. if( pc>=usableSize ){
  34705. return SQLITE_CORRUPT_BKPT;
  34706. }
  34707. size = cellSizePtr(pPage, &temp[pc]);
  34708. cbrk -= size;
  34709. if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
  34710. return SQLITE_CORRUPT_BKPT;
  34711. }
  34712. assert( cbrk+size<=usableSize && cbrk>=0 );
  34713. memcpy(&data[cbrk], &temp[pc], size);
  34714. put2byte(pAddr, cbrk);
  34715. }
  34716. assert( cbrk>=cellOffset+2*nCell );
  34717. put2byte(&data[hdr+5], cbrk);
  34718. data[hdr+1] = 0;
  34719. data[hdr+2] = 0;
  34720. data[hdr+7] = 0;
  34721. addr = cellOffset+2*nCell;
  34722. memset(&data[addr], 0, cbrk-addr);
  34723. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34724. if( cbrk-addr!=pPage->nFree ){
  34725. return SQLITE_CORRUPT_BKPT;
  34726. }
  34727. return SQLITE_OK;
  34728. }
  34729. /*
  34730. ** Allocate nByte bytes of space on a page.
  34731. **
  34732. ** Return the index into pPage->aData[] of the first byte of
  34733. ** the new allocation. The caller guarantees that there is enough
  34734. ** space. This routine will never fail.
  34735. **
  34736. ** If the page contains nBytes of free space but does not contain
  34737. ** nBytes of contiguous free space, then this routine automatically
  34738. ** calls defragementPage() to consolidate all free space before
  34739. ** allocating the new chunk.
  34740. */
  34741. static int allocateSpace(MemPage *pPage, int nByte){
  34742. int addr, pc, hdr;
  34743. int size;
  34744. int nFrag;
  34745. int top;
  34746. int nCell;
  34747. int cellOffset;
  34748. unsigned char *data;
  34749. data = pPage->aData;
  34750. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34751. assert( pPage->pBt );
  34752. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34753. assert( nByte>=0 ); /* Minimum cell size is 4 */
  34754. assert( pPage->nFree>=nByte );
  34755. assert( pPage->nOverflow==0 );
  34756. pPage->nFree -= (u16)nByte;
  34757. hdr = pPage->hdrOffset;
  34758. nFrag = data[hdr+7];
  34759. if( nFrag<60 ){
  34760. /* Search the freelist looking for a slot big enough to satisfy the
  34761. ** space request. */
  34762. addr = hdr+1;
  34763. while( (pc = get2byte(&data[addr]))>0 ){
  34764. size = get2byte(&data[pc+2]);
  34765. if( size>=nByte ){
  34766. int x = size - nByte;
  34767. if( size<nByte+4 ){
  34768. memcpy(&data[addr], &data[pc], 2);
  34769. data[hdr+7] = (u8)(nFrag + x);
  34770. return pc;
  34771. }else{
  34772. put2byte(&data[pc+2], x);
  34773. return pc + x;
  34774. }
  34775. }
  34776. addr = pc;
  34777. }
  34778. }
  34779. /* Allocate memory from the gap in between the cell pointer array
  34780. ** and the cell content area.
  34781. */
  34782. top = get2byte(&data[hdr+5]);
  34783. nCell = get2byte(&data[hdr+3]);
  34784. cellOffset = pPage->cellOffset;
  34785. if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
  34786. defragmentPage(pPage);
  34787. top = get2byte(&data[hdr+5]);
  34788. }
  34789. top -= nByte;
  34790. assert( cellOffset + 2*nCell <= top );
  34791. put2byte(&data[hdr+5], top);
  34792. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34793. return top;
  34794. }
  34795. /*
  34796. ** Return a section of the pPage->aData to the freelist.
  34797. ** The first byte of the new free block is pPage->aDisk[start]
  34798. ** and the size of the block is "size" bytes.
  34799. **
  34800. ** Most of the effort here is involved in coalesing adjacent
  34801. ** free blocks into a single big free block.
  34802. */
  34803. static int freeSpace(MemPage *pPage, int start, int size){
  34804. int addr, pbegin, hdr;
  34805. unsigned char *data = pPage->aData;
  34806. assert( pPage->pBt!=0 );
  34807. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34808. assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
  34809. assert( (start + size)<=pPage->pBt->usableSize );
  34810. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34811. assert( size>=0 ); /* Minimum cell size is 4 */
  34812. #ifdef SQLITE_SECURE_DELETE
  34813. /* Overwrite deleted information with zeros when the SECURE_DELETE
  34814. ** option is enabled at compile-time */
  34815. memset(&data[start], 0, size);
  34816. #endif
  34817. /* Add the space back into the linked list of freeblocks */
  34818. hdr = pPage->hdrOffset;
  34819. addr = hdr + 1;
  34820. while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
  34821. assert( pbegin<=pPage->pBt->usableSize-4 );
  34822. if( pbegin<=addr ) {
  34823. return SQLITE_CORRUPT_BKPT;
  34824. }
  34825. addr = pbegin;
  34826. }
  34827. if ( pbegin>pPage->pBt->usableSize-4 ) {
  34828. return SQLITE_CORRUPT_BKPT;
  34829. }
  34830. assert( pbegin>addr || pbegin==0 );
  34831. put2byte(&data[addr], start);
  34832. put2byte(&data[start], pbegin);
  34833. put2byte(&data[start+2], size);
  34834. pPage->nFree += (u16)size;
  34835. /* Coalesce adjacent free blocks */
  34836. addr = pPage->hdrOffset + 1;
  34837. while( (pbegin = get2byte(&data[addr]))>0 ){
  34838. int pnext, psize, x;
  34839. assert( pbegin>addr );
  34840. assert( pbegin<=pPage->pBt->usableSize-4 );
  34841. pnext = get2byte(&data[pbegin]);
  34842. psize = get2byte(&data[pbegin+2]);
  34843. if( pbegin + psize + 3 >= pnext && pnext>0 ){
  34844. int frag = pnext - (pbegin+psize);
  34845. if( (frag<0) || (frag>(int)data[pPage->hdrOffset+7]) ){
  34846. return SQLITE_CORRUPT_BKPT;
  34847. }
  34848. data[pPage->hdrOffset+7] -= (u8)frag;
  34849. x = get2byte(&data[pnext]);
  34850. put2byte(&data[pbegin], x);
  34851. x = pnext + get2byte(&data[pnext+2]) - pbegin;
  34852. put2byte(&data[pbegin+2], x);
  34853. }else{
  34854. addr = pbegin;
  34855. }
  34856. }
  34857. /* If the cell content area begins with a freeblock, remove it. */
  34858. if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
  34859. int top;
  34860. pbegin = get2byte(&data[hdr+1]);
  34861. memcpy(&data[hdr+1], &data[pbegin], 2);
  34862. top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
  34863. put2byte(&data[hdr+5], top);
  34864. }
  34865. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34866. return SQLITE_OK;
  34867. }
  34868. /*
  34869. ** Decode the flags byte (the first byte of the header) for a page
  34870. ** and initialize fields of the MemPage structure accordingly.
  34871. **
  34872. ** Only the following combinations are supported. Anything different
  34873. ** indicates a corrupt database files:
  34874. **
  34875. ** PTF_ZERODATA
  34876. ** PTF_ZERODATA | PTF_LEAF
  34877. ** PTF_LEAFDATA | PTF_INTKEY
  34878. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  34879. */
  34880. static int decodeFlags(MemPage *pPage, int flagByte){
  34881. BtShared *pBt; /* A copy of pPage->pBt */
  34882. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  34883. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34884. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  34885. flagByte &= ~PTF_LEAF;
  34886. pPage->childPtrSize = 4-4*pPage->leaf;
  34887. pBt = pPage->pBt;
  34888. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  34889. pPage->intKey = 1;
  34890. pPage->hasData = pPage->leaf;
  34891. pPage->maxLocal = pBt->maxLeaf;
  34892. pPage->minLocal = pBt->minLeaf;
  34893. }else if( flagByte==PTF_ZERODATA ){
  34894. pPage->intKey = 0;
  34895. pPage->hasData = 0;
  34896. pPage->maxLocal = pBt->maxLocal;
  34897. pPage->minLocal = pBt->minLocal;
  34898. }else{
  34899. return SQLITE_CORRUPT_BKPT;
  34900. }
  34901. return SQLITE_OK;
  34902. }
  34903. /*
  34904. ** Initialize the auxiliary information for a disk block.
  34905. **
  34906. ** Return SQLITE_OK on success. If we see that the page does
  34907. ** not contain a well-formed database page, then return
  34908. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  34909. ** guarantee that the page is well-formed. It only shows that
  34910. ** we failed to detect any corruption.
  34911. */
  34912. SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage){
  34913. assert( pPage->pBt!=0 );
  34914. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34915. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  34916. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  34917. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  34918. if( !pPage->isInit ){
  34919. u16 pc; /* Address of a freeblock within pPage->aData[] */
  34920. u8 hdr; /* Offset to beginning of page header */
  34921. u8 *data; /* Equal to pPage->aData */
  34922. BtShared *pBt; /* The main btree structure */
  34923. u16 usableSize; /* Amount of usable space on each page */
  34924. u16 cellOffset; /* Offset from start of page to first cell pointer */
  34925. u16 nFree; /* Number of unused bytes on the page */
  34926. u16 top; /* First byte of the cell content area */
  34927. pBt = pPage->pBt;
  34928. hdr = pPage->hdrOffset;
  34929. data = pPage->aData;
  34930. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  34931. assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
  34932. pPage->maskPage = pBt->pageSize - 1;
  34933. pPage->nOverflow = 0;
  34934. usableSize = pBt->usableSize;
  34935. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  34936. top = get2byte(&data[hdr+5]);
  34937. pPage->nCell = get2byte(&data[hdr+3]);
  34938. if( pPage->nCell>MX_CELL(pBt) ){
  34939. /* To many cells for a single page. The page must be corrupt */
  34940. return SQLITE_CORRUPT_BKPT;
  34941. }
  34942. /* Compute the total free space on the page */
  34943. pc = get2byte(&data[hdr+1]);
  34944. nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
  34945. while( pc>0 ){
  34946. u16 next, size;
  34947. if( pc>usableSize-4 ){
  34948. /* Free block is off the page */
  34949. return SQLITE_CORRUPT_BKPT;
  34950. }
  34951. next = get2byte(&data[pc]);
  34952. size = get2byte(&data[pc+2]);
  34953. if( next>0 && next<=pc+size+3 ){
  34954. /* Free blocks must be in accending order */
  34955. return SQLITE_CORRUPT_BKPT;
  34956. }
  34957. nFree += size;
  34958. pc = next;
  34959. }
  34960. pPage->nFree = (u16)nFree;
  34961. if( nFree>=usableSize ){
  34962. /* Free space cannot exceed total page size */
  34963. return SQLITE_CORRUPT_BKPT;
  34964. }
  34965. #if 0
  34966. /* Check that all the offsets in the cell offset array are within range.
  34967. **
  34968. ** Omitting this consistency check and using the pPage->maskPage mask
  34969. ** to prevent overrunning the page buffer in findCell() results in a
  34970. ** 2.5% performance gain.
  34971. */
  34972. {
  34973. u8 *pOff; /* Iterator used to check all cell offsets are in range */
  34974. u8 *pEnd; /* Pointer to end of cell offset array */
  34975. u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
  34976. mask = ~(((u8)(pBt->pageSize>>8))-1);
  34977. pEnd = &data[cellOffset + pPage->nCell*2];
  34978. for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
  34979. if( pOff!=pEnd ){
  34980. return SQLITE_CORRUPT_BKPT;
  34981. }
  34982. }
  34983. #endif
  34984. pPage->isInit = 1;
  34985. }
  34986. return SQLITE_OK;
  34987. }
  34988. /*
  34989. ** Set up a raw page so that it looks like a database page holding
  34990. ** no entries.
  34991. */
  34992. static void zeroPage(MemPage *pPage, int flags){
  34993. unsigned char *data = pPage->aData;
  34994. BtShared *pBt = pPage->pBt;
  34995. u8 hdr = pPage->hdrOffset;
  34996. u16 first;
  34997. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  34998. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  34999. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  35000. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  35001. assert( sqlite3_mutex_held(pBt->mutex) );
  35002. /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
  35003. data[hdr] = (char)flags;
  35004. first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  35005. memset(&data[hdr+1], 0, 4);
  35006. data[hdr+7] = 0;
  35007. put2byte(&data[hdr+5], pBt->usableSize);
  35008. pPage->nFree = pBt->usableSize - first;
  35009. decodeFlags(pPage, flags);
  35010. pPage->hdrOffset = hdr;
  35011. pPage->cellOffset = first;
  35012. pPage->nOverflow = 0;
  35013. assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
  35014. pPage->maskPage = pBt->pageSize - 1;
  35015. pPage->nCell = 0;
  35016. pPage->isInit = 1;
  35017. }
  35018. /*
  35019. ** Convert a DbPage obtained from the pager into a MemPage used by
  35020. ** the btree layer.
  35021. */
  35022. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  35023. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  35024. pPage->aData = sqlite3PagerGetData(pDbPage);
  35025. pPage->pDbPage = pDbPage;
  35026. pPage->pBt = pBt;
  35027. pPage->pgno = pgno;
  35028. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  35029. return pPage;
  35030. }
  35031. /*
  35032. ** Get a page from the pager. Initialize the MemPage.pBt and
  35033. ** MemPage.aData elements if needed.
  35034. **
  35035. ** If the noContent flag is set, it means that we do not care about
  35036. ** the content of the page at this time. So do not go to the disk
  35037. ** to fetch the content. Just fill in the content with zeros for now.
  35038. ** If in the future we call sqlite3PagerWrite() on this page, that
  35039. ** means we have started to be concerned about content and the disk
  35040. ** read should occur at that point.
  35041. */
  35042. SQLITE_PRIVATE int sqlite3BtreeGetPage(
  35043. BtShared *pBt, /* The btree */
  35044. Pgno pgno, /* Number of the page to fetch */
  35045. MemPage **ppPage, /* Return the page in this parameter */
  35046. int noContent /* Do not load page content if true */
  35047. ){
  35048. int rc;
  35049. DbPage *pDbPage;
  35050. assert( sqlite3_mutex_held(pBt->mutex) );
  35051. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
  35052. if( rc ) return rc;
  35053. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  35054. return SQLITE_OK;
  35055. }
  35056. /*
  35057. ** Return the size of the database file in pages. If there is any kind of
  35058. ** error, return ((unsigned int)-1).
  35059. */
  35060. static Pgno pagerPagecount(BtShared *pBt){
  35061. int nPage = -1;
  35062. int rc;
  35063. assert( pBt->pPage1 );
  35064. rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
  35065. assert( rc==SQLITE_OK || nPage==-1 );
  35066. return (Pgno)nPage;
  35067. }
  35068. /*
  35069. ** Get a page from the pager and initialize it. This routine
  35070. ** is just a convenience wrapper around separate calls to
  35071. ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
  35072. */
  35073. static int getAndInitPage(
  35074. BtShared *pBt, /* The database file */
  35075. Pgno pgno, /* Number of the page to get */
  35076. MemPage **ppPage /* Write the page pointer here */
  35077. ){
  35078. int rc;
  35079. DbPage *pDbPage;
  35080. MemPage *pPage;
  35081. assert( sqlite3_mutex_held(pBt->mutex) );
  35082. if( pgno==0 ){
  35083. return SQLITE_CORRUPT_BKPT;
  35084. }
  35085. /* It is often the case that the page we want is already in cache.
  35086. ** If so, get it directly. This saves us from having to call
  35087. ** pagerPagecount() to make sure pgno is within limits, which results
  35088. ** in a measureable performance improvements.
  35089. */
  35090. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  35091. if( pDbPage ){
  35092. /* Page is already in cache */
  35093. *ppPage = pPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  35094. rc = SQLITE_OK;
  35095. }else{
  35096. /* Page not in cache. Acquire it. */
  35097. if( pgno>pagerPagecount(pBt) ){
  35098. return SQLITE_CORRUPT_BKPT;
  35099. }
  35100. rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
  35101. if( rc ) return rc;
  35102. pPage = *ppPage;
  35103. }
  35104. if( !pPage->isInit ){
  35105. rc = sqlite3BtreeInitPage(pPage);
  35106. }
  35107. if( rc!=SQLITE_OK ){
  35108. releasePage(pPage);
  35109. *ppPage = 0;
  35110. }
  35111. return rc;
  35112. }
  35113. /*
  35114. ** Release a MemPage. This should be called once for each prior
  35115. ** call to sqlite3BtreeGetPage.
  35116. */
  35117. static void releasePage(MemPage *pPage){
  35118. if( pPage ){
  35119. assert( pPage->nOverflow==0 || sqlite3PagerPageRefcount(pPage->pDbPage)>1 );
  35120. assert( pPage->aData );
  35121. assert( pPage->pBt );
  35122. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  35123. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  35124. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  35125. sqlite3PagerUnref(pPage->pDbPage);
  35126. }
  35127. }
  35128. /*
  35129. ** During a rollback, when the pager reloads information into the cache
  35130. ** so that the cache is restored to its original state at the start of
  35131. ** the transaction, for each page restored this routine is called.
  35132. **
  35133. ** This routine needs to reset the extra data section at the end of the
  35134. ** page to agree with the restored data.
  35135. */
  35136. static void pageReinit(DbPage *pData){
  35137. MemPage *pPage;
  35138. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  35139. if( pPage->isInit ){
  35140. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  35141. pPage->isInit = 0;
  35142. if( sqlite3PagerPageRefcount(pData)>0 ){
  35143. sqlite3BtreeInitPage(pPage);
  35144. }
  35145. }
  35146. }
  35147. /*
  35148. ** Invoke the busy handler for a btree.
  35149. */
  35150. static int btreeInvokeBusyHandler(void *pArg){
  35151. BtShared *pBt = (BtShared*)pArg;
  35152. assert( pBt->db );
  35153. assert( sqlite3_mutex_held(pBt->db->mutex) );
  35154. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  35155. }
  35156. /*
  35157. ** Open a database file.
  35158. **
  35159. ** zFilename is the name of the database file. If zFilename is NULL
  35160. ** a new database with a random name is created. This randomly named
  35161. ** database file will be deleted when sqlite3BtreeClose() is called.
  35162. ** If zFilename is ":memory:" then an in-memory database is created
  35163. ** that is automatically destroyed when it is closed.
  35164. */
  35165. SQLITE_PRIVATE int sqlite3BtreeOpen(
  35166. const char *zFilename, /* Name of the file containing the BTree database */
  35167. sqlite3 *db, /* Associated database handle */
  35168. Btree **ppBtree, /* Pointer to new Btree object written here */
  35169. int flags, /* Options */
  35170. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  35171. ){
  35172. sqlite3_vfs *pVfs; /* The VFS to use for this btree */
  35173. BtShared *pBt = 0; /* Shared part of btree structure */
  35174. Btree *p; /* Handle to return */
  35175. int rc = SQLITE_OK;
  35176. u8 nReserve;
  35177. unsigned char zDbHeader[100];
  35178. /* Set the variable isMemdb to true for an in-memory database, or
  35179. ** false for a file-based database. This symbol is only required if
  35180. ** either of the shared-data or autovacuum features are compiled
  35181. ** into the library.
  35182. */
  35183. #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
  35184. #ifdef SQLITE_OMIT_MEMORYDB
  35185. const int isMemdb = 0;
  35186. #else
  35187. const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
  35188. #endif
  35189. #endif
  35190. assert( db!=0 );
  35191. assert( sqlite3_mutex_held(db->mutex) );
  35192. pVfs = db->pVfs;
  35193. p = sqlite3MallocZero(sizeof(Btree));
  35194. if( !p ){
  35195. return SQLITE_NOMEM;
  35196. }
  35197. p->inTrans = TRANS_NONE;
  35198. p->db = db;
  35199. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  35200. /*
  35201. ** If this Btree is a candidate for shared cache, try to find an
  35202. ** existing BtShared object that we can share with
  35203. */
  35204. if( isMemdb==0
  35205. && (db->flags & SQLITE_Vtab)==0
  35206. && zFilename && zFilename[0]
  35207. ){
  35208. if( sqlite3GlobalConfig.sharedCacheEnabled ){
  35209. int nFullPathname = pVfs->mxPathname+1;
  35210. char *zFullPathname = sqlite3Malloc(nFullPathname);
  35211. sqlite3_mutex *mutexShared;
  35212. p->sharable = 1;
  35213. db->flags |= SQLITE_SharedCache;
  35214. if( !zFullPathname ){
  35215. sqlite3_free(p);
  35216. return SQLITE_NOMEM;
  35217. }
  35218. sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
  35219. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  35220. sqlite3_mutex_enter(mutexShared);
  35221. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  35222. assert( pBt->nRef>0 );
  35223. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
  35224. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  35225. p->pBt = pBt;
  35226. pBt->nRef++;
  35227. break;
  35228. }
  35229. }
  35230. sqlite3_mutex_leave(mutexShared);
  35231. sqlite3_free(zFullPathname);
  35232. }
  35233. #ifdef SQLITE_DEBUG
  35234. else{
  35235. /* In debug mode, we mark all persistent databases as sharable
  35236. ** even when they are not. This exercises the locking code and
  35237. ** gives more opportunity for asserts(sqlite3_mutex_held())
  35238. ** statements to find locking problems.
  35239. */
  35240. p->sharable = 1;
  35241. }
  35242. #endif
  35243. }
  35244. #endif
  35245. if( pBt==0 ){
  35246. /*
  35247. ** The following asserts make sure that structures used by the btree are
  35248. ** the right size. This is to guard against size changes that result
  35249. ** when compiling on a different architecture.
  35250. */
  35251. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  35252. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  35253. assert( sizeof(u32)==4 );
  35254. assert( sizeof(u16)==2 );
  35255. assert( sizeof(Pgno)==4 );
  35256. pBt = sqlite3MallocZero( sizeof(*pBt) );
  35257. if( pBt==0 ){
  35258. rc = SQLITE_NOMEM;
  35259. goto btree_open_out;
  35260. }
  35261. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  35262. EXTRA_SIZE, flags, vfsFlags);
  35263. if( rc==SQLITE_OK ){
  35264. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  35265. }
  35266. if( rc!=SQLITE_OK ){
  35267. goto btree_open_out;
  35268. }
  35269. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  35270. p->pBt = pBt;
  35271. sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
  35272. pBt->pCursor = 0;
  35273. pBt->pPage1 = 0;
  35274. pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
  35275. pBt->pageSize = get2byte(&zDbHeader[16]);
  35276. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  35277. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  35278. pBt->pageSize = 0;
  35279. sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  35280. #ifndef SQLITE_OMIT_AUTOVACUUM
  35281. /* If the magic name ":memory:" will create an in-memory database, then
  35282. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  35283. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  35284. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  35285. ** regular file-name. In this case the auto-vacuum applies as per normal.
  35286. */
  35287. if( zFilename && !isMemdb ){
  35288. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  35289. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  35290. }
  35291. #endif
  35292. nReserve = 0;
  35293. }else{
  35294. nReserve = zDbHeader[20];
  35295. pBt->pageSizeFixed = 1;
  35296. #ifndef SQLITE_OMIT_AUTOVACUUM
  35297. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  35298. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  35299. #endif
  35300. }
  35301. pBt->usableSize = pBt->pageSize - nReserve;
  35302. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  35303. sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  35304. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  35305. /* Add the new BtShared object to the linked list sharable BtShareds.
  35306. */
  35307. if( p->sharable ){
  35308. sqlite3_mutex *mutexShared;
  35309. pBt->nRef = 1;
  35310. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  35311. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  35312. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  35313. if( pBt->mutex==0 ){
  35314. rc = SQLITE_NOMEM;
  35315. db->mallocFailed = 0;
  35316. goto btree_open_out;
  35317. }
  35318. }
  35319. sqlite3_mutex_enter(mutexShared);
  35320. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  35321. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  35322. sqlite3_mutex_leave(mutexShared);
  35323. }
  35324. #endif
  35325. }
  35326. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  35327. /* If the new Btree uses a sharable pBtShared, then link the new
  35328. ** Btree into the list of all sharable Btrees for the same connection.
  35329. ** The list is kept in ascending order by pBt address.
  35330. */
  35331. if( p->sharable ){
  35332. int i;
  35333. Btree *pSib;
  35334. for(i=0; i<db->nDb; i++){
  35335. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  35336. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  35337. if( p->pBt<pSib->pBt ){
  35338. p->pNext = pSib;
  35339. p->pPrev = 0;
  35340. pSib->pPrev = p;
  35341. }else{
  35342. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  35343. pSib = pSib->pNext;
  35344. }
  35345. p->pNext = pSib->pNext;
  35346. p->pPrev = pSib;
  35347. if( p->pNext ){
  35348. p->pNext->pPrev = p;
  35349. }
  35350. pSib->pNext = p;
  35351. }
  35352. break;
  35353. }
  35354. }
  35355. }
  35356. #endif
  35357. *ppBtree = p;
  35358. btree_open_out:
  35359. if( rc!=SQLITE_OK ){
  35360. if( pBt && pBt->pPager ){
  35361. sqlite3PagerClose(pBt->pPager);
  35362. }
  35363. sqlite3_free(pBt);
  35364. sqlite3_free(p);
  35365. *ppBtree = 0;
  35366. }
  35367. return rc;
  35368. }
  35369. /*
  35370. ** Decrement the BtShared.nRef counter. When it reaches zero,
  35371. ** remove the BtShared structure from the sharing list. Return
  35372. ** true if the BtShared.nRef counter reaches zero and return
  35373. ** false if it is still positive.
  35374. */
  35375. static int removeFromSharingList(BtShared *pBt){
  35376. #ifndef SQLITE_OMIT_SHARED_CACHE
  35377. sqlite3_mutex *pMaster;
  35378. BtShared *pList;
  35379. int removed = 0;
  35380. assert( sqlite3_mutex_notheld(pBt->mutex) );
  35381. pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  35382. sqlite3_mutex_enter(pMaster);
  35383. pBt->nRef--;
  35384. if( pBt->nRef<=0 ){
  35385. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  35386. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  35387. }else{
  35388. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  35389. while( ALWAYS(pList) && pList->pNext!=pBt ){
  35390. pList=pList->pNext;
  35391. }
  35392. if( ALWAYS(pList) ){
  35393. pList->pNext = pBt->pNext;
  35394. }
  35395. }
  35396. if( SQLITE_THREADSAFE ){
  35397. sqlite3_mutex_free(pBt->mutex);
  35398. }
  35399. removed = 1;
  35400. }
  35401. sqlite3_mutex_leave(pMaster);
  35402. return removed;
  35403. #else
  35404. return 1;
  35405. #endif
  35406. }
  35407. /*
  35408. ** Make sure pBt->pTmpSpace points to an allocation of
  35409. ** MX_CELL_SIZE(pBt) bytes.
  35410. */
  35411. static void allocateTempSpace(BtShared *pBt){
  35412. if( !pBt->pTmpSpace ){
  35413. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  35414. }
  35415. }
  35416. /*
  35417. ** Free the pBt->pTmpSpace allocation
  35418. */
  35419. static void freeTempSpace(BtShared *pBt){
  35420. sqlite3PageFree( pBt->pTmpSpace);
  35421. pBt->pTmpSpace = 0;
  35422. }
  35423. /*
  35424. ** Close an open database and invalidate all cursors.
  35425. */
  35426. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  35427. BtShared *pBt = p->pBt;
  35428. BtCursor *pCur;
  35429. /* Close all cursors opened via this handle. */
  35430. assert( sqlite3_mutex_held(p->db->mutex) );
  35431. sqlite3BtreeEnter(p);
  35432. pBt->db = p->db;
  35433. pCur = pBt->pCursor;
  35434. while( pCur ){
  35435. BtCursor *pTmp = pCur;
  35436. pCur = pCur->pNext;
  35437. if( pTmp->pBtree==p ){
  35438. sqlite3BtreeCloseCursor(pTmp);
  35439. }
  35440. }
  35441. /* Rollback any active transaction and free the handle structure.
  35442. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  35443. ** this handle.
  35444. */
  35445. sqlite3BtreeRollback(p);
  35446. sqlite3BtreeLeave(p);
  35447. /* If there are still other outstanding references to the shared-btree
  35448. ** structure, return now. The remainder of this procedure cleans
  35449. ** up the shared-btree.
  35450. */
  35451. assert( p->wantToLock==0 && p->locked==0 );
  35452. if( !p->sharable || removeFromSharingList(pBt) ){
  35453. /* The pBt is no longer on the sharing list, so we can access
  35454. ** it without having to hold the mutex.
  35455. **
  35456. ** Clean out and delete the BtShared object.
  35457. */
  35458. assert( !pBt->pCursor );
  35459. sqlite3PagerClose(pBt->pPager);
  35460. if( pBt->xFreeSchema && pBt->pSchema ){
  35461. pBt->xFreeSchema(pBt->pSchema);
  35462. }
  35463. sqlite3_free(pBt->pSchema);
  35464. freeTempSpace(pBt);
  35465. sqlite3_free(pBt);
  35466. }
  35467. #ifndef SQLITE_OMIT_SHARED_CACHE
  35468. assert( p->wantToLock==0 );
  35469. assert( p->locked==0 );
  35470. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  35471. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  35472. #endif
  35473. sqlite3_free(p);
  35474. return SQLITE_OK;
  35475. }
  35476. /*
  35477. ** Change the limit on the number of pages allowed in the cache.
  35478. **
  35479. ** The maximum number of cache pages is set to the absolute
  35480. ** value of mxPage. If mxPage is negative, the pager will
  35481. ** operate asynchronously - it will not stop to do fsync()s
  35482. ** to insure data is written to the disk surface before
  35483. ** continuing. Transactions still work if synchronous is off,
  35484. ** and the database cannot be corrupted if this program
  35485. ** crashes. But if the operating system crashes or there is
  35486. ** an abrupt power failure when synchronous is off, the database
  35487. ** could be left in an inconsistent and unrecoverable state.
  35488. ** Synchronous is on by default so database corruption is not
  35489. ** normally a worry.
  35490. */
  35491. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  35492. BtShared *pBt = p->pBt;
  35493. assert( sqlite3_mutex_held(p->db->mutex) );
  35494. sqlite3BtreeEnter(p);
  35495. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  35496. sqlite3BtreeLeave(p);
  35497. return SQLITE_OK;
  35498. }
  35499. /*
  35500. ** Change the way data is synced to disk in order to increase or decrease
  35501. ** how well the database resists damage due to OS crashes and power
  35502. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  35503. ** there is a high probability of damage) Level 2 is the default. There
  35504. ** is a very low but non-zero probability of damage. Level 3 reduces the
  35505. ** probability of damage to near zero but with a write performance reduction.
  35506. */
  35507. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  35508. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
  35509. BtShared *pBt = p->pBt;
  35510. assert( sqlite3_mutex_held(p->db->mutex) );
  35511. sqlite3BtreeEnter(p);
  35512. sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
  35513. sqlite3BtreeLeave(p);
  35514. return SQLITE_OK;
  35515. }
  35516. #endif
  35517. /*
  35518. ** Return TRUE if the given btree is set to safety level 1. In other
  35519. ** words, return TRUE if no sync() occurs on the disk files.
  35520. */
  35521. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  35522. BtShared *pBt = p->pBt;
  35523. int rc;
  35524. assert( sqlite3_mutex_held(p->db->mutex) );
  35525. sqlite3BtreeEnter(p);
  35526. assert( pBt && pBt->pPager );
  35527. rc = sqlite3PagerNosync(pBt->pPager);
  35528. sqlite3BtreeLeave(p);
  35529. return rc;
  35530. }
  35531. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  35532. /*
  35533. ** Change the default pages size and the number of reserved bytes per page.
  35534. **
  35535. ** The page size must be a power of 2 between 512 and 65536. If the page
  35536. ** size supplied does not meet this constraint then the page size is not
  35537. ** changed.
  35538. **
  35539. ** Page sizes are constrained to be a power of two so that the region
  35540. ** of the database file used for locking (beginning at PENDING_BYTE,
  35541. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  35542. ** at the beginning of a page.
  35543. **
  35544. ** If parameter nReserve is less than zero, then the number of reserved
  35545. ** bytes per page is left unchanged.
  35546. */
  35547. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
  35548. int rc = SQLITE_OK;
  35549. BtShared *pBt = p->pBt;
  35550. assert( nReserve>=-1 && nReserve<=255 );
  35551. sqlite3BtreeEnter(p);
  35552. if( pBt->pageSizeFixed ){
  35553. sqlite3BtreeLeave(p);
  35554. return SQLITE_READONLY;
  35555. }
  35556. if( nReserve<0 ){
  35557. nReserve = pBt->pageSize - pBt->usableSize;
  35558. }
  35559. assert( nReserve>=0 && nReserve<=255 );
  35560. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  35561. ((pageSize-1)&pageSize)==0 ){
  35562. assert( (pageSize & 7)==0 );
  35563. assert( !pBt->pPage1 && !pBt->pCursor );
  35564. pBt->pageSize = (u16)pageSize;
  35565. freeTempSpace(pBt);
  35566. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  35567. }
  35568. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  35569. sqlite3BtreeLeave(p);
  35570. return rc;
  35571. }
  35572. /*
  35573. ** Return the currently defined page size
  35574. */
  35575. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  35576. return p->pBt->pageSize;
  35577. }
  35578. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  35579. int n;
  35580. sqlite3BtreeEnter(p);
  35581. n = p->pBt->pageSize - p->pBt->usableSize;
  35582. sqlite3BtreeLeave(p);
  35583. return n;
  35584. }
  35585. /*
  35586. ** Set the maximum page count for a database if mxPage is positive.
  35587. ** No changes are made if mxPage is 0 or negative.
  35588. ** Regardless of the value of mxPage, return the maximum page count.
  35589. */
  35590. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  35591. int n;
  35592. sqlite3BtreeEnter(p);
  35593. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  35594. sqlite3BtreeLeave(p);
  35595. return n;
  35596. }
  35597. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  35598. /*
  35599. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  35600. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  35601. ** is disabled. The default value for the auto-vacuum property is
  35602. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  35603. */
  35604. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  35605. #ifdef SQLITE_OMIT_AUTOVACUUM
  35606. return SQLITE_READONLY;
  35607. #else
  35608. BtShared *pBt = p->pBt;
  35609. int rc = SQLITE_OK;
  35610. u8 av = autoVacuum ?1:0;
  35611. sqlite3BtreeEnter(p);
  35612. if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
  35613. rc = SQLITE_READONLY;
  35614. }else{
  35615. pBt->autoVacuum = av;
  35616. }
  35617. sqlite3BtreeLeave(p);
  35618. return rc;
  35619. #endif
  35620. }
  35621. /*
  35622. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  35623. ** enabled 1 is returned. Otherwise 0.
  35624. */
  35625. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  35626. #ifdef SQLITE_OMIT_AUTOVACUUM
  35627. return BTREE_AUTOVACUUM_NONE;
  35628. #else
  35629. int rc;
  35630. sqlite3BtreeEnter(p);
  35631. rc = (
  35632. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  35633. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  35634. BTREE_AUTOVACUUM_INCR
  35635. );
  35636. sqlite3BtreeLeave(p);
  35637. return rc;
  35638. #endif
  35639. }
  35640. /*
  35641. ** Get a reference to pPage1 of the database file. This will
  35642. ** also acquire a readlock on that file.
  35643. **
  35644. ** SQLITE_OK is returned on success. If the file is not a
  35645. ** well-formed database file, then SQLITE_CORRUPT is returned.
  35646. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  35647. ** is returned if we run out of memory.
  35648. */
  35649. static int lockBtree(BtShared *pBt){
  35650. int rc;
  35651. MemPage *pPage1;
  35652. int nPage;
  35653. assert( sqlite3_mutex_held(pBt->mutex) );
  35654. if( pBt->pPage1 ) return SQLITE_OK;
  35655. rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
  35656. if( rc!=SQLITE_OK ) return rc;
  35657. /* Do some checking to help insure the file we opened really is
  35658. ** a valid database file.
  35659. */
  35660. rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
  35661. if( rc!=SQLITE_OK ){
  35662. goto page1_init_failed;
  35663. }else if( nPage>0 ){
  35664. int pageSize;
  35665. int usableSize;
  35666. u8 *page1 = pPage1->aData;
  35667. rc = SQLITE_NOTADB;
  35668. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  35669. goto page1_init_failed;
  35670. }
  35671. if( page1[18]>1 ){
  35672. pBt->readOnly = 1;
  35673. }
  35674. if( page1[19]>1 ){
  35675. goto page1_init_failed;
  35676. }
  35677. /* The maximum embedded fraction must be exactly 25%. And the minimum
  35678. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  35679. ** The original design allowed these amounts to vary, but as of
  35680. ** version 3.6.0, we require them to be fixed.
  35681. */
  35682. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  35683. goto page1_init_failed;
  35684. }
  35685. pageSize = get2byte(&page1[16]);
  35686. if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
  35687. (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
  35688. ){
  35689. goto page1_init_failed;
  35690. }
  35691. assert( (pageSize & 7)==0 );
  35692. usableSize = pageSize - page1[20];
  35693. if( pageSize!=pBt->pageSize ){
  35694. /* After reading the first page of the database assuming a page size
  35695. ** of BtShared.pageSize, we have discovered that the page-size is
  35696. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  35697. ** zero and return SQLITE_OK. The caller will call this function
  35698. ** again with the correct page-size.
  35699. */
  35700. releasePage(pPage1);
  35701. pBt->usableSize = (u16)usableSize;
  35702. pBt->pageSize = (u16)pageSize;
  35703. freeTempSpace(pBt);
  35704. sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  35705. return SQLITE_OK;
  35706. }
  35707. if( usableSize<500 ){
  35708. goto page1_init_failed;
  35709. }
  35710. pBt->pageSize = (u16)pageSize;
  35711. pBt->usableSize = (u16)usableSize;
  35712. #ifndef SQLITE_OMIT_AUTOVACUUM
  35713. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  35714. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  35715. #endif
  35716. }
  35717. /* maxLocal is the maximum amount of payload to store locally for
  35718. ** a cell. Make sure it is small enough so that at least minFanout
  35719. ** cells can will fit on one page. We assume a 10-byte page header.
  35720. ** Besides the payload, the cell must store:
  35721. ** 2-byte pointer to the cell
  35722. ** 4-byte child pointer
  35723. ** 9-byte nKey value
  35724. ** 4-byte nData value
  35725. ** 4-byte overflow page pointer
  35726. ** So a cell consists of a 2-byte poiner, a header which is as much as
  35727. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  35728. ** page pointer.
  35729. */
  35730. pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
  35731. pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
  35732. pBt->maxLeaf = pBt->usableSize - 35;
  35733. pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
  35734. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  35735. pBt->pPage1 = pPage1;
  35736. return SQLITE_OK;
  35737. page1_init_failed:
  35738. releasePage(pPage1);
  35739. pBt->pPage1 = 0;
  35740. return rc;
  35741. }
  35742. /*
  35743. ** This routine works like lockBtree() except that it also invokes the
  35744. ** busy callback if there is lock contention.
  35745. */
  35746. static int lockBtreeWithRetry(Btree *pRef){
  35747. int rc = SQLITE_OK;
  35748. assert( sqlite3BtreeHoldsMutex(pRef) );
  35749. if( pRef->inTrans==TRANS_NONE ){
  35750. u8 inTransaction = pRef->pBt->inTransaction;
  35751. btreeIntegrity(pRef);
  35752. rc = sqlite3BtreeBeginTrans(pRef, 0);
  35753. pRef->pBt->inTransaction = inTransaction;
  35754. pRef->inTrans = TRANS_NONE;
  35755. if( rc==SQLITE_OK ){
  35756. pRef->pBt->nTransaction--;
  35757. }
  35758. btreeIntegrity(pRef);
  35759. }
  35760. return rc;
  35761. }
  35762. /*
  35763. ** If there are no outstanding cursors and we are not in the middle
  35764. ** of a transaction but there is a read lock on the database, then
  35765. ** this routine unrefs the first page of the database file which
  35766. ** has the effect of releasing the read lock.
  35767. **
  35768. ** If there are any outstanding cursors, this routine is a no-op.
  35769. **
  35770. ** If there is a transaction in progress, this routine is a no-op.
  35771. */
  35772. static void unlockBtreeIfUnused(BtShared *pBt){
  35773. assert( sqlite3_mutex_held(pBt->mutex) );
  35774. if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
  35775. if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
  35776. assert( pBt->pPage1->aData );
  35777. #if 0
  35778. if( pBt->pPage1->aData==0 ){
  35779. MemPage *pPage = pBt->pPage1;
  35780. pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
  35781. pPage->pBt = pBt;
  35782. pPage->pgno = 1;
  35783. }
  35784. #endif
  35785. releasePage(pBt->pPage1);
  35786. }
  35787. pBt->pPage1 = 0;
  35788. pBt->inStmt = 0;
  35789. }
  35790. }
  35791. /*
  35792. ** Create a new database by initializing the first page of the
  35793. ** file.
  35794. */
  35795. static int newDatabase(BtShared *pBt){
  35796. MemPage *pP1;
  35797. unsigned char *data;
  35798. int rc;
  35799. int nPage;
  35800. assert( sqlite3_mutex_held(pBt->mutex) );
  35801. rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
  35802. if( rc!=SQLITE_OK || nPage>0 ){
  35803. return rc;
  35804. }
  35805. pP1 = pBt->pPage1;
  35806. assert( pP1!=0 );
  35807. data = pP1->aData;
  35808. rc = sqlite3PagerWrite(pP1->pDbPage);
  35809. if( rc ) return rc;
  35810. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  35811. assert( sizeof(zMagicHeader)==16 );
  35812. put2byte(&data[16], pBt->pageSize);
  35813. data[18] = 1;
  35814. data[19] = 1;
  35815. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  35816. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  35817. data[21] = 64;
  35818. data[22] = 32;
  35819. data[23] = 32;
  35820. memset(&data[24], 0, 100-24);
  35821. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  35822. pBt->pageSizeFixed = 1;
  35823. #ifndef SQLITE_OMIT_AUTOVACUUM
  35824. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  35825. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  35826. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  35827. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  35828. #endif
  35829. return SQLITE_OK;
  35830. }
  35831. /*
  35832. ** Attempt to start a new transaction. A write-transaction
  35833. ** is started if the second argument is nonzero, otherwise a read-
  35834. ** transaction. If the second argument is 2 or more and exclusive
  35835. ** transaction is started, meaning that no other process is allowed
  35836. ** to access the database. A preexisting transaction may not be
  35837. ** upgraded to exclusive by calling this routine a second time - the
  35838. ** exclusivity flag only works for a new transaction.
  35839. **
  35840. ** A write-transaction must be started before attempting any
  35841. ** changes to the database. None of the following routines
  35842. ** will work unless a transaction is started first:
  35843. **
  35844. ** sqlite3BtreeCreateTable()
  35845. ** sqlite3BtreeCreateIndex()
  35846. ** sqlite3BtreeClearTable()
  35847. ** sqlite3BtreeDropTable()
  35848. ** sqlite3BtreeInsert()
  35849. ** sqlite3BtreeDelete()
  35850. ** sqlite3BtreeUpdateMeta()
  35851. **
  35852. ** If an initial attempt to acquire the lock fails because of lock contention
  35853. ** and the database was previously unlocked, then invoke the busy handler
  35854. ** if there is one. But if there was previously a read-lock, do not
  35855. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  35856. ** returned when there is already a read-lock in order to avoid a deadlock.
  35857. **
  35858. ** Suppose there are two processes A and B. A has a read lock and B has
  35859. ** a reserved lock. B tries to promote to exclusive but is blocked because
  35860. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  35861. ** One or the other of the two processes must give way or there can be
  35862. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  35863. ** when A already has a read lock, we encourage A to give up and let B
  35864. ** proceed.
  35865. */
  35866. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  35867. BtShared *pBt = p->pBt;
  35868. int rc = SQLITE_OK;
  35869. sqlite3BtreeEnter(p);
  35870. pBt->db = p->db;
  35871. btreeIntegrity(p);
  35872. /* If the btree is already in a write-transaction, or it
  35873. ** is already in a read-transaction and a read-transaction
  35874. ** is requested, this is a no-op.
  35875. */
  35876. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  35877. goto trans_begun;
  35878. }
  35879. /* Write transactions are not possible on a read-only database */
  35880. if( pBt->readOnly && wrflag ){
  35881. rc = SQLITE_READONLY;
  35882. goto trans_begun;
  35883. }
  35884. /* If another database handle has already opened a write transaction
  35885. ** on this shared-btree structure and a second write transaction is
  35886. ** requested, return SQLITE_BUSY.
  35887. */
  35888. if( pBt->inTransaction==TRANS_WRITE && wrflag ){
  35889. rc = SQLITE_BUSY;
  35890. goto trans_begun;
  35891. }
  35892. #ifndef SQLITE_OMIT_SHARED_CACHE
  35893. if( wrflag>1 ){
  35894. BtLock *pIter;
  35895. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  35896. if( pIter->pBtree!=p ){
  35897. rc = SQLITE_BUSY;
  35898. goto trans_begun;
  35899. }
  35900. }
  35901. }
  35902. #endif
  35903. do {
  35904. if( pBt->pPage1==0 ){
  35905. do{
  35906. rc = lockBtree(pBt);
  35907. }while( pBt->pPage1==0 && rc==SQLITE_OK );
  35908. }
  35909. if( rc==SQLITE_OK && wrflag ){
  35910. if( pBt->readOnly ){
  35911. rc = SQLITE_READONLY;
  35912. }else{
  35913. rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
  35914. if( rc==SQLITE_OK ){
  35915. rc = newDatabase(pBt);
  35916. }
  35917. }
  35918. }
  35919. if( rc==SQLITE_OK ){
  35920. if( wrflag ) pBt->inStmt = 0;
  35921. }else{
  35922. unlockBtreeIfUnused(pBt);
  35923. }
  35924. }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  35925. btreeInvokeBusyHandler(pBt) );
  35926. if( rc==SQLITE_OK ){
  35927. if( p->inTrans==TRANS_NONE ){
  35928. pBt->nTransaction++;
  35929. }
  35930. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  35931. if( p->inTrans>pBt->inTransaction ){
  35932. pBt->inTransaction = p->inTrans;
  35933. }
  35934. #ifndef SQLITE_OMIT_SHARED_CACHE
  35935. if( wrflag>1 ){
  35936. assert( !pBt->pExclusive );
  35937. pBt->pExclusive = p;
  35938. }
  35939. #endif
  35940. }
  35941. trans_begun:
  35942. if( rc==SQLITE_OK && wrflag ){
  35943. /* This call makes sure that the pager has the correct number of
  35944. ** open savepoints. If the second parameter is greater than 0 and
  35945. ** the sub-journal is not already open, then it will be opened here.
  35946. */
  35947. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  35948. }
  35949. btreeIntegrity(p);
  35950. sqlite3BtreeLeave(p);
  35951. return rc;
  35952. }
  35953. #ifndef SQLITE_OMIT_AUTOVACUUM
  35954. /*
  35955. ** Set the pointer-map entries for all children of page pPage. Also, if
  35956. ** pPage contains cells that point to overflow pages, set the pointer
  35957. ** map entries for the overflow pages as well.
  35958. */
  35959. static int setChildPtrmaps(MemPage *pPage){
  35960. int i; /* Counter variable */
  35961. int nCell; /* Number of cells in page pPage */
  35962. int rc; /* Return code */
  35963. BtShared *pBt = pPage->pBt;
  35964. u8 isInitOrig = pPage->isInit;
  35965. Pgno pgno = pPage->pgno;
  35966. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  35967. rc = sqlite3BtreeInitPage(pPage);
  35968. if( rc!=SQLITE_OK ){
  35969. goto set_child_ptrmaps_out;
  35970. }
  35971. nCell = pPage->nCell;
  35972. for(i=0; i<nCell; i++){
  35973. u8 *pCell = findCell(pPage, i);
  35974. rc = ptrmapPutOvflPtr(pPage, pCell);
  35975. if( rc!=SQLITE_OK ){
  35976. goto set_child_ptrmaps_out;
  35977. }
  35978. if( !pPage->leaf ){
  35979. Pgno childPgno = get4byte(pCell);
  35980. rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
  35981. if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
  35982. }
  35983. }
  35984. if( !pPage->leaf ){
  35985. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  35986. rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
  35987. }
  35988. set_child_ptrmaps_out:
  35989. pPage->isInit = isInitOrig;
  35990. return rc;
  35991. }
  35992. /*
  35993. ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
  35994. ** page, is a pointer to page iFrom. Modify this pointer so that it points to
  35995. ** iTo. Parameter eType describes the type of pointer to be modified, as
  35996. ** follows:
  35997. **
  35998. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  35999. ** page of pPage.
  36000. **
  36001. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  36002. ** page pointed to by one of the cells on pPage.
  36003. **
  36004. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  36005. ** overflow page in the list.
  36006. */
  36007. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  36008. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  36009. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  36010. if( eType==PTRMAP_OVERFLOW2 ){
  36011. /* The pointer is always the first 4 bytes of the page in this case. */
  36012. if( get4byte(pPage->aData)!=iFrom ){
  36013. return SQLITE_CORRUPT_BKPT;
  36014. }
  36015. put4byte(pPage->aData, iTo);
  36016. }else{
  36017. u8 isInitOrig = pPage->isInit;
  36018. int i;
  36019. int nCell;
  36020. sqlite3BtreeInitPage(pPage);
  36021. nCell = pPage->nCell;
  36022. for(i=0; i<nCell; i++){
  36023. u8 *pCell = findCell(pPage, i);
  36024. if( eType==PTRMAP_OVERFLOW1 ){
  36025. CellInfo info;
  36026. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  36027. if( info.iOverflow ){
  36028. if( iFrom==get4byte(&pCell[info.iOverflow]) ){
  36029. put4byte(&pCell[info.iOverflow], iTo);
  36030. break;
  36031. }
  36032. }
  36033. }else{
  36034. if( get4byte(pCell)==iFrom ){
  36035. put4byte(pCell, iTo);
  36036. break;
  36037. }
  36038. }
  36039. }
  36040. if( i==nCell ){
  36041. if( eType!=PTRMAP_BTREE ||
  36042. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  36043. return SQLITE_CORRUPT_BKPT;
  36044. }
  36045. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  36046. }
  36047. pPage->isInit = isInitOrig;
  36048. }
  36049. return SQLITE_OK;
  36050. }
  36051. /*
  36052. ** Move the open database page pDbPage to location iFreePage in the
  36053. ** database. The pDbPage reference remains valid.
  36054. */
  36055. static int relocatePage(
  36056. BtShared *pBt, /* Btree */
  36057. MemPage *pDbPage, /* Open page to move */
  36058. u8 eType, /* Pointer map 'type' entry for pDbPage */
  36059. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  36060. Pgno iFreePage, /* The location to move pDbPage to */
  36061. int isCommit
  36062. ){
  36063. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  36064. Pgno iDbPage = pDbPage->pgno;
  36065. Pager *pPager = pBt->pPager;
  36066. int rc;
  36067. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  36068. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  36069. assert( sqlite3_mutex_held(pBt->mutex) );
  36070. assert( pDbPage->pBt==pBt );
  36071. /* Move page iDbPage from its current location to page number iFreePage */
  36072. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  36073. iDbPage, iFreePage, iPtrPage, eType));
  36074. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  36075. if( rc!=SQLITE_OK ){
  36076. return rc;
  36077. }
  36078. pDbPage->pgno = iFreePage;
  36079. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  36080. ** that point to overflow pages. The pointer map entries for all these
  36081. ** pages need to be changed.
  36082. **
  36083. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  36084. ** pointer to a subsequent overflow page. If this is the case, then
  36085. ** the pointer map needs to be updated for the subsequent overflow page.
  36086. */
  36087. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  36088. rc = setChildPtrmaps(pDbPage);
  36089. if( rc!=SQLITE_OK ){
  36090. return rc;
  36091. }
  36092. }else{
  36093. Pgno nextOvfl = get4byte(pDbPage->aData);
  36094. if( nextOvfl!=0 ){
  36095. rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
  36096. if( rc!=SQLITE_OK ){
  36097. return rc;
  36098. }
  36099. }
  36100. }
  36101. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  36102. ** that it points at iFreePage. Also fix the pointer map entry for
  36103. ** iPtrPage.
  36104. */
  36105. if( eType!=PTRMAP_ROOTPAGE ){
  36106. rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  36107. if( rc!=SQLITE_OK ){
  36108. return rc;
  36109. }
  36110. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  36111. if( rc!=SQLITE_OK ){
  36112. releasePage(pPtrPage);
  36113. return rc;
  36114. }
  36115. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  36116. releasePage(pPtrPage);
  36117. if( rc==SQLITE_OK ){
  36118. rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
  36119. }
  36120. }
  36121. return rc;
  36122. }
  36123. /* Forward declaration required by incrVacuumStep(). */
  36124. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  36125. /*
  36126. ** Perform a single step of an incremental-vacuum. If successful,
  36127. ** return SQLITE_OK. If there is no work to do (and therefore no
  36128. ** point in calling this function again), return SQLITE_DONE.
  36129. **
  36130. ** More specificly, this function attempts to re-organize the
  36131. ** database so that the last page of the file currently in use
  36132. ** is no longer in use.
  36133. **
  36134. ** If the nFin parameter is non-zero, the implementation assumes
  36135. ** that the caller will keep calling incrVacuumStep() until
  36136. ** it returns SQLITE_DONE or an error, and that nFin is the
  36137. ** number of pages the database file will contain after this
  36138. ** process is complete.
  36139. */
  36140. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
  36141. Pgno nFreeList; /* Number of pages still on the free-list */
  36142. assert( sqlite3_mutex_held(pBt->mutex) );
  36143. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  36144. int rc;
  36145. u8 eType;
  36146. Pgno iPtrPage;
  36147. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  36148. if( nFreeList==0 || nFin==iLastPg ){
  36149. return SQLITE_DONE;
  36150. }
  36151. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  36152. if( rc!=SQLITE_OK ){
  36153. return rc;
  36154. }
  36155. if( eType==PTRMAP_ROOTPAGE ){
  36156. return SQLITE_CORRUPT_BKPT;
  36157. }
  36158. if( eType==PTRMAP_FREEPAGE ){
  36159. if( nFin==0 ){
  36160. /* Remove the page from the files free-list. This is not required
  36161. ** if nFin is non-zero. In that case, the free-list will be
  36162. ** truncated to zero after this function returns, so it doesn't
  36163. ** matter if it still contains some garbage entries.
  36164. */
  36165. Pgno iFreePg;
  36166. MemPage *pFreePg;
  36167. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
  36168. if( rc!=SQLITE_OK ){
  36169. return rc;
  36170. }
  36171. assert( iFreePg==iLastPg );
  36172. releasePage(pFreePg);
  36173. }
  36174. } else {
  36175. Pgno iFreePg; /* Index of free page to move pLastPg to */
  36176. MemPage *pLastPg;
  36177. rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
  36178. if( rc!=SQLITE_OK ){
  36179. return rc;
  36180. }
  36181. /* If nFin is zero, this loop runs exactly once and page pLastPg
  36182. ** is swapped with the first free page pulled off the free list.
  36183. **
  36184. ** On the other hand, if nFin is greater than zero, then keep
  36185. ** looping until a free-page located within the first nFin pages
  36186. ** of the file is found.
  36187. */
  36188. do {
  36189. MemPage *pFreePg;
  36190. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
  36191. if( rc!=SQLITE_OK ){
  36192. releasePage(pLastPg);
  36193. return rc;
  36194. }
  36195. releasePage(pFreePg);
  36196. }while( nFin!=0 && iFreePg>nFin );
  36197. assert( iFreePg<iLastPg );
  36198. rc = sqlite3PagerWrite(pLastPg->pDbPage);
  36199. if( rc==SQLITE_OK ){
  36200. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
  36201. }
  36202. releasePage(pLastPg);
  36203. if( rc!=SQLITE_OK ){
  36204. return rc;
  36205. }
  36206. }
  36207. }
  36208. if( nFin==0 ){
  36209. iLastPg--;
  36210. while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
  36211. iLastPg--;
  36212. }
  36213. sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
  36214. }
  36215. return SQLITE_OK;
  36216. }
  36217. /*
  36218. ** A write-transaction must be opened before calling this function.
  36219. ** It performs a single unit of work towards an incremental vacuum.
  36220. **
  36221. ** If the incremental vacuum is finished after this function has run,
  36222. ** SQLITE_DONE is returned. If it is not finished, but no error occured,
  36223. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  36224. */
  36225. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  36226. int rc;
  36227. BtShared *pBt = p->pBt;
  36228. sqlite3BtreeEnter(p);
  36229. pBt->db = p->db;
  36230. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  36231. if( !pBt->autoVacuum ){
  36232. rc = SQLITE_DONE;
  36233. }else{
  36234. invalidateAllOverflowCache(pBt);
  36235. rc = incrVacuumStep(pBt, 0, sqlite3PagerImageSize(pBt->pPager));
  36236. }
  36237. sqlite3BtreeLeave(p);
  36238. return rc;
  36239. }
  36240. /*
  36241. ** This routine is called prior to sqlite3PagerCommit when a transaction
  36242. ** is commited for an auto-vacuum database.
  36243. **
  36244. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  36245. ** the database file should be truncated to during the commit process.
  36246. ** i.e. the database has been reorganized so that only the first *pnTrunc
  36247. ** pages are in use.
  36248. */
  36249. static int autoVacuumCommit(BtShared *pBt){
  36250. int rc = SQLITE_OK;
  36251. Pager *pPager = pBt->pPager;
  36252. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  36253. assert( sqlite3_mutex_held(pBt->mutex) );
  36254. invalidateAllOverflowCache(pBt);
  36255. assert(pBt->autoVacuum);
  36256. if( !pBt->incrVacuum ){
  36257. Pgno nFin;
  36258. Pgno nFree;
  36259. Pgno nPtrmap;
  36260. Pgno iFree;
  36261. const int pgsz = pBt->pageSize;
  36262. Pgno nOrig = pagerPagecount(pBt);
  36263. if( PTRMAP_ISPAGE(pBt, nOrig) ){
  36264. return SQLITE_CORRUPT_BKPT;
  36265. }
  36266. if( nOrig==PENDING_BYTE_PAGE(pBt) ){
  36267. nOrig--;
  36268. }
  36269. nFree = get4byte(&pBt->pPage1->aData[36]);
  36270. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
  36271. nFin = nOrig - nFree - nPtrmap;
  36272. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
  36273. nFin--;
  36274. }
  36275. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  36276. nFin--;
  36277. }
  36278. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  36279. rc = incrVacuumStep(pBt, nFin, iFree);
  36280. }
  36281. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  36282. rc = SQLITE_OK;
  36283. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  36284. put4byte(&pBt->pPage1->aData[32], 0);
  36285. put4byte(&pBt->pPage1->aData[36], 0);
  36286. sqlite3PagerTruncateImage(pBt->pPager, nFin);
  36287. }
  36288. if( rc!=SQLITE_OK ){
  36289. sqlite3PagerRollback(pPager);
  36290. }
  36291. }
  36292. assert( nRef==sqlite3PagerRefcount(pPager) );
  36293. return rc;
  36294. }
  36295. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  36296. /*
  36297. ** This routine does the first phase of a two-phase commit. This routine
  36298. ** causes a rollback journal to be created (if it does not already exist)
  36299. ** and populated with enough information so that if a power loss occurs
  36300. ** the database can be restored to its original state by playing back
  36301. ** the journal. Then the contents of the journal are flushed out to
  36302. ** the disk. After the journal is safely on oxide, the changes to the
  36303. ** database are written into the database file and flushed to oxide.
  36304. ** At the end of this call, the rollback journal still exists on the
  36305. ** disk and we are still holding all locks, so the transaction has not
  36306. ** committed. See sqlite3BtreeCommit() for the second phase of the
  36307. ** commit process.
  36308. **
  36309. ** This call is a no-op if no write-transaction is currently active on pBt.
  36310. **
  36311. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  36312. ** the name of a master journal file that should be written into the
  36313. ** individual journal file, or is NULL, indicating no master journal file
  36314. ** (single database transaction).
  36315. **
  36316. ** When this is called, the master journal should already have been
  36317. ** created, populated with this journal pointer and synced to disk.
  36318. **
  36319. ** Once this is routine has returned, the only thing required to commit
  36320. ** the write-transaction for this database file is to delete the journal.
  36321. */
  36322. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  36323. int rc = SQLITE_OK;
  36324. if( p->inTrans==TRANS_WRITE ){
  36325. BtShared *pBt = p->pBt;
  36326. sqlite3BtreeEnter(p);
  36327. pBt->db = p->db;
  36328. #ifndef SQLITE_OMIT_AUTOVACUUM
  36329. if( pBt->autoVacuum ){
  36330. rc = autoVacuumCommit(pBt);
  36331. if( rc!=SQLITE_OK ){
  36332. sqlite3BtreeLeave(p);
  36333. return rc;
  36334. }
  36335. }
  36336. #endif
  36337. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  36338. sqlite3BtreeLeave(p);
  36339. }
  36340. return rc;
  36341. }
  36342. /*
  36343. ** Commit the transaction currently in progress.
  36344. **
  36345. ** This routine implements the second phase of a 2-phase commit. The
  36346. ** sqlite3BtreeSync() routine does the first phase and should be invoked
  36347. ** prior to calling this routine. The sqlite3BtreeSync() routine did
  36348. ** all the work of writing information out to disk and flushing the
  36349. ** contents so that they are written onto the disk platter. All this
  36350. ** routine has to do is delete or truncate the rollback journal
  36351. ** (which causes the transaction to commit) and drop locks.
  36352. **
  36353. ** This will release the write lock on the database file. If there
  36354. ** are no active cursors, it also releases the read lock.
  36355. */
  36356. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
  36357. BtShared *pBt = p->pBt;
  36358. sqlite3BtreeEnter(p);
  36359. pBt->db = p->db;
  36360. btreeIntegrity(p);
  36361. /* If the handle has a write-transaction open, commit the shared-btrees
  36362. ** transaction and set the shared state to TRANS_READ.
  36363. */
  36364. if( p->inTrans==TRANS_WRITE ){
  36365. int rc;
  36366. assert( pBt->inTransaction==TRANS_WRITE );
  36367. assert( pBt->nTransaction>0 );
  36368. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  36369. if( rc!=SQLITE_OK ){
  36370. sqlite3BtreeLeave(p);
  36371. return rc;
  36372. }
  36373. pBt->inTransaction = TRANS_READ;
  36374. pBt->inStmt = 0;
  36375. }
  36376. unlockAllTables(p);
  36377. /* If the handle has any kind of transaction open, decrement the transaction
  36378. ** count of the shared btree. If the transaction count reaches 0, set
  36379. ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
  36380. ** will unlock the pager.
  36381. */
  36382. if( p->inTrans!=TRANS_NONE ){
  36383. pBt->nTransaction--;
  36384. if( 0==pBt->nTransaction ){
  36385. pBt->inTransaction = TRANS_NONE;
  36386. }
  36387. }
  36388. /* Set the handles current transaction state to TRANS_NONE and unlock
  36389. ** the pager if this call closed the only read or write transaction.
  36390. */
  36391. p->inTrans = TRANS_NONE;
  36392. unlockBtreeIfUnused(pBt);
  36393. btreeIntegrity(p);
  36394. sqlite3BtreeLeave(p);
  36395. return SQLITE_OK;
  36396. }
  36397. /*
  36398. ** Do both phases of a commit.
  36399. */
  36400. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  36401. int rc;
  36402. sqlite3BtreeEnter(p);
  36403. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  36404. if( rc==SQLITE_OK ){
  36405. rc = sqlite3BtreeCommitPhaseTwo(p);
  36406. }
  36407. sqlite3BtreeLeave(p);
  36408. return rc;
  36409. }
  36410. #ifndef NDEBUG
  36411. /*
  36412. ** Return the number of write-cursors open on this handle. This is for use
  36413. ** in assert() expressions, so it is only compiled if NDEBUG is not
  36414. ** defined.
  36415. **
  36416. ** For the purposes of this routine, a write-cursor is any cursor that
  36417. ** is capable of writing to the databse. That means the cursor was
  36418. ** originally opened for writing and the cursor has not be disabled
  36419. ** by having its state changed to CURSOR_FAULT.
  36420. */
  36421. static int countWriteCursors(BtShared *pBt){
  36422. BtCursor *pCur;
  36423. int r = 0;
  36424. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  36425. if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
  36426. }
  36427. return r;
  36428. }
  36429. #endif
  36430. /*
  36431. ** This routine sets the state to CURSOR_FAULT and the error
  36432. ** code to errCode for every cursor on BtShared that pBtree
  36433. ** references.
  36434. **
  36435. ** Every cursor is tripped, including cursors that belong
  36436. ** to other database connections that happen to be sharing
  36437. ** the cache with pBtree.
  36438. **
  36439. ** This routine gets called when a rollback occurs.
  36440. ** All cursors using the same cache must be tripped
  36441. ** to prevent them from trying to use the btree after
  36442. ** the rollback. The rollback may have deleted tables
  36443. ** or moved root pages, so it is not sufficient to
  36444. ** save the state of the cursor. The cursor must be
  36445. ** invalidated.
  36446. */
  36447. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  36448. BtCursor *p;
  36449. sqlite3BtreeEnter(pBtree);
  36450. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  36451. int i;
  36452. sqlite3BtreeClearCursor(p);
  36453. p->eState = CURSOR_FAULT;
  36454. p->skip = errCode;
  36455. for(i=0; i<=p->iPage; i++){
  36456. releasePage(p->apPage[i]);
  36457. p->apPage[i] = 0;
  36458. }
  36459. }
  36460. sqlite3BtreeLeave(pBtree);
  36461. }
  36462. /*
  36463. ** Rollback the transaction in progress. All cursors will be
  36464. ** invalided by this operation. Any attempt to use a cursor
  36465. ** that was open at the beginning of this operation will result
  36466. ** in an error.
  36467. **
  36468. ** This will release the write lock on the database file. If there
  36469. ** are no active cursors, it also releases the read lock.
  36470. */
  36471. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
  36472. int rc;
  36473. BtShared *pBt = p->pBt;
  36474. MemPage *pPage1;
  36475. sqlite3BtreeEnter(p);
  36476. pBt->db = p->db;
  36477. rc = saveAllCursors(pBt, 0, 0);
  36478. #ifndef SQLITE_OMIT_SHARED_CACHE
  36479. if( rc!=SQLITE_OK ){
  36480. /* This is a horrible situation. An IO or malloc() error occured whilst
  36481. ** trying to save cursor positions. If this is an automatic rollback (as
  36482. ** the result of a constraint, malloc() failure or IO error) then
  36483. ** the cache may be internally inconsistent (not contain valid trees) so
  36484. ** we cannot simply return the error to the caller. Instead, abort
  36485. ** all queries that may be using any of the cursors that failed to save.
  36486. */
  36487. sqlite3BtreeTripAllCursors(p, rc);
  36488. }
  36489. #endif
  36490. btreeIntegrity(p);
  36491. unlockAllTables(p);
  36492. if( p->inTrans==TRANS_WRITE ){
  36493. int rc2;
  36494. assert( TRANS_WRITE==pBt->inTransaction );
  36495. rc2 = sqlite3PagerRollback(pBt->pPager);
  36496. if( rc2!=SQLITE_OK ){
  36497. rc = rc2;
  36498. }
  36499. /* The rollback may have destroyed the pPage1->aData value. So
  36500. ** call sqlite3BtreeGetPage() on page 1 again to make
  36501. ** sure pPage1->aData is set correctly. */
  36502. if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  36503. releasePage(pPage1);
  36504. }
  36505. assert( countWriteCursors(pBt)==0 );
  36506. pBt->inTransaction = TRANS_READ;
  36507. }
  36508. if( p->inTrans!=TRANS_NONE ){
  36509. assert( pBt->nTransaction>0 );
  36510. pBt->nTransaction--;
  36511. if( 0==pBt->nTransaction ){
  36512. pBt->inTransaction = TRANS_NONE;
  36513. }
  36514. }
  36515. p->inTrans = TRANS_NONE;
  36516. pBt->inStmt = 0;
  36517. unlockBtreeIfUnused(pBt);
  36518. btreeIntegrity(p);
  36519. sqlite3BtreeLeave(p);
  36520. return rc;
  36521. }
  36522. /*
  36523. ** Start a statement subtransaction. The subtransaction can
  36524. ** can be rolled back independently of the main transaction.
  36525. ** You must start a transaction before starting a subtransaction.
  36526. ** The subtransaction is ended automatically if the main transaction
  36527. ** commits or rolls back.
  36528. **
  36529. ** Only one subtransaction may be active at a time. It is an error to try
  36530. ** to start a new subtransaction if another subtransaction is already active.
  36531. **
  36532. ** Statement subtransactions are used around individual SQL statements
  36533. ** that are contained within a BEGIN...COMMIT block. If a constraint
  36534. ** error occurs within the statement, the effect of that one statement
  36535. ** can be rolled back without having to rollback the entire transaction.
  36536. */
  36537. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){
  36538. int rc;
  36539. BtShared *pBt = p->pBt;
  36540. sqlite3BtreeEnter(p);
  36541. pBt->db = p->db;
  36542. assert( p->inTrans==TRANS_WRITE );
  36543. assert( !pBt->inStmt );
  36544. assert( pBt->readOnly==0 );
  36545. if( NEVER(p->inTrans!=TRANS_WRITE || pBt->inStmt || pBt->readOnly) ){
  36546. rc = SQLITE_INTERNAL;
  36547. }else{
  36548. assert( pBt->inTransaction==TRANS_WRITE );
  36549. /* At the pager level, a statement transaction is a savepoint with
  36550. ** an index greater than all savepoints created explicitly using
  36551. ** SQL statements. It is illegal to open, release or rollback any
  36552. ** such savepoints while the statement transaction savepoint is active.
  36553. */
  36554. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint+1);
  36555. pBt->inStmt = 1;
  36556. }
  36557. sqlite3BtreeLeave(p);
  36558. return rc;
  36559. }
  36560. /*
  36561. ** Commit the statment subtransaction currently in progress. If no
  36562. ** subtransaction is active, this is a no-op.
  36563. */
  36564. SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){
  36565. int rc;
  36566. BtShared *pBt = p->pBt;
  36567. sqlite3BtreeEnter(p);
  36568. pBt->db = p->db;
  36569. assert( pBt->readOnly==0 );
  36570. if( pBt->inStmt ){
  36571. int iStmtpoint = p->db->nSavepoint;
  36572. rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_RELEASE, iStmtpoint);
  36573. }else{
  36574. rc = SQLITE_OK;
  36575. }
  36576. pBt->inStmt = 0;
  36577. sqlite3BtreeLeave(p);
  36578. return rc;
  36579. }
  36580. /*
  36581. ** Rollback the active statement subtransaction. If no subtransaction
  36582. ** is active this routine is a no-op.
  36583. **
  36584. ** All cursors will be invalidated by this operation. Any attempt
  36585. ** to use a cursor that was open at the beginning of this operation
  36586. ** will result in an error.
  36587. */
  36588. SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){
  36589. int rc = SQLITE_OK;
  36590. BtShared *pBt = p->pBt;
  36591. sqlite3BtreeEnter(p);
  36592. pBt->db = p->db;
  36593. assert( pBt->readOnly==0 );
  36594. if( pBt->inStmt ){
  36595. int iStmtpoint = p->db->nSavepoint;
  36596. rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_ROLLBACK, iStmtpoint);
  36597. if( rc==SQLITE_OK ){
  36598. rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_RELEASE, iStmtpoint);
  36599. }
  36600. pBt->inStmt = 0;
  36601. }
  36602. sqlite3BtreeLeave(p);
  36603. return rc;
  36604. }
  36605. /*
  36606. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  36607. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  36608. ** savepoint identified by parameter iSavepoint, depending on the value
  36609. ** of op.
  36610. **
  36611. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  36612. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  36613. ** contents of the entire transaction are rolled back. This is different
  36614. ** from a normal transaction rollback, as no locks are released and the
  36615. ** transaction remains open.
  36616. */
  36617. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  36618. int rc = SQLITE_OK;
  36619. if( p && p->inTrans==TRANS_WRITE ){
  36620. BtShared *pBt = p->pBt;
  36621. assert( pBt->inStmt==0 );
  36622. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  36623. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  36624. sqlite3BtreeEnter(p);
  36625. pBt->db = p->db;
  36626. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  36627. if( rc==SQLITE_OK ){
  36628. rc = newDatabase(pBt);
  36629. }
  36630. sqlite3BtreeLeave(p);
  36631. }
  36632. return rc;
  36633. }
  36634. /*
  36635. ** Create a new cursor for the BTree whose root is on the page
  36636. ** iTable. The act of acquiring a cursor gets a read lock on
  36637. ** the database file.
  36638. **
  36639. ** If wrFlag==0, then the cursor can only be used for reading.
  36640. ** If wrFlag==1, then the cursor can be used for reading or for
  36641. ** writing if other conditions for writing are also met. These
  36642. ** are the conditions that must be met in order for writing to
  36643. ** be allowed:
  36644. **
  36645. ** 1: The cursor must have been opened with wrFlag==1
  36646. **
  36647. ** 2: Other database connections that share the same pager cache
  36648. ** but which are not in the READ_UNCOMMITTED state may not have
  36649. ** cursors open with wrFlag==0 on the same table. Otherwise
  36650. ** the changes made by this write cursor would be visible to
  36651. ** the read cursors in the other database connection.
  36652. **
  36653. ** 3: The database must be writable (not on read-only media)
  36654. **
  36655. ** 4: There must be an active transaction.
  36656. **
  36657. ** No checking is done to make sure that page iTable really is the
  36658. ** root page of a b-tree. If it is not, then the cursor acquired
  36659. ** will not work correctly.
  36660. **
  36661. ** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
  36662. ** pointed to by pCur have been zeroed by the caller.
  36663. */
  36664. static int btreeCursor(
  36665. Btree *p, /* The btree */
  36666. int iTable, /* Root page of table to open */
  36667. int wrFlag, /* 1 to write. 0 read-only */
  36668. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  36669. BtCursor *pCur /* Space for new cursor */
  36670. ){
  36671. int rc;
  36672. Pgno nPage;
  36673. BtShared *pBt = p->pBt;
  36674. assert( sqlite3BtreeHoldsMutex(p) );
  36675. assert( wrFlag==0 || wrFlag==1 );
  36676. if( wrFlag ){
  36677. assert( !pBt->readOnly );
  36678. if( NEVER(pBt->readOnly) ){
  36679. return SQLITE_READONLY;
  36680. }
  36681. if( checkReadLocks(p, iTable, 0, 0) ){
  36682. return SQLITE_LOCKED;
  36683. }
  36684. }
  36685. if( pBt->pPage1==0 ){
  36686. rc = lockBtreeWithRetry(p);
  36687. if( rc!=SQLITE_OK ){
  36688. return rc;
  36689. }
  36690. }
  36691. pCur->pgnoRoot = (Pgno)iTable;
  36692. rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage);
  36693. if( rc!=SQLITE_OK ){
  36694. return rc;
  36695. }
  36696. if( iTable==1 && nPage==0 ){
  36697. rc = SQLITE_EMPTY;
  36698. goto create_cursor_exception;
  36699. }
  36700. rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
  36701. if( rc!=SQLITE_OK ){
  36702. goto create_cursor_exception;
  36703. }
  36704. /* Now that no other errors can occur, finish filling in the BtCursor
  36705. ** variables, link the cursor into the BtShared list and set *ppCur (the
  36706. ** output argument to this function).
  36707. */
  36708. pCur->pKeyInfo = pKeyInfo;
  36709. pCur->pBtree = p;
  36710. pCur->pBt = pBt;
  36711. pCur->wrFlag = (u8)wrFlag;
  36712. pCur->pNext = pBt->pCursor;
  36713. if( pCur->pNext ){
  36714. pCur->pNext->pPrev = pCur;
  36715. }
  36716. pBt->pCursor = pCur;
  36717. pCur->eState = CURSOR_INVALID;
  36718. return SQLITE_OK;
  36719. create_cursor_exception:
  36720. releasePage(pCur->apPage[0]);
  36721. unlockBtreeIfUnused(pBt);
  36722. return rc;
  36723. }
  36724. SQLITE_PRIVATE int sqlite3BtreeCursor(
  36725. Btree *p, /* The btree */
  36726. int iTable, /* Root page of table to open */
  36727. int wrFlag, /* 1 to write. 0 read-only */
  36728. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  36729. BtCursor *pCur /* Write new cursor here */
  36730. ){
  36731. int rc;
  36732. sqlite3BtreeEnter(p);
  36733. p->pBt->db = p->db;
  36734. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  36735. sqlite3BtreeLeave(p);
  36736. return rc;
  36737. }
  36738. SQLITE_PRIVATE int sqlite3BtreeCursorSize(){
  36739. return sizeof(BtCursor);
  36740. }
  36741. /*
  36742. ** Close a cursor. The read lock on the database file is released
  36743. ** when the last cursor is closed.
  36744. */
  36745. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  36746. Btree *pBtree = pCur->pBtree;
  36747. if( pBtree ){
  36748. int i;
  36749. BtShared *pBt = pCur->pBt;
  36750. sqlite3BtreeEnter(pBtree);
  36751. pBt->db = pBtree->db;
  36752. sqlite3BtreeClearCursor(pCur);
  36753. if( pCur->pPrev ){
  36754. pCur->pPrev->pNext = pCur->pNext;
  36755. }else{
  36756. pBt->pCursor = pCur->pNext;
  36757. }
  36758. if( pCur->pNext ){
  36759. pCur->pNext->pPrev = pCur->pPrev;
  36760. }
  36761. for(i=0; i<=pCur->iPage; i++){
  36762. releasePage(pCur->apPage[i]);
  36763. }
  36764. unlockBtreeIfUnused(pBt);
  36765. invalidateOverflowCache(pCur);
  36766. /* sqlite3_free(pCur); */
  36767. sqlite3BtreeLeave(pBtree);
  36768. }
  36769. return SQLITE_OK;
  36770. }
  36771. /*
  36772. ** Make a temporary cursor by filling in the fields of pTempCur.
  36773. ** The temporary cursor is not on the cursor list for the Btree.
  36774. */
  36775. SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
  36776. int i;
  36777. assert( cursorHoldsMutex(pCur) );
  36778. memcpy(pTempCur, pCur, sizeof(BtCursor));
  36779. pTempCur->pNext = 0;
  36780. pTempCur->pPrev = 0;
  36781. for(i=0; i<=pTempCur->iPage; i++){
  36782. sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
  36783. }
  36784. assert( pTempCur->pKey==0 );
  36785. }
  36786. /*
  36787. ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
  36788. ** function above.
  36789. */
  36790. SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
  36791. int i;
  36792. assert( cursorHoldsMutex(pCur) );
  36793. for(i=0; i<=pCur->iPage; i++){
  36794. sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
  36795. }
  36796. sqlite3_free(pCur->pKey);
  36797. }
  36798. /*
  36799. ** Make sure the BtCursor* given in the argument has a valid
  36800. ** BtCursor.info structure. If it is not already valid, call
  36801. ** sqlite3BtreeParseCell() to fill it in.
  36802. **
  36803. ** BtCursor.info is a cache of the information in the current cell.
  36804. ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
  36805. **
  36806. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  36807. ** compiler to crash when getCellInfo() is implemented as a macro.
  36808. ** But there is a measureable speed advantage to using the macro on gcc
  36809. ** (when less compiler optimizations like -Os or -O0 are used and the
  36810. ** compiler is not doing agressive inlining.) So we use a real function
  36811. ** for MSVC and a macro for everything else. Ticket #2457.
  36812. */
  36813. #ifndef NDEBUG
  36814. static void assertCellInfo(BtCursor *pCur){
  36815. CellInfo info;
  36816. int iPage = pCur->iPage;
  36817. memset(&info, 0, sizeof(info));
  36818. sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  36819. assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  36820. }
  36821. #else
  36822. #define assertCellInfo(x)
  36823. #endif
  36824. #ifdef _MSC_VER
  36825. /* Use a real function in MSVC to work around bugs in that compiler. */
  36826. static void getCellInfo(BtCursor *pCur){
  36827. if( pCur->info.nSize==0 ){
  36828. int iPage = pCur->iPage;
  36829. sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  36830. pCur->validNKey = 1;
  36831. }else{
  36832. assertCellInfo(pCur);
  36833. }
  36834. }
  36835. #else /* if not _MSC_VER */
  36836. /* Use a macro in all other compilers so that the function is inlined */
  36837. #define getCellInfo(pCur) \
  36838. if( pCur->info.nSize==0 ){ \
  36839. int iPage = pCur->iPage; \
  36840. sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  36841. pCur->validNKey = 1; \
  36842. }else{ \
  36843. assertCellInfo(pCur); \
  36844. }
  36845. #endif /* _MSC_VER */
  36846. /*
  36847. ** Set *pSize to the size of the buffer needed to hold the value of
  36848. ** the key for the current entry. If the cursor is not pointing
  36849. ** to a valid entry, *pSize is set to 0.
  36850. **
  36851. ** For a table with the INTKEY flag set, this routine returns the key
  36852. ** itself, not the number of bytes in the key.
  36853. */
  36854. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  36855. int rc;
  36856. assert( cursorHoldsMutex(pCur) );
  36857. rc = restoreCursorPosition(pCur);
  36858. if( rc==SQLITE_OK ){
  36859. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  36860. if( pCur->eState==CURSOR_INVALID ){
  36861. *pSize = 0;
  36862. }else{
  36863. getCellInfo(pCur);
  36864. *pSize = pCur->info.nKey;
  36865. }
  36866. }
  36867. return rc;
  36868. }
  36869. /*
  36870. ** Set *pSize to the number of bytes of data in the entry the
  36871. ** cursor currently points to. Always return SQLITE_OK.
  36872. ** Failure is not possible. If the cursor is not currently
  36873. ** pointing to an entry (which can happen, for example, if
  36874. ** the database is empty) then *pSize is set to 0.
  36875. */
  36876. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  36877. int rc;
  36878. assert( cursorHoldsMutex(pCur) );
  36879. rc = restoreCursorPosition(pCur);
  36880. if( rc==SQLITE_OK ){
  36881. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  36882. if( pCur->eState==CURSOR_INVALID ){
  36883. /* Not pointing at a valid entry - set *pSize to 0. */
  36884. *pSize = 0;
  36885. }else{
  36886. getCellInfo(pCur);
  36887. *pSize = pCur->info.nData;
  36888. }
  36889. }
  36890. return rc;
  36891. }
  36892. /*
  36893. ** Given the page number of an overflow page in the database (parameter
  36894. ** ovfl), this function finds the page number of the next page in the
  36895. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  36896. ** pointer-map data instead of reading the content of page ovfl to do so.
  36897. **
  36898. ** If an error occurs an SQLite error code is returned. Otherwise:
  36899. **
  36900. ** Unless pPgnoNext is NULL, the page number of the next overflow
  36901. ** page in the linked list is written to *pPgnoNext. If page ovfl
  36902. ** is the last page in its linked list, *pPgnoNext is set to zero.
  36903. **
  36904. ** If ppPage is not NULL, *ppPage is set to the MemPage* handle
  36905. ** for page ovfl. The underlying pager page may have been requested
  36906. ** with the noContent flag set, so the page data accessable via
  36907. ** this handle may not be trusted.
  36908. */
  36909. static int getOverflowPage(
  36910. BtShared *pBt,
  36911. Pgno ovfl, /* Overflow page */
  36912. MemPage **ppPage, /* OUT: MemPage handle */
  36913. Pgno *pPgnoNext /* OUT: Next overflow page number */
  36914. ){
  36915. Pgno next = 0;
  36916. int rc = SQLITE_OK;
  36917. assert( sqlite3_mutex_held(pBt->mutex) );
  36918. /* One of these must not be NULL. Otherwise, why call this function? */
  36919. assert(ppPage || pPgnoNext);
  36920. /* If pPgnoNext is NULL, then this function is being called to obtain
  36921. ** a MemPage* reference only. No page-data is required in this case.
  36922. */
  36923. if( !pPgnoNext ){
  36924. return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
  36925. }
  36926. #ifndef SQLITE_OMIT_AUTOVACUUM
  36927. /* Try to find the next page in the overflow list using the
  36928. ** autovacuum pointer-map pages. Guess that the next page in
  36929. ** the overflow list is page number (ovfl+1). If that guess turns
  36930. ** out to be wrong, fall back to loading the data of page
  36931. ** number ovfl to determine the next page number.
  36932. */
  36933. if( pBt->autoVacuum ){
  36934. Pgno pgno;
  36935. Pgno iGuess = ovfl+1;
  36936. u8 eType;
  36937. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  36938. iGuess++;
  36939. }
  36940. if( iGuess<=pagerPagecount(pBt) ){
  36941. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  36942. if( rc!=SQLITE_OK ){
  36943. return rc;
  36944. }
  36945. if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  36946. next = iGuess;
  36947. }
  36948. }
  36949. }
  36950. #endif
  36951. if( next==0 || ppPage ){
  36952. MemPage *pPage = 0;
  36953. rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
  36954. assert(rc==SQLITE_OK || pPage==0);
  36955. if( next==0 && rc==SQLITE_OK ){
  36956. next = get4byte(pPage->aData);
  36957. }
  36958. if( ppPage ){
  36959. *ppPage = pPage;
  36960. }else{
  36961. releasePage(pPage);
  36962. }
  36963. }
  36964. *pPgnoNext = next;
  36965. return rc;
  36966. }
  36967. /*
  36968. ** Copy data from a buffer to a page, or from a page to a buffer.
  36969. **
  36970. ** pPayload is a pointer to data stored on database page pDbPage.
  36971. ** If argument eOp is false, then nByte bytes of data are copied
  36972. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  36973. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  36974. ** of data are copied from the buffer pBuf to pPayload.
  36975. **
  36976. ** SQLITE_OK is returned on success, otherwise an error code.
  36977. */
  36978. static int copyPayload(
  36979. void *pPayload, /* Pointer to page data */
  36980. void *pBuf, /* Pointer to buffer */
  36981. int nByte, /* Number of bytes to copy */
  36982. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  36983. DbPage *pDbPage /* Page containing pPayload */
  36984. ){
  36985. if( eOp ){
  36986. /* Copy data from buffer to page (a write operation) */
  36987. int rc = sqlite3PagerWrite(pDbPage);
  36988. if( rc!=SQLITE_OK ){
  36989. return rc;
  36990. }
  36991. memcpy(pPayload, pBuf, nByte);
  36992. }else{
  36993. /* Copy data from page to buffer (a read operation) */
  36994. memcpy(pBuf, pPayload, nByte);
  36995. }
  36996. return SQLITE_OK;
  36997. }
  36998. /*
  36999. ** This function is used to read or overwrite payload information
  37000. ** for the entry that the pCur cursor is pointing to. If the eOp
  37001. ** parameter is 0, this is a read operation (data copied into
  37002. ** buffer pBuf). If it is non-zero, a write (data copied from
  37003. ** buffer pBuf).
  37004. **
  37005. ** A total of "amt" bytes are read or written beginning at "offset".
  37006. ** Data is read to or from the buffer pBuf.
  37007. **
  37008. ** This routine does not make a distinction between key and data.
  37009. ** It just reads or writes bytes from the payload area. Data might
  37010. ** appear on the main page or be scattered out on multiple overflow
  37011. ** pages.
  37012. **
  37013. ** If the BtCursor.isIncrblobHandle flag is set, and the current
  37014. ** cursor entry uses one or more overflow pages, this function
  37015. ** allocates space for and lazily popluates the overflow page-list
  37016. ** cache array (BtCursor.aOverflow). Subsequent calls use this
  37017. ** cache to make seeking to the supplied offset more efficient.
  37018. **
  37019. ** Once an overflow page-list cache has been allocated, it may be
  37020. ** invalidated if some other cursor writes to the same table, or if
  37021. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  37022. ** mode, the following events may invalidate an overflow page-list cache.
  37023. **
  37024. ** * An incremental vacuum,
  37025. ** * A commit in auto_vacuum="full" mode,
  37026. ** * Creating a table (may require moving an overflow page).
  37027. */
  37028. static int accessPayload(
  37029. BtCursor *pCur, /* Cursor pointing to entry to read from */
  37030. u32 offset, /* Begin reading this far into payload */
  37031. u32 amt, /* Read this many bytes */
  37032. unsigned char *pBuf, /* Write the bytes into this buffer */
  37033. int skipKey, /* offset begins at data if this is true */
  37034. int eOp /* zero to read. non-zero to write. */
  37035. ){
  37036. unsigned char *aPayload;
  37037. int rc = SQLITE_OK;
  37038. u32 nKey;
  37039. int iIdx = 0;
  37040. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  37041. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  37042. assert( pPage );
  37043. assert( pCur->eState==CURSOR_VALID );
  37044. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  37045. assert( cursorHoldsMutex(pCur) );
  37046. getCellInfo(pCur);
  37047. aPayload = pCur->info.pCell + pCur->info.nHeader;
  37048. nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
  37049. if( skipKey ){
  37050. offset += nKey;
  37051. }
  37052. if( offset+amt > nKey+pCur->info.nData
  37053. || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  37054. ){
  37055. /* Trying to read or write past the end of the data is an error */
  37056. return SQLITE_CORRUPT_BKPT;
  37057. }
  37058. /* Check if data must be read/written to/from the btree page itself. */
  37059. if( offset<pCur->info.nLocal ){
  37060. int a = amt;
  37061. if( a+offset>pCur->info.nLocal ){
  37062. a = pCur->info.nLocal - offset;
  37063. }
  37064. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  37065. offset = 0;
  37066. pBuf += a;
  37067. amt -= a;
  37068. }else{
  37069. offset -= pCur->info.nLocal;
  37070. }
  37071. if( rc==SQLITE_OK && amt>0 ){
  37072. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  37073. Pgno nextPage;
  37074. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  37075. #ifndef SQLITE_OMIT_INCRBLOB
  37076. /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
  37077. ** has not been allocated, allocate it now. The array is sized at
  37078. ** one entry for each overflow page in the overflow chain. The
  37079. ** page number of the first overflow page is stored in aOverflow[0],
  37080. ** etc. A value of 0 in the aOverflow[] array means "not yet known"
  37081. ** (the cache is lazily populated).
  37082. */
  37083. if( pCur->isIncrblobHandle && !pCur->aOverflow ){
  37084. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  37085. pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
  37086. if( nOvfl && !pCur->aOverflow ){
  37087. rc = SQLITE_NOMEM;
  37088. }
  37089. }
  37090. /* If the overflow page-list cache has been allocated and the
  37091. ** entry for the first required overflow page is valid, skip
  37092. ** directly to it.
  37093. */
  37094. if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
  37095. iIdx = (offset/ovflSize);
  37096. nextPage = pCur->aOverflow[iIdx];
  37097. offset = (offset%ovflSize);
  37098. }
  37099. #endif
  37100. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  37101. #ifndef SQLITE_OMIT_INCRBLOB
  37102. /* If required, populate the overflow page-list cache. */
  37103. if( pCur->aOverflow ){
  37104. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  37105. pCur->aOverflow[iIdx] = nextPage;
  37106. }
  37107. #endif
  37108. if( offset>=ovflSize ){
  37109. /* The only reason to read this page is to obtain the page
  37110. ** number for the next page in the overflow chain. The page
  37111. ** data is not required. So first try to lookup the overflow
  37112. ** page-list cache, if any, then fall back to the getOverflowPage()
  37113. ** function.
  37114. */
  37115. #ifndef SQLITE_OMIT_INCRBLOB
  37116. if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
  37117. nextPage = pCur->aOverflow[iIdx+1];
  37118. } else
  37119. #endif
  37120. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  37121. offset -= ovflSize;
  37122. }else{
  37123. /* Need to read this page properly. It contains some of the
  37124. ** range of data that is being read (eOp==0) or written (eOp!=0).
  37125. */
  37126. DbPage *pDbPage;
  37127. int a = amt;
  37128. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
  37129. if( rc==SQLITE_OK ){
  37130. aPayload = sqlite3PagerGetData(pDbPage);
  37131. nextPage = get4byte(aPayload);
  37132. if( a + offset > ovflSize ){
  37133. a = ovflSize - offset;
  37134. }
  37135. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  37136. sqlite3PagerUnref(pDbPage);
  37137. offset = 0;
  37138. amt -= a;
  37139. pBuf += a;
  37140. }
  37141. }
  37142. }
  37143. }
  37144. if( rc==SQLITE_OK && amt>0 ){
  37145. return SQLITE_CORRUPT_BKPT;
  37146. }
  37147. return rc;
  37148. }
  37149. /*
  37150. ** Read part of the key associated with cursor pCur. Exactly
  37151. ** "amt" bytes will be transfered into pBuf[]. The transfer
  37152. ** begins at "offset".
  37153. **
  37154. ** Return SQLITE_OK on success or an error code if anything goes
  37155. ** wrong. An error is returned if "offset+amt" is larger than
  37156. ** the available payload.
  37157. */
  37158. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  37159. int rc;
  37160. assert( cursorHoldsMutex(pCur) );
  37161. rc = restoreCursorPosition(pCur);
  37162. if( rc==SQLITE_OK ){
  37163. assert( pCur->eState==CURSOR_VALID );
  37164. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  37165. if( pCur->apPage[0]->intKey ){
  37166. return SQLITE_CORRUPT_BKPT;
  37167. }
  37168. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  37169. rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
  37170. }
  37171. return rc;
  37172. }
  37173. /*
  37174. ** Read part of the data associated with cursor pCur. Exactly
  37175. ** "amt" bytes will be transfered into pBuf[]. The transfer
  37176. ** begins at "offset".
  37177. **
  37178. ** Return SQLITE_OK on success or an error code if anything goes
  37179. ** wrong. An error is returned if "offset+amt" is larger than
  37180. ** the available payload.
  37181. */
  37182. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  37183. int rc;
  37184. #ifndef SQLITE_OMIT_INCRBLOB
  37185. if ( pCur->eState==CURSOR_INVALID ){
  37186. return SQLITE_ABORT;
  37187. }
  37188. #endif
  37189. assert( cursorHoldsMutex(pCur) );
  37190. rc = restoreCursorPosition(pCur);
  37191. if( rc==SQLITE_OK ){
  37192. assert( pCur->eState==CURSOR_VALID );
  37193. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  37194. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  37195. rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
  37196. }
  37197. return rc;
  37198. }
  37199. /*
  37200. ** Return a pointer to payload information from the entry that the
  37201. ** pCur cursor is pointing to. The pointer is to the beginning of
  37202. ** the key if skipKey==0 and it points to the beginning of data if
  37203. ** skipKey==1. The number of bytes of available key/data is written
  37204. ** into *pAmt. If *pAmt==0, then the value returned will not be
  37205. ** a valid pointer.
  37206. **
  37207. ** This routine is an optimization. It is common for the entire key
  37208. ** and data to fit on the local page and for there to be no overflow
  37209. ** pages. When that is so, this routine can be used to access the
  37210. ** key and data without making a copy. If the key and/or data spills
  37211. ** onto overflow pages, then accessPayload() must be used to reassembly
  37212. ** the key/data and copy it into a preallocated buffer.
  37213. **
  37214. ** The pointer returned by this routine looks directly into the cached
  37215. ** page of the database. The data might change or move the next time
  37216. ** any btree routine is called.
  37217. */
  37218. static const unsigned char *fetchPayload(
  37219. BtCursor *pCur, /* Cursor pointing to entry to read from */
  37220. int *pAmt, /* Write the number of available bytes here */
  37221. int skipKey /* read beginning at data if this is true */
  37222. ){
  37223. unsigned char *aPayload;
  37224. MemPage *pPage;
  37225. u32 nKey;
  37226. u32 nLocal;
  37227. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  37228. assert( pCur->eState==CURSOR_VALID );
  37229. assert( cursorHoldsMutex(pCur) );
  37230. pPage = pCur->apPage[pCur->iPage];
  37231. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  37232. getCellInfo(pCur);
  37233. aPayload = pCur->info.pCell;
  37234. aPayload += pCur->info.nHeader;
  37235. if( pPage->intKey ){
  37236. nKey = 0;
  37237. }else{
  37238. nKey = (int)pCur->info.nKey;
  37239. }
  37240. if( skipKey ){
  37241. aPayload += nKey;
  37242. nLocal = pCur->info.nLocal - nKey;
  37243. }else{
  37244. nLocal = pCur->info.nLocal;
  37245. if( nLocal>nKey ){
  37246. nLocal = nKey;
  37247. }
  37248. }
  37249. *pAmt = nLocal;
  37250. return aPayload;
  37251. }
  37252. /*
  37253. ** For the entry that cursor pCur is point to, return as
  37254. ** many bytes of the key or data as are available on the local
  37255. ** b-tree page. Write the number of available bytes into *pAmt.
  37256. **
  37257. ** The pointer returned is ephemeral. The key/data may move
  37258. ** or be destroyed on the next call to any Btree routine,
  37259. ** including calls from other threads against the same cache.
  37260. ** Hence, a mutex on the BtShared should be held prior to calling
  37261. ** this routine.
  37262. **
  37263. ** These routines is used to get quick access to key and data
  37264. ** in the common case where no overflow pages are used.
  37265. */
  37266. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  37267. assert( cursorHoldsMutex(pCur) );
  37268. if( pCur->eState==CURSOR_VALID ){
  37269. return (const void*)fetchPayload(pCur, pAmt, 0);
  37270. }
  37271. return 0;
  37272. }
  37273. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  37274. assert( cursorHoldsMutex(pCur) );
  37275. if( pCur->eState==CURSOR_VALID ){
  37276. return (const void*)fetchPayload(pCur, pAmt, 1);
  37277. }
  37278. return 0;
  37279. }
  37280. /*
  37281. ** Move the cursor down to a new child page. The newPgno argument is the
  37282. ** page number of the child page to move to.
  37283. */
  37284. static int moveToChild(BtCursor *pCur, u32 newPgno){
  37285. int rc;
  37286. int i = pCur->iPage;
  37287. MemPage *pNewPage;
  37288. BtShared *pBt = pCur->pBt;
  37289. assert( cursorHoldsMutex(pCur) );
  37290. assert( pCur->eState==CURSOR_VALID );
  37291. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  37292. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  37293. return SQLITE_CORRUPT_BKPT;
  37294. }
  37295. rc = getAndInitPage(pBt, newPgno, &pNewPage);
  37296. if( rc ) return rc;
  37297. pCur->apPage[i+1] = pNewPage;
  37298. pCur->aiIdx[i+1] = 0;
  37299. pCur->iPage++;
  37300. pCur->info.nSize = 0;
  37301. pCur->validNKey = 0;
  37302. if( pNewPage->nCell<1 ){
  37303. return SQLITE_CORRUPT_BKPT;
  37304. }
  37305. return SQLITE_OK;
  37306. }
  37307. #ifndef NDEBUG
  37308. /*
  37309. ** Page pParent is an internal (non-leaf) tree page. This function
  37310. ** asserts that page number iChild is the left-child if the iIdx'th
  37311. ** cell in page pParent. Or, if iIdx is equal to the total number of
  37312. ** cells in pParent, that page number iChild is the right-child of
  37313. ** the page.
  37314. */
  37315. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  37316. assert( iIdx<=pParent->nCell );
  37317. if( iIdx==pParent->nCell ){
  37318. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  37319. }else{
  37320. assert( get4byte(findCell(pParent, iIdx))==iChild );
  37321. }
  37322. }
  37323. #else
  37324. # define assertParentIndex(x,y,z)
  37325. #endif
  37326. /*
  37327. ** Move the cursor up to the parent page.
  37328. **
  37329. ** pCur->idx is set to the cell index that contains the pointer
  37330. ** to the page we are coming from. If we are coming from the
  37331. ** right-most child page then pCur->idx is set to one more than
  37332. ** the largest cell index.
  37333. */
  37334. SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
  37335. assert( cursorHoldsMutex(pCur) );
  37336. assert( pCur->eState==CURSOR_VALID );
  37337. assert( pCur->iPage>0 );
  37338. assert( pCur->apPage[pCur->iPage] );
  37339. assertParentIndex(
  37340. pCur->apPage[pCur->iPage-1],
  37341. pCur->aiIdx[pCur->iPage-1],
  37342. pCur->apPage[pCur->iPage]->pgno
  37343. );
  37344. releasePage(pCur->apPage[pCur->iPage]);
  37345. pCur->iPage--;
  37346. pCur->info.nSize = 0;
  37347. pCur->validNKey = 0;
  37348. }
  37349. /*
  37350. ** Move the cursor to the root page
  37351. */
  37352. static int moveToRoot(BtCursor *pCur){
  37353. MemPage *pRoot;
  37354. int rc = SQLITE_OK;
  37355. Btree *p = pCur->pBtree;
  37356. BtShared *pBt = p->pBt;
  37357. assert( cursorHoldsMutex(pCur) );
  37358. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  37359. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  37360. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  37361. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  37362. if( pCur->eState==CURSOR_FAULT ){
  37363. return pCur->skip;
  37364. }
  37365. sqlite3BtreeClearCursor(pCur);
  37366. }
  37367. if( pCur->iPage>=0 ){
  37368. int i;
  37369. for(i=1; i<=pCur->iPage; i++){
  37370. releasePage(pCur->apPage[i]);
  37371. }
  37372. }else{
  37373. if(
  37374. SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
  37375. ){
  37376. pCur->eState = CURSOR_INVALID;
  37377. return rc;
  37378. }
  37379. }
  37380. pRoot = pCur->apPage[0];
  37381. assert( pRoot->pgno==pCur->pgnoRoot );
  37382. pCur->iPage = 0;
  37383. pCur->aiIdx[0] = 0;
  37384. pCur->info.nSize = 0;
  37385. pCur->atLast = 0;
  37386. pCur->validNKey = 0;
  37387. if( pRoot->nCell==0 && !pRoot->leaf ){
  37388. Pgno subpage;
  37389. assert( pRoot->pgno==1 );
  37390. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  37391. assert( subpage>0 );
  37392. pCur->eState = CURSOR_VALID;
  37393. rc = moveToChild(pCur, subpage);
  37394. }else{
  37395. pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  37396. }
  37397. return rc;
  37398. }
  37399. /*
  37400. ** Move the cursor down to the left-most leaf entry beneath the
  37401. ** entry to which it is currently pointing.
  37402. **
  37403. ** The left-most leaf is the one with the smallest key - the first
  37404. ** in ascending order.
  37405. */
  37406. static int moveToLeftmost(BtCursor *pCur){
  37407. Pgno pgno;
  37408. int rc = SQLITE_OK;
  37409. MemPage *pPage;
  37410. assert( cursorHoldsMutex(pCur) );
  37411. assert( pCur->eState==CURSOR_VALID );
  37412. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  37413. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  37414. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  37415. rc = moveToChild(pCur, pgno);
  37416. }
  37417. return rc;
  37418. }
  37419. /*
  37420. ** Move the cursor down to the right-most leaf entry beneath the
  37421. ** page to which it is currently pointing. Notice the difference
  37422. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  37423. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  37424. ** finds the right-most entry beneath the *page*.
  37425. **
  37426. ** The right-most entry is the one with the largest key - the last
  37427. ** key in ascending order.
  37428. */
  37429. static int moveToRightmost(BtCursor *pCur){
  37430. Pgno pgno;
  37431. int rc = SQLITE_OK;
  37432. MemPage *pPage = 0;
  37433. assert( cursorHoldsMutex(pCur) );
  37434. assert( pCur->eState==CURSOR_VALID );
  37435. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  37436. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  37437. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  37438. rc = moveToChild(pCur, pgno);
  37439. }
  37440. if( rc==SQLITE_OK ){
  37441. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  37442. pCur->info.nSize = 0;
  37443. pCur->validNKey = 0;
  37444. }
  37445. return rc;
  37446. }
  37447. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  37448. ** on success. Set *pRes to 0 if the cursor actually points to something
  37449. ** or set *pRes to 1 if the table is empty.
  37450. */
  37451. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  37452. int rc;
  37453. assert( cursorHoldsMutex(pCur) );
  37454. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  37455. rc = moveToRoot(pCur);
  37456. if( rc==SQLITE_OK ){
  37457. if( pCur->eState==CURSOR_INVALID ){
  37458. assert( pCur->apPage[pCur->iPage]->nCell==0 );
  37459. *pRes = 1;
  37460. rc = SQLITE_OK;
  37461. }else{
  37462. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  37463. *pRes = 0;
  37464. rc = moveToLeftmost(pCur);
  37465. }
  37466. }
  37467. return rc;
  37468. }
  37469. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  37470. ** on success. Set *pRes to 0 if the cursor actually points to something
  37471. ** or set *pRes to 1 if the table is empty.
  37472. */
  37473. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  37474. int rc;
  37475. assert( cursorHoldsMutex(pCur) );
  37476. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  37477. rc = moveToRoot(pCur);
  37478. if( rc==SQLITE_OK ){
  37479. if( CURSOR_INVALID==pCur->eState ){
  37480. assert( pCur->apPage[pCur->iPage]->nCell==0 );
  37481. *pRes = 1;
  37482. }else{
  37483. assert( pCur->eState==CURSOR_VALID );
  37484. *pRes = 0;
  37485. rc = moveToRightmost(pCur);
  37486. getCellInfo(pCur);
  37487. pCur->atLast = rc==SQLITE_OK ?1:0;
  37488. }
  37489. }
  37490. return rc;
  37491. }
  37492. /* Move the cursor so that it points to an entry near the key
  37493. ** specified by pIdxKey or intKey. Return a success code.
  37494. **
  37495. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  37496. ** must be NULL. For index tables, pIdxKey is used and intKey
  37497. ** is ignored.
  37498. **
  37499. ** If an exact match is not found, then the cursor is always
  37500. ** left pointing at a leaf page which would hold the entry if it
  37501. ** were present. The cursor might point to an entry that comes
  37502. ** before or after the key.
  37503. **
  37504. ** An integer is written into *pRes which is the result of
  37505. ** comparing the key with the entry to which the cursor is
  37506. ** pointing. The meaning of the integer written into
  37507. ** *pRes is as follows:
  37508. **
  37509. ** *pRes<0 The cursor is left pointing at an entry that
  37510. ** is smaller than intKey/pIdxKey or if the table is empty
  37511. ** and the cursor is therefore left point to nothing.
  37512. **
  37513. ** *pRes==0 The cursor is left pointing at an entry that
  37514. ** exactly matches intKey/pIdxKey.
  37515. **
  37516. ** *pRes>0 The cursor is left pointing at an entry that
  37517. ** is larger than intKey/pIdxKey.
  37518. **
  37519. */
  37520. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  37521. BtCursor *pCur, /* The cursor to be moved */
  37522. UnpackedRecord *pIdxKey, /* Unpacked index key */
  37523. i64 intKey, /* The table key */
  37524. int biasRight, /* If true, bias the search to the high end */
  37525. int *pRes /* Write search results here */
  37526. ){
  37527. int rc;
  37528. assert( cursorHoldsMutex(pCur) );
  37529. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  37530. /* If the cursor is already positioned at the point we are trying
  37531. ** to move to, then just return without doing any work */
  37532. if( pCur->eState==CURSOR_VALID && pCur->validNKey
  37533. && pCur->apPage[0]->intKey
  37534. ){
  37535. if( pCur->info.nKey==intKey ){
  37536. *pRes = 0;
  37537. return SQLITE_OK;
  37538. }
  37539. if( pCur->atLast && pCur->info.nKey<intKey ){
  37540. *pRes = -1;
  37541. return SQLITE_OK;
  37542. }
  37543. }
  37544. rc = moveToRoot(pCur);
  37545. if( rc ){
  37546. return rc;
  37547. }
  37548. assert( pCur->apPage[pCur->iPage] );
  37549. assert( pCur->apPage[pCur->iPage]->isInit );
  37550. if( pCur->eState==CURSOR_INVALID ){
  37551. *pRes = -1;
  37552. assert( pCur->apPage[pCur->iPage]->nCell==0 );
  37553. return SQLITE_OK;
  37554. }
  37555. assert( pCur->apPage[0]->intKey || pIdxKey );
  37556. for(;;){
  37557. int lwr, upr;
  37558. Pgno chldPg;
  37559. MemPage *pPage = pCur->apPage[pCur->iPage];
  37560. int c = -1; /* pRes return if table is empty must be -1 */
  37561. lwr = 0;
  37562. upr = pPage->nCell-1;
  37563. if( (!pPage->intKey && pIdxKey==0) || upr<0 ){
  37564. rc = SQLITE_CORRUPT_BKPT;
  37565. goto moveto_finish;
  37566. }
  37567. if( biasRight ){
  37568. pCur->aiIdx[pCur->iPage] = (u16)upr;
  37569. }else{
  37570. pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
  37571. }
  37572. for(;;){
  37573. void *pCellKey;
  37574. i64 nCellKey;
  37575. int idx = pCur->aiIdx[pCur->iPage];
  37576. pCur->info.nSize = 0;
  37577. pCur->validNKey = 1;
  37578. if( pPage->intKey ){
  37579. u8 *pCell;
  37580. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  37581. if( pPage->hasData ){
  37582. u32 dummy;
  37583. pCell += getVarint32(pCell, dummy);
  37584. }
  37585. getVarint(pCell, (u64*)&nCellKey);
  37586. if( nCellKey==intKey ){
  37587. c = 0;
  37588. }else if( nCellKey<intKey ){
  37589. c = -1;
  37590. }else{
  37591. assert( nCellKey>intKey );
  37592. c = +1;
  37593. }
  37594. }else{
  37595. int available;
  37596. pCellKey = (void *)fetchPayload(pCur, &available, 0);
  37597. nCellKey = pCur->info.nKey;
  37598. if( available>=nCellKey ){
  37599. c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
  37600. }else{
  37601. pCellKey = sqlite3Malloc( (int)nCellKey );
  37602. if( pCellKey==0 ){
  37603. rc = SQLITE_NOMEM;
  37604. goto moveto_finish;
  37605. }
  37606. rc = sqlite3BtreeKey(pCur, 0, (int)nCellKey, (void*)pCellKey);
  37607. c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
  37608. sqlite3_free(pCellKey);
  37609. if( rc ) goto moveto_finish;
  37610. }
  37611. }
  37612. if( c==0 ){
  37613. pCur->info.nKey = nCellKey;
  37614. if( pPage->intKey && !pPage->leaf ){
  37615. lwr = idx;
  37616. upr = lwr - 1;
  37617. break;
  37618. }else{
  37619. *pRes = 0;
  37620. rc = SQLITE_OK;
  37621. goto moveto_finish;
  37622. }
  37623. }
  37624. if( c<0 ){
  37625. lwr = idx+1;
  37626. }else{
  37627. upr = idx-1;
  37628. }
  37629. if( lwr>upr ){
  37630. pCur->info.nKey = nCellKey;
  37631. break;
  37632. }
  37633. pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
  37634. }
  37635. assert( lwr==upr+1 );
  37636. assert( pPage->isInit );
  37637. if( pPage->leaf ){
  37638. chldPg = 0;
  37639. }else if( lwr>=pPage->nCell ){
  37640. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  37641. }else{
  37642. chldPg = get4byte(findCell(pPage, lwr));
  37643. }
  37644. if( chldPg==0 ){
  37645. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  37646. if( pRes ) *pRes = c;
  37647. rc = SQLITE_OK;
  37648. goto moveto_finish;
  37649. }
  37650. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  37651. pCur->info.nSize = 0;
  37652. pCur->validNKey = 0;
  37653. rc = moveToChild(pCur, chldPg);
  37654. if( rc ) goto moveto_finish;
  37655. }
  37656. moveto_finish:
  37657. return rc;
  37658. }
  37659. /*
  37660. ** In this version of BtreeMoveto, pKey is a packed index record
  37661. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  37662. ** record and then call BtreeMovetoUnpacked() to do the work.
  37663. */
  37664. SQLITE_PRIVATE int sqlite3BtreeMoveto(
  37665. BtCursor *pCur, /* Cursor open on the btree to be searched */
  37666. const void *pKey, /* Packed key if the btree is an index */
  37667. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  37668. int bias, /* Bias search to the high end */
  37669. int *pRes /* Write search results here */
  37670. ){
  37671. int rc; /* Status code */
  37672. UnpackedRecord *pIdxKey; /* Unpacked index key */
  37673. UnpackedRecord aSpace[16]; /* Temp space for pIdxKey - to avoid a malloc */
  37674. if( pKey ){
  37675. assert( nKey==(i64)(int)nKey );
  37676. pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
  37677. aSpace, sizeof(aSpace));
  37678. if( pIdxKey==0 ) return SQLITE_NOMEM;
  37679. }else{
  37680. pIdxKey = 0;
  37681. }
  37682. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  37683. if( pKey ){
  37684. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  37685. }
  37686. return rc;
  37687. }
  37688. /*
  37689. ** Return TRUE if the cursor is not pointing at an entry of the table.
  37690. **
  37691. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  37692. ** past the last entry in the table or sqlite3BtreePrev() moves past
  37693. ** the first entry. TRUE is also returned if the table is empty.
  37694. */
  37695. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  37696. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  37697. ** have been deleted? This API will need to change to return an error code
  37698. ** as well as the boolean result value.
  37699. */
  37700. return (CURSOR_VALID!=pCur->eState);
  37701. }
  37702. /*
  37703. ** Return the database connection handle for a cursor.
  37704. */
  37705. SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
  37706. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  37707. return pCur->pBtree->db;
  37708. }
  37709. /*
  37710. ** Advance the cursor to the next entry in the database. If
  37711. ** successful then set *pRes=0. If the cursor
  37712. ** was already pointing to the last entry in the database before
  37713. ** this routine was called, then set *pRes=1.
  37714. */
  37715. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  37716. int rc;
  37717. int idx;
  37718. MemPage *pPage;
  37719. assert( cursorHoldsMutex(pCur) );
  37720. rc = restoreCursorPosition(pCur);
  37721. if( rc!=SQLITE_OK ){
  37722. return rc;
  37723. }
  37724. assert( pRes!=0 );
  37725. if( CURSOR_INVALID==pCur->eState ){
  37726. *pRes = 1;
  37727. return SQLITE_OK;
  37728. }
  37729. if( pCur->skip>0 ){
  37730. pCur->skip = 0;
  37731. *pRes = 0;
  37732. return SQLITE_OK;
  37733. }
  37734. pCur->skip = 0;
  37735. pPage = pCur->apPage[pCur->iPage];
  37736. idx = ++pCur->aiIdx[pCur->iPage];
  37737. assert( pPage->isInit );
  37738. assert( idx<=pPage->nCell );
  37739. pCur->info.nSize = 0;
  37740. pCur->validNKey = 0;
  37741. if( idx>=pPage->nCell ){
  37742. if( !pPage->leaf ){
  37743. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  37744. if( rc ) return rc;
  37745. rc = moveToLeftmost(pCur);
  37746. *pRes = 0;
  37747. return rc;
  37748. }
  37749. do{
  37750. if( pCur->iPage==0 ){
  37751. *pRes = 1;
  37752. pCur->eState = CURSOR_INVALID;
  37753. return SQLITE_OK;
  37754. }
  37755. sqlite3BtreeMoveToParent(pCur);
  37756. pPage = pCur->apPage[pCur->iPage];
  37757. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  37758. *pRes = 0;
  37759. if( pPage->intKey ){
  37760. rc = sqlite3BtreeNext(pCur, pRes);
  37761. }else{
  37762. rc = SQLITE_OK;
  37763. }
  37764. return rc;
  37765. }
  37766. *pRes = 0;
  37767. if( pPage->leaf ){
  37768. return SQLITE_OK;
  37769. }
  37770. rc = moveToLeftmost(pCur);
  37771. return rc;
  37772. }
  37773. /*
  37774. ** Step the cursor to the back to the previous entry in the database. If
  37775. ** successful then set *pRes=0. If the cursor
  37776. ** was already pointing to the first entry in the database before
  37777. ** this routine was called, then set *pRes=1.
  37778. */
  37779. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  37780. int rc;
  37781. MemPage *pPage;
  37782. assert( cursorHoldsMutex(pCur) );
  37783. rc = restoreCursorPosition(pCur);
  37784. if( rc!=SQLITE_OK ){
  37785. return rc;
  37786. }
  37787. pCur->atLast = 0;
  37788. if( CURSOR_INVALID==pCur->eState ){
  37789. *pRes = 1;
  37790. return SQLITE_OK;
  37791. }
  37792. if( pCur->skip<0 ){
  37793. pCur->skip = 0;
  37794. *pRes = 0;
  37795. return SQLITE_OK;
  37796. }
  37797. pCur->skip = 0;
  37798. pPage = pCur->apPage[pCur->iPage];
  37799. assert( pPage->isInit );
  37800. if( !pPage->leaf ){
  37801. int idx = pCur->aiIdx[pCur->iPage];
  37802. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  37803. if( rc ){
  37804. return rc;
  37805. }
  37806. rc = moveToRightmost(pCur);
  37807. }else{
  37808. while( pCur->aiIdx[pCur->iPage]==0 ){
  37809. if( pCur->iPage==0 ){
  37810. pCur->eState = CURSOR_INVALID;
  37811. *pRes = 1;
  37812. return SQLITE_OK;
  37813. }
  37814. sqlite3BtreeMoveToParent(pCur);
  37815. }
  37816. pCur->info.nSize = 0;
  37817. pCur->validNKey = 0;
  37818. pCur->aiIdx[pCur->iPage]--;
  37819. pPage = pCur->apPage[pCur->iPage];
  37820. if( pPage->intKey && !pPage->leaf ){
  37821. rc = sqlite3BtreePrevious(pCur, pRes);
  37822. }else{
  37823. rc = SQLITE_OK;
  37824. }
  37825. }
  37826. *pRes = 0;
  37827. return rc;
  37828. }
  37829. /*
  37830. ** Allocate a new page from the database file.
  37831. **
  37832. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  37833. ** has already been called on the new page.) The new page has also
  37834. ** been referenced and the calling routine is responsible for calling
  37835. ** sqlite3PagerUnref() on the new page when it is done.
  37836. **
  37837. ** SQLITE_OK is returned on success. Any other return value indicates
  37838. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  37839. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  37840. **
  37841. ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
  37842. ** locate a page close to the page number "nearby". This can be used in an
  37843. ** attempt to keep related pages close to each other in the database file,
  37844. ** which in turn can make database access faster.
  37845. **
  37846. ** If the "exact" parameter is not 0, and the page-number nearby exists
  37847. ** anywhere on the free-list, then it is guarenteed to be returned. This
  37848. ** is only used by auto-vacuum databases when allocating a new table.
  37849. */
  37850. static int allocateBtreePage(
  37851. BtShared *pBt,
  37852. MemPage **ppPage,
  37853. Pgno *pPgno,
  37854. Pgno nearby,
  37855. u8 exact
  37856. ){
  37857. MemPage *pPage1;
  37858. int rc;
  37859. int n; /* Number of pages on the freelist */
  37860. int k; /* Number of leaves on the trunk of the freelist */
  37861. MemPage *pTrunk = 0;
  37862. MemPage *pPrevTrunk = 0;
  37863. assert( sqlite3_mutex_held(pBt->mutex) );
  37864. pPage1 = pBt->pPage1;
  37865. n = get4byte(&pPage1->aData[36]);
  37866. if( n>0 ){
  37867. /* There are pages on the freelist. Reuse one of those pages. */
  37868. Pgno iTrunk;
  37869. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  37870. /* If the 'exact' parameter was true and a query of the pointer-map
  37871. ** shows that the page 'nearby' is somewhere on the free-list, then
  37872. ** the entire-list will be searched for that page.
  37873. */
  37874. #ifndef SQLITE_OMIT_AUTOVACUUM
  37875. if( exact && nearby<=pagerPagecount(pBt) ){
  37876. u8 eType;
  37877. assert( nearby>0 );
  37878. assert( pBt->autoVacuum );
  37879. rc = ptrmapGet(pBt, nearby, &eType, 0);
  37880. if( rc ) return rc;
  37881. if( eType==PTRMAP_FREEPAGE ){
  37882. searchList = 1;
  37883. }
  37884. *pPgno = nearby;
  37885. }
  37886. #endif
  37887. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  37888. ** first free-list trunk page. iPrevTrunk is initially 1.
  37889. */
  37890. rc = sqlite3PagerWrite(pPage1->pDbPage);
  37891. if( rc ) return rc;
  37892. put4byte(&pPage1->aData[36], n-1);
  37893. /* The code within this loop is run only once if the 'searchList' variable
  37894. ** is not true. Otherwise, it runs once for each trunk-page on the
  37895. ** free-list until the page 'nearby' is located.
  37896. */
  37897. do {
  37898. pPrevTrunk = pTrunk;
  37899. if( pPrevTrunk ){
  37900. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  37901. }else{
  37902. iTrunk = get4byte(&pPage1->aData[32]);
  37903. }
  37904. rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
  37905. if( rc ){
  37906. pTrunk = 0;
  37907. goto end_allocate_page;
  37908. }
  37909. k = get4byte(&pTrunk->aData[4]);
  37910. if( k==0 && !searchList ){
  37911. /* The trunk has no leaves and the list is not being searched.
  37912. ** So extract the trunk page itself and use it as the newly
  37913. ** allocated page */
  37914. assert( pPrevTrunk==0 );
  37915. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  37916. if( rc ){
  37917. goto end_allocate_page;
  37918. }
  37919. *pPgno = iTrunk;
  37920. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  37921. *ppPage = pTrunk;
  37922. pTrunk = 0;
  37923. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  37924. }else if( k>pBt->usableSize/4 - 2 ){
  37925. /* Value of k is out of range. Database corruption */
  37926. rc = SQLITE_CORRUPT_BKPT;
  37927. goto end_allocate_page;
  37928. #ifndef SQLITE_OMIT_AUTOVACUUM
  37929. }else if( searchList && nearby==iTrunk ){
  37930. /* The list is being searched and this trunk page is the page
  37931. ** to allocate, regardless of whether it has leaves.
  37932. */
  37933. assert( *pPgno==iTrunk );
  37934. *ppPage = pTrunk;
  37935. searchList = 0;
  37936. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  37937. if( rc ){
  37938. goto end_allocate_page;
  37939. }
  37940. if( k==0 ){
  37941. if( !pPrevTrunk ){
  37942. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  37943. }else{
  37944. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  37945. }
  37946. }else{
  37947. /* The trunk page is required by the caller but it contains
  37948. ** pointers to free-list leaves. The first leaf becomes a trunk
  37949. ** page in this case.
  37950. */
  37951. MemPage *pNewTrunk;
  37952. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  37953. rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  37954. if( rc!=SQLITE_OK ){
  37955. goto end_allocate_page;
  37956. }
  37957. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  37958. if( rc!=SQLITE_OK ){
  37959. releasePage(pNewTrunk);
  37960. goto end_allocate_page;
  37961. }
  37962. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  37963. put4byte(&pNewTrunk->aData[4], k-1);
  37964. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  37965. releasePage(pNewTrunk);
  37966. if( !pPrevTrunk ){
  37967. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  37968. put4byte(&pPage1->aData[32], iNewTrunk);
  37969. }else{
  37970. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  37971. if( rc ){
  37972. goto end_allocate_page;
  37973. }
  37974. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  37975. }
  37976. }
  37977. pTrunk = 0;
  37978. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  37979. #endif
  37980. }else{
  37981. /* Extract a leaf from the trunk */
  37982. int closest;
  37983. Pgno iPage;
  37984. unsigned char *aData = pTrunk->aData;
  37985. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  37986. if( rc ){
  37987. goto end_allocate_page;
  37988. }
  37989. if( nearby>0 ){
  37990. int i, dist;
  37991. closest = 0;
  37992. dist = get4byte(&aData[8]) - nearby;
  37993. if( dist<0 ) dist = -dist;
  37994. for(i=1; i<k; i++){
  37995. int d2 = get4byte(&aData[8+i*4]) - nearby;
  37996. if( d2<0 ) d2 = -d2;
  37997. if( d2<dist ){
  37998. closest = i;
  37999. dist = d2;
  38000. }
  38001. }
  38002. }else{
  38003. closest = 0;
  38004. }
  38005. iPage = get4byte(&aData[8+closest*4]);
  38006. if( !searchList || iPage==nearby ){
  38007. Pgno nPage;
  38008. *pPgno = iPage;
  38009. nPage = pagerPagecount(pBt);
  38010. if( *pPgno>nPage ){
  38011. /* Free page off the end of the file */
  38012. rc = SQLITE_CORRUPT_BKPT;
  38013. goto end_allocate_page;
  38014. }
  38015. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  38016. ": %d more free pages\n",
  38017. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  38018. if( closest<k-1 ){
  38019. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  38020. }
  38021. put4byte(&aData[4], k-1);
  38022. assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
  38023. rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
  38024. if( rc==SQLITE_OK ){
  38025. sqlite3PagerDontRollback((*ppPage)->pDbPage);
  38026. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  38027. if( rc!=SQLITE_OK ){
  38028. releasePage(*ppPage);
  38029. }
  38030. }
  38031. searchList = 0;
  38032. }
  38033. }
  38034. releasePage(pPrevTrunk);
  38035. pPrevTrunk = 0;
  38036. }while( searchList );
  38037. }else{
  38038. /* There are no pages on the freelist, so create a new page at the
  38039. ** end of the file */
  38040. int nPage = pagerPagecount(pBt);
  38041. *pPgno = nPage + 1;
  38042. #ifndef SQLITE_OMIT_AUTOVACUUM
  38043. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
  38044. /* If *pPgno refers to a pointer-map page, allocate two new pages
  38045. ** at the end of the file instead of one. The first allocated page
  38046. ** becomes a new pointer-map page, the second is used by the caller.
  38047. */
  38048. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
  38049. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  38050. (*pPgno)++;
  38051. if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
  38052. }
  38053. #endif
  38054. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  38055. rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
  38056. if( rc ) return rc;
  38057. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  38058. if( rc!=SQLITE_OK ){
  38059. releasePage(*ppPage);
  38060. }
  38061. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  38062. }
  38063. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  38064. end_allocate_page:
  38065. releasePage(pTrunk);
  38066. releasePage(pPrevTrunk);
  38067. if( rc==SQLITE_OK ){
  38068. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  38069. releasePage(*ppPage);
  38070. return SQLITE_CORRUPT_BKPT;
  38071. }
  38072. (*ppPage)->isInit = 0;
  38073. }
  38074. return rc;
  38075. }
  38076. /*
  38077. ** Add a page of the database file to the freelist.
  38078. **
  38079. ** sqlite3PagerUnref() is NOT called for pPage.
  38080. */
  38081. static int freePage(MemPage *pPage){
  38082. BtShared *pBt = pPage->pBt;
  38083. MemPage *pPage1 = pBt->pPage1;
  38084. int rc, n, k;
  38085. /* Prepare the page for freeing */
  38086. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38087. assert( pPage->pgno>1 );
  38088. pPage->isInit = 0;
  38089. /* Increment the free page count on pPage1 */
  38090. rc = sqlite3PagerWrite(pPage1->pDbPage);
  38091. if( rc ) return rc;
  38092. n = get4byte(&pPage1->aData[36]);
  38093. put4byte(&pPage1->aData[36], n+1);
  38094. #ifdef SQLITE_SECURE_DELETE
  38095. /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
  38096. ** always fully overwrite deleted information with zeros.
  38097. */
  38098. rc = sqlite3PagerWrite(pPage->pDbPage);
  38099. if( rc ) return rc;
  38100. memset(pPage->aData, 0, pPage->pBt->pageSize);
  38101. #endif
  38102. /* If the database supports auto-vacuum, write an entry in the pointer-map
  38103. ** to indicate that the page is free.
  38104. */
  38105. if( ISAUTOVACUUM ){
  38106. rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
  38107. if( rc ) return rc;
  38108. }
  38109. if( n==0 ){
  38110. /* This is the first free page */
  38111. rc = sqlite3PagerWrite(pPage->pDbPage);
  38112. if( rc ) return rc;
  38113. memset(pPage->aData, 0, 8);
  38114. put4byte(&pPage1->aData[32], pPage->pgno);
  38115. TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
  38116. }else{
  38117. /* Other free pages already exist. Retrive the first trunk page
  38118. ** of the freelist and find out how many leaves it has. */
  38119. MemPage *pTrunk;
  38120. rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
  38121. if( rc ) return rc;
  38122. k = get4byte(&pTrunk->aData[4]);
  38123. if( k>=pBt->usableSize/4 - 8 ){
  38124. /* The trunk is full. Turn the page being freed into a new
  38125. ** trunk page with no leaves.
  38126. **
  38127. ** Note that the trunk page is not really full until it contains
  38128. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  38129. ** coded. But due to a coding error in versions of SQLite prior to
  38130. ** 3.6.0, databases with freelist trunk pages holding more than
  38131. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  38132. ** to maintain backwards compatibility with older versions of SQLite,
  38133. ** we will contain to restrict the number of entries to usableSize/4 - 8
  38134. ** for now. At some point in the future (once everyone has upgraded
  38135. ** to 3.6.0 or later) we should consider fixing the conditional above
  38136. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  38137. */
  38138. rc = sqlite3PagerWrite(pPage->pDbPage);
  38139. if( rc==SQLITE_OK ){
  38140. put4byte(pPage->aData, pTrunk->pgno);
  38141. put4byte(&pPage->aData[4], 0);
  38142. put4byte(&pPage1->aData[32], pPage->pgno);
  38143. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
  38144. pPage->pgno, pTrunk->pgno));
  38145. }
  38146. }else if( k<0 ){
  38147. rc = SQLITE_CORRUPT;
  38148. }else{
  38149. /* Add the newly freed page as a leaf on the current trunk */
  38150. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  38151. if( rc==SQLITE_OK ){
  38152. put4byte(&pTrunk->aData[4], k+1);
  38153. put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
  38154. #ifndef SQLITE_SECURE_DELETE
  38155. rc = sqlite3PagerDontWrite(pPage->pDbPage);
  38156. #endif
  38157. }
  38158. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  38159. }
  38160. releasePage(pTrunk);
  38161. }
  38162. return rc;
  38163. }
  38164. /*
  38165. ** Free any overflow pages associated with the given Cell.
  38166. */
  38167. static int clearCell(MemPage *pPage, unsigned char *pCell){
  38168. BtShared *pBt = pPage->pBt;
  38169. CellInfo info;
  38170. Pgno ovflPgno;
  38171. int rc;
  38172. int nOvfl;
  38173. int ovflPageSize;
  38174. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38175. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  38176. if( info.iOverflow==0 ){
  38177. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  38178. }
  38179. ovflPgno = get4byte(&pCell[info.iOverflow]);
  38180. ovflPageSize = pBt->usableSize - 4;
  38181. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  38182. assert( ovflPgno==0 || nOvfl>0 );
  38183. while( nOvfl-- ){
  38184. MemPage *pOvfl;
  38185. if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt) ){
  38186. return SQLITE_CORRUPT_BKPT;
  38187. }
  38188. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
  38189. if( rc ) return rc;
  38190. rc = freePage(pOvfl);
  38191. sqlite3PagerUnref(pOvfl->pDbPage);
  38192. if( rc ) return rc;
  38193. }
  38194. return SQLITE_OK;
  38195. }
  38196. /*
  38197. ** Create the byte sequence used to represent a cell on page pPage
  38198. ** and write that byte sequence into pCell[]. Overflow pages are
  38199. ** allocated and filled in as necessary. The calling procedure
  38200. ** is responsible for making sure sufficient space has been allocated
  38201. ** for pCell[].
  38202. **
  38203. ** Note that pCell does not necessary need to point to the pPage->aData
  38204. ** area. pCell might point to some temporary storage. The cell will
  38205. ** be constructed in this temporary area then copied into pPage->aData
  38206. ** later.
  38207. */
  38208. static int fillInCell(
  38209. MemPage *pPage, /* The page that contains the cell */
  38210. unsigned char *pCell, /* Complete text of the cell */
  38211. const void *pKey, i64 nKey, /* The key */
  38212. const void *pData,int nData, /* The data */
  38213. int nZero, /* Extra zero bytes to append to pData */
  38214. int *pnSize /* Write cell size here */
  38215. ){
  38216. int nPayload;
  38217. const u8 *pSrc;
  38218. int nSrc, n, rc;
  38219. int spaceLeft;
  38220. MemPage *pOvfl = 0;
  38221. MemPage *pToRelease = 0;
  38222. unsigned char *pPrior;
  38223. unsigned char *pPayload;
  38224. BtShared *pBt = pPage->pBt;
  38225. Pgno pgnoOvfl = 0;
  38226. int nHeader;
  38227. CellInfo info;
  38228. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38229. /* pPage is not necessarily writeable since pCell might be auxiliary
  38230. ** buffer space that is separate from the pPage buffer area */
  38231. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  38232. || sqlite3PagerIswriteable(pPage->pDbPage) );
  38233. /* Fill in the header. */
  38234. nHeader = 0;
  38235. if( !pPage->leaf ){
  38236. nHeader += 4;
  38237. }
  38238. if( pPage->hasData ){
  38239. nHeader += putVarint(&pCell[nHeader], nData+nZero);
  38240. }else{
  38241. nData = nZero = 0;
  38242. }
  38243. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  38244. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  38245. assert( info.nHeader==nHeader );
  38246. assert( info.nKey==nKey );
  38247. assert( info.nData==(u32)(nData+nZero) );
  38248. /* Fill in the payload */
  38249. nPayload = nData + nZero;
  38250. if( pPage->intKey ){
  38251. pSrc = pData;
  38252. nSrc = nData;
  38253. nData = 0;
  38254. }else{
  38255. /* TBD: Perhaps raise SQLITE_CORRUPT if nKey is larger than 31 bits? */
  38256. nPayload += (int)nKey;
  38257. pSrc = pKey;
  38258. nSrc = (int)nKey;
  38259. }
  38260. *pnSize = info.nSize;
  38261. spaceLeft = info.nLocal;
  38262. pPayload = &pCell[nHeader];
  38263. pPrior = &pCell[info.iOverflow];
  38264. while( nPayload>0 ){
  38265. if( spaceLeft==0 ){
  38266. #ifndef SQLITE_OMIT_AUTOVACUUM
  38267. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  38268. if( pBt->autoVacuum ){
  38269. do{
  38270. pgnoOvfl++;
  38271. } while(
  38272. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  38273. );
  38274. }
  38275. #endif
  38276. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  38277. #ifndef SQLITE_OMIT_AUTOVACUUM
  38278. /* If the database supports auto-vacuum, and the second or subsequent
  38279. ** overflow page is being allocated, add an entry to the pointer-map
  38280. ** for that page now.
  38281. **
  38282. ** If this is the first overflow page, then write a partial entry
  38283. ** to the pointer-map. If we write nothing to this pointer-map slot,
  38284. ** then the optimistic overflow chain processing in clearCell()
  38285. ** may misinterpret the uninitialised values and delete the
  38286. ** wrong pages from the database.
  38287. */
  38288. if( pBt->autoVacuum && rc==SQLITE_OK ){
  38289. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  38290. rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
  38291. if( rc ){
  38292. releasePage(pOvfl);
  38293. }
  38294. }
  38295. #endif
  38296. if( rc ){
  38297. releasePage(pToRelease);
  38298. return rc;
  38299. }
  38300. /* If pToRelease is not zero than pPrior points into the data area
  38301. ** of pToRelease. Make sure pToRelease is still writeable. */
  38302. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  38303. /* If pPrior is part of the data area of pPage, then make sure pPage
  38304. ** is still writeable */
  38305. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  38306. || sqlite3PagerIswriteable(pPage->pDbPage) );
  38307. put4byte(pPrior, pgnoOvfl);
  38308. releasePage(pToRelease);
  38309. pToRelease = pOvfl;
  38310. pPrior = pOvfl->aData;
  38311. put4byte(pPrior, 0);
  38312. pPayload = &pOvfl->aData[4];
  38313. spaceLeft = pBt->usableSize - 4;
  38314. }
  38315. n = nPayload;
  38316. if( n>spaceLeft ) n = spaceLeft;
  38317. /* If pToRelease is not zero than pPayload points into the data area
  38318. ** of pToRelease. Make sure pToRelease is still writeable. */
  38319. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  38320. /* If pPayload is part of the data area of pPage, then make sure pPage
  38321. ** is still writeable */
  38322. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  38323. || sqlite3PagerIswriteable(pPage->pDbPage) );
  38324. if( nSrc>0 ){
  38325. if( n>nSrc ) n = nSrc;
  38326. assert( pSrc );
  38327. memcpy(pPayload, pSrc, n);
  38328. }else{
  38329. memset(pPayload, 0, n);
  38330. }
  38331. nPayload -= n;
  38332. pPayload += n;
  38333. pSrc += n;
  38334. nSrc -= n;
  38335. spaceLeft -= n;
  38336. if( nSrc==0 ){
  38337. nSrc = nData;
  38338. pSrc = pData;
  38339. }
  38340. }
  38341. releasePage(pToRelease);
  38342. return SQLITE_OK;
  38343. }
  38344. /*
  38345. ** Remove the i-th cell from pPage. This routine effects pPage only.
  38346. ** The cell content is not freed or deallocated. It is assumed that
  38347. ** the cell content has been copied someplace else. This routine just
  38348. ** removes the reference to the cell from pPage.
  38349. **
  38350. ** "sz" must be the number of bytes in the cell.
  38351. */
  38352. static int dropCell(MemPage *pPage, int idx, int sz){
  38353. int i; /* Loop counter */
  38354. int pc; /* Offset to cell content of cell being deleted */
  38355. u8 *data; /* pPage->aData */
  38356. u8 *ptr; /* Used to move bytes around within data[] */
  38357. int rc; /* The return code */
  38358. assert( idx>=0 && idx<pPage->nCell );
  38359. assert( sz==cellSize(pPage, idx) );
  38360. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38361. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38362. data = pPage->aData;
  38363. ptr = &data[pPage->cellOffset + 2*idx];
  38364. pc = get2byte(ptr);
  38365. if( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4))
  38366. || (pc+sz>pPage->pBt->usableSize) ){
  38367. return SQLITE_CORRUPT_BKPT;
  38368. }
  38369. rc = freeSpace(pPage, pc, sz);
  38370. if( rc!=SQLITE_OK ){
  38371. return rc;
  38372. }
  38373. for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
  38374. ptr[0] = ptr[2];
  38375. ptr[1] = ptr[3];
  38376. }
  38377. pPage->nCell--;
  38378. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  38379. pPage->nFree += 2;
  38380. return SQLITE_OK;
  38381. }
  38382. /*
  38383. ** Insert a new cell on pPage at cell index "i". pCell points to the
  38384. ** content of the cell.
  38385. **
  38386. ** If the cell content will fit on the page, then put it there. If it
  38387. ** will not fit, then make a copy of the cell content into pTemp if
  38388. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  38389. ** in pPage->aOvfl[] and make it point to the cell content (either
  38390. ** in pTemp or the original pCell) and also record its index.
  38391. ** Allocating a new entry in pPage->aCell[] implies that
  38392. ** pPage->nOverflow is incremented.
  38393. **
  38394. ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
  38395. ** cell. The caller will overwrite them after this function returns. If
  38396. ** nSkip is non-zero, then pCell may not point to an invalid memory location
  38397. ** (but pCell+nSkip is always valid).
  38398. */
  38399. static int insertCell(
  38400. MemPage *pPage, /* Page into which we are copying */
  38401. int i, /* New cell becomes the i-th cell of the page */
  38402. u8 *pCell, /* Content of the new cell */
  38403. int sz, /* Bytes of content in pCell */
  38404. u8 *pTemp, /* Temp storage space for pCell, if needed */
  38405. u8 nSkip /* Do not write the first nSkip bytes of the cell */
  38406. ){
  38407. int idx; /* Where to write new cell content in data[] */
  38408. int j; /* Loop counter */
  38409. int top; /* First byte of content for any cell in data[] */
  38410. int end; /* First byte past the last cell pointer in data[] */
  38411. int ins; /* Index in data[] where new cell pointer is inserted */
  38412. int hdr; /* Offset into data[] of the page header */
  38413. int cellOffset; /* Address of first cell pointer in data[] */
  38414. u8 *data; /* The content of the whole page */
  38415. u8 *ptr; /* Used for moving information around in data[] */
  38416. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  38417. assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
  38418. assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
  38419. assert( sz==cellSizePtr(pPage, pCell) );
  38420. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38421. if( pPage->nOverflow || sz+2>pPage->nFree ){
  38422. if( pTemp ){
  38423. memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
  38424. pCell = pTemp;
  38425. }
  38426. j = pPage->nOverflow++;
  38427. assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
  38428. pPage->aOvfl[j].pCell = pCell;
  38429. pPage->aOvfl[j].idx = (u16)i;
  38430. pPage->nFree = 0;
  38431. }else{
  38432. int rc = sqlite3PagerWrite(pPage->pDbPage);
  38433. if( rc!=SQLITE_OK ){
  38434. return rc;
  38435. }
  38436. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38437. data = pPage->aData;
  38438. hdr = pPage->hdrOffset;
  38439. top = get2byte(&data[hdr+5]);
  38440. cellOffset = pPage->cellOffset;
  38441. end = cellOffset + 2*pPage->nCell + 2;
  38442. ins = cellOffset + 2*i;
  38443. if( end > top - sz ){
  38444. rc = defragmentPage(pPage);
  38445. if( rc!=SQLITE_OK ){
  38446. return rc;
  38447. }
  38448. top = get2byte(&data[hdr+5]);
  38449. assert( end + sz <= top );
  38450. }
  38451. idx = allocateSpace(pPage, sz);
  38452. assert( idx>0 );
  38453. assert( end <= get2byte(&data[hdr+5]) );
  38454. if (idx+sz > pPage->pBt->usableSize) {
  38455. return SQLITE_CORRUPT_BKPT;
  38456. }
  38457. pPage->nCell++;
  38458. pPage->nFree -= 2;
  38459. memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
  38460. for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
  38461. ptr[0] = ptr[-2];
  38462. ptr[1] = ptr[-1];
  38463. }
  38464. put2byte(&data[ins], idx);
  38465. put2byte(&data[hdr+3], pPage->nCell);
  38466. #ifndef SQLITE_OMIT_AUTOVACUUM
  38467. if( pPage->pBt->autoVacuum ){
  38468. /* The cell may contain a pointer to an overflow page. If so, write
  38469. ** the entry for the overflow page into the pointer map.
  38470. */
  38471. CellInfo info;
  38472. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  38473. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  38474. if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
  38475. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  38476. rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
  38477. if( rc!=SQLITE_OK ) return rc;
  38478. }
  38479. }
  38480. #endif
  38481. }
  38482. return SQLITE_OK;
  38483. }
  38484. /*
  38485. ** Add a list of cells to a page. The page should be initially empty.
  38486. ** The cells are guaranteed to fit on the page.
  38487. */
  38488. static void assemblePage(
  38489. MemPage *pPage, /* The page to be assemblied */
  38490. int nCell, /* The number of cells to add to this page */
  38491. u8 **apCell, /* Pointers to cell bodies */
  38492. u16 *aSize /* Sizes of the cells */
  38493. ){
  38494. int i; /* Loop counter */
  38495. int totalSize; /* Total size of all cells */
  38496. int hdr; /* Index of page header */
  38497. int cellptr; /* Address of next cell pointer */
  38498. int cellbody; /* Address of next cell body */
  38499. u8 *data; /* Data for the page */
  38500. assert( pPage->nOverflow==0 );
  38501. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38502. assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
  38503. totalSize = 0;
  38504. for(i=0; i<nCell; i++){
  38505. totalSize += aSize[i];
  38506. }
  38507. assert( totalSize+2*nCell<=pPage->nFree );
  38508. assert( pPage->nCell==0 );
  38509. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38510. cellptr = pPage->cellOffset;
  38511. data = pPage->aData;
  38512. hdr = pPage->hdrOffset;
  38513. put2byte(&data[hdr+3], nCell);
  38514. if( nCell ){
  38515. cellbody = allocateSpace(pPage, totalSize);
  38516. assert( cellbody>0 );
  38517. assert( pPage->nFree >= 2*nCell );
  38518. pPage->nFree -= 2*nCell;
  38519. for(i=0; i<nCell; i++){
  38520. put2byte(&data[cellptr], cellbody);
  38521. memcpy(&data[cellbody], apCell[i], aSize[i]);
  38522. cellptr += 2;
  38523. cellbody += aSize[i];
  38524. }
  38525. assert( cellbody==pPage->pBt->usableSize );
  38526. }
  38527. pPage->nCell = (u16)nCell;
  38528. }
  38529. /*
  38530. ** The following parameters determine how many adjacent pages get involved
  38531. ** in a balancing operation. NN is the number of neighbors on either side
  38532. ** of the page that participate in the balancing operation. NB is the
  38533. ** total number of pages that participate, including the target page and
  38534. ** NN neighbors on either side.
  38535. **
  38536. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  38537. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  38538. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  38539. ** The value of NN appears to give the best results overall.
  38540. */
  38541. #define NN 1 /* Number of neighbors on either side of pPage */
  38542. #define NB (NN*2+1) /* Total pages involved in the balance */
  38543. /* Forward reference */
  38544. static int balance(BtCursor*, int);
  38545. #ifndef SQLITE_OMIT_QUICKBALANCE
  38546. /*
  38547. ** This version of balance() handles the common special case where
  38548. ** a new entry is being inserted on the extreme right-end of the
  38549. ** tree, in other words, when the new entry will become the largest
  38550. ** entry in the tree.
  38551. **
  38552. ** Instead of trying balance the 3 right-most leaf pages, just add
  38553. ** a new page to the right-hand side and put the one new entry in
  38554. ** that page. This leaves the right side of the tree somewhat
  38555. ** unbalanced. But odds are that we will be inserting new entries
  38556. ** at the end soon afterwards so the nearly empty page will quickly
  38557. ** fill up. On average.
  38558. **
  38559. ** pPage is the leaf page which is the right-most page in the tree.
  38560. ** pParent is its parent. pPage must have a single overflow entry
  38561. ** which is also the right-most entry on the page.
  38562. */
  38563. static int balance_quick(BtCursor *pCur){
  38564. int rc;
  38565. MemPage *pNew = 0;
  38566. Pgno pgnoNew;
  38567. u8 *pCell;
  38568. u16 szCell;
  38569. CellInfo info;
  38570. MemPage *pPage = pCur->apPage[pCur->iPage];
  38571. MemPage *pParent = pCur->apPage[pCur->iPage-1];
  38572. BtShared *pBt = pPage->pBt;
  38573. int parentIdx = pParent->nCell; /* pParent new divider cell index */
  38574. int parentSize; /* Size of new divider cell */
  38575. u8 parentCell[64]; /* Space for the new divider cell */
  38576. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38577. /* Allocate a new page. Insert the overflow cell from pPage
  38578. ** into it. Then remove the overflow cell from pPage.
  38579. */
  38580. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  38581. if( rc==SQLITE_OK ){
  38582. pCell = pPage->aOvfl[0].pCell;
  38583. szCell = cellSizePtr(pPage, pCell);
  38584. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  38585. zeroPage(pNew, pPage->aData[0]);
  38586. assemblePage(pNew, 1, &pCell, &szCell);
  38587. pPage->nOverflow = 0;
  38588. /* pPage is currently the right-child of pParent. Change this
  38589. ** so that the right-child is the new page allocated above and
  38590. ** pPage is the next-to-right child.
  38591. **
  38592. ** Ignore the return value of the call to fillInCell(). fillInCell()
  38593. ** may only return other than SQLITE_OK if it is required to allocate
  38594. ** one or more overflow pages. Since an internal table B-Tree cell
  38595. ** may never spill over onto an overflow page (it is a maximum of
  38596. ** 13 bytes in size), it is not neccessary to check the return code.
  38597. **
  38598. ** Similarly, the insertCell() function cannot fail if the page
  38599. ** being inserted into is already writable and the cell does not
  38600. ** contain an overflow pointer. So ignore this return code too.
  38601. */
  38602. assert( pPage->nCell>0 );
  38603. pCell = findCell(pPage, pPage->nCell-1);
  38604. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  38605. fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
  38606. assert( parentSize<64 );
  38607. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  38608. insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
  38609. put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
  38610. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  38611. /* If this is an auto-vacuum database, update the pointer map
  38612. ** with entries for the new page, and any pointer from the
  38613. ** cell on the page to an overflow page.
  38614. */
  38615. if( ISAUTOVACUUM ){
  38616. rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
  38617. if( rc==SQLITE_OK ){
  38618. rc = ptrmapPutOvfl(pNew, 0);
  38619. }
  38620. }
  38621. /* Release the reference to the new page. */
  38622. releasePage(pNew);
  38623. }
  38624. /* At this point the pPage->nFree variable is not set correctly with
  38625. ** respect to the content of the page (because it was set to 0 by
  38626. ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
  38627. ** correct.
  38628. **
  38629. ** This has to be done even if an error will be returned. Normally, if
  38630. ** an error occurs during tree balancing, the contents of MemPage are
  38631. ** not important, as they will be recalculated when the page is rolled
  38632. ** back. But here, in balance_quick(), it is possible that pPage has
  38633. ** not yet been marked dirty or written into the journal file. Therefore
  38634. ** it will not be rolled back and so it is important to make sure that
  38635. ** the page data and contents of MemPage are consistent.
  38636. */
  38637. pPage->isInit = 0;
  38638. sqlite3BtreeInitPage(pPage);
  38639. assert( pPage->nOverflow==0 );
  38640. /* If everything else succeeded, balance the parent page, in
  38641. ** case the divider cell inserted caused it to become overfull.
  38642. */
  38643. if( rc==SQLITE_OK ){
  38644. releasePage(pPage);
  38645. pCur->iPage--;
  38646. rc = balance(pCur, 0);
  38647. }
  38648. return rc;
  38649. }
  38650. #endif /* SQLITE_OMIT_QUICKBALANCE */
  38651. /*
  38652. ** This routine redistributes Cells on pPage and up to NN*2 siblings
  38653. ** of pPage so that all pages have about the same amount of free space.
  38654. ** Usually NN siblings on either side of pPage is used in the balancing,
  38655. ** though more siblings might come from one side if pPage is the first
  38656. ** or last child of its parent. If pPage has fewer than 2*NN siblings
  38657. ** (something which can only happen if pPage is the root page or a
  38658. ** child of root) then all available siblings participate in the balancing.
  38659. **
  38660. ** The number of siblings of pPage might be increased or decreased by one or
  38661. ** two in an effort to keep pages nearly full but not over full. The root page
  38662. ** is special and is allowed to be nearly empty. If pPage is
  38663. ** the root page, then the depth of the tree might be increased
  38664. ** or decreased by one, as necessary, to keep the root page from being
  38665. ** overfull or completely empty.
  38666. **
  38667. ** Note that when this routine is called, some of the Cells on pPage
  38668. ** might not actually be stored in pPage->aData[]. This can happen
  38669. ** if the page is overfull. Part of the job of this routine is to
  38670. ** make sure all Cells for pPage once again fit in pPage->aData[].
  38671. **
  38672. ** In the course of balancing the siblings of pPage, the parent of pPage
  38673. ** might become overfull or underfull. If that happens, then this routine
  38674. ** is called recursively on the parent.
  38675. **
  38676. ** If this routine fails for any reason, it might leave the database
  38677. ** in a corrupted state. So if this routine fails, the database should
  38678. ** be rolled back.
  38679. */
  38680. static int balance_nonroot(BtCursor *pCur){
  38681. MemPage *pPage; /* The over or underfull page to balance */
  38682. MemPage *pParent; /* The parent of pPage */
  38683. BtShared *pBt; /* The whole database */
  38684. int nCell = 0; /* Number of cells in apCell[] */
  38685. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  38686. int nOld = 0; /* Number of pages in apOld[] */
  38687. int nNew = 0; /* Number of pages in apNew[] */
  38688. int nDiv; /* Number of cells in apDiv[] */
  38689. int i, j, k; /* Loop counters */
  38690. int idx; /* Index of pPage in pParent->aCell[] */
  38691. int nxDiv; /* Next divider slot in pParent->aCell[] */
  38692. int rc; /* The return code */
  38693. int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  38694. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  38695. int usableSpace; /* Bytes in pPage beyond the header */
  38696. int pageFlags; /* Value of pPage->aData[0] */
  38697. int subtotal; /* Subtotal of bytes in cells on one page */
  38698. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  38699. int iSpace2 = 0; /* First unused byte of aSpace2[] */
  38700. int szScratch; /* Size of scratch memory requested */
  38701. MemPage *apOld[NB]; /* pPage and up to two siblings */
  38702. Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
  38703. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  38704. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  38705. Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
  38706. u8 *apDiv[NB]; /* Divider cells in pParent */
  38707. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  38708. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  38709. u8 **apCell = 0; /* All cells begin balanced */
  38710. u16 *szCell; /* Local size of all cells in apCell[] */
  38711. u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
  38712. u8 *aSpace1; /* Space for copies of dividers cells before balance */
  38713. u8 *aSpace2 = 0; /* Space for overflow dividers cells after balance */
  38714. u8 *aFrom = 0;
  38715. pPage = pCur->apPage[pCur->iPage];
  38716. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38717. VVA_ONLY( pCur->pagesShuffled = 1 );
  38718. /*
  38719. ** Find the parent page.
  38720. */
  38721. assert( pCur->iPage>0 );
  38722. assert( pPage->isInit );
  38723. assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
  38724. pBt = pPage->pBt;
  38725. pParent = pCur->apPage[pCur->iPage-1];
  38726. assert( pParent );
  38727. if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
  38728. goto balance_cleanup;
  38729. }
  38730. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  38731. #ifndef SQLITE_OMIT_QUICKBALANCE
  38732. /*
  38733. ** A special case: If a new entry has just been inserted into a
  38734. ** table (that is, a btree with integer keys and all data at the leaves)
  38735. ** and the new entry is the right-most entry in the tree (it has the
  38736. ** largest key) then use the special balance_quick() routine for
  38737. ** balancing. balance_quick() is much faster and results in a tighter
  38738. ** packing of data in the common case.
  38739. */
  38740. if( pPage->leaf &&
  38741. pPage->intKey &&
  38742. pPage->nOverflow==1 &&
  38743. pPage->aOvfl[0].idx==pPage->nCell &&
  38744. pParent->pgno!=1 &&
  38745. get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
  38746. ){
  38747. assert( pPage->intKey );
  38748. /*
  38749. ** TODO: Check the siblings to the left of pPage. It may be that
  38750. ** they are not full and no new page is required.
  38751. */
  38752. return balance_quick(pCur);
  38753. }
  38754. #endif
  38755. if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
  38756. goto balance_cleanup;
  38757. }
  38758. /*
  38759. ** Find the cell in the parent page whose left child points back
  38760. ** to pPage. The "idx" variable is the index of that cell. If pPage
  38761. ** is the rightmost child of pParent then set idx to pParent->nCell
  38762. */
  38763. idx = pCur->aiIdx[pCur->iPage-1];
  38764. assertParentIndex(pParent, idx, pPage->pgno);
  38765. /*
  38766. ** Find sibling pages to pPage and the cells in pParent that divide
  38767. ** the siblings. An attempt is made to find NN siblings on either
  38768. ** side of pPage. More siblings are taken from one side, however, if
  38769. ** pPage there are fewer than NN siblings on the other side. If pParent
  38770. ** has NB or fewer children then all children of pParent are taken.
  38771. */
  38772. nxDiv = idx - NN;
  38773. if( nxDiv + NB > pParent->nCell ){
  38774. nxDiv = pParent->nCell - NB + 1;
  38775. }
  38776. if( nxDiv<0 ){
  38777. nxDiv = 0;
  38778. }
  38779. nDiv = 0;
  38780. for(i=0, k=nxDiv; i<NB; i++, k++){
  38781. if( k<pParent->nCell ){
  38782. apDiv[i] = findCell(pParent, k);
  38783. nDiv++;
  38784. assert( !pParent->leaf );
  38785. pgnoOld[i] = get4byte(apDiv[i]);
  38786. }else if( k==pParent->nCell ){
  38787. pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
  38788. }else{
  38789. break;
  38790. }
  38791. rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
  38792. if( rc ) goto balance_cleanup;
  38793. /* apOld[i]->idxParent = k; */
  38794. apCopy[i] = 0;
  38795. assert( i==nOld );
  38796. nOld++;
  38797. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  38798. }
  38799. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  38800. ** alignment */
  38801. nMaxCells = (nMaxCells + 3)&~3;
  38802. /*
  38803. ** Allocate space for memory structures
  38804. */
  38805. szScratch =
  38806. nMaxCells*sizeof(u8*) /* apCell */
  38807. + nMaxCells*sizeof(u16) /* szCell */
  38808. + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB /* aCopy */
  38809. + pBt->pageSize /* aSpace1 */
  38810. + (ISAUTOVACUUM ? nMaxCells : 0); /* aFrom */
  38811. apCell = sqlite3ScratchMalloc( szScratch );
  38812. if( apCell==0 ){
  38813. rc = SQLITE_NOMEM;
  38814. goto balance_cleanup;
  38815. }
  38816. szCell = (u16*)&apCell[nMaxCells];
  38817. aCopy[0] = (u8*)&szCell[nMaxCells];
  38818. assert( ((aCopy[0] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
  38819. for(i=1; i<NB; i++){
  38820. aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
  38821. assert( ((aCopy[i] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
  38822. }
  38823. aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
  38824. assert( ((aSpace1 - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
  38825. if( ISAUTOVACUUM ){
  38826. aFrom = &aSpace1[pBt->pageSize];
  38827. }
  38828. aSpace2 = sqlite3PageMalloc(pBt->pageSize);
  38829. if( aSpace2==0 ){
  38830. rc = SQLITE_NOMEM;
  38831. goto balance_cleanup;
  38832. }
  38833. /*
  38834. ** Make copies of the content of pPage and its siblings into aOld[].
  38835. ** The rest of this function will use data from the copies rather
  38836. ** that the original pages since the original pages will be in the
  38837. ** process of being overwritten.
  38838. */
  38839. for(i=0; i<nOld; i++){
  38840. MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
  38841. memcpy(p, apOld[i], sizeof(MemPage));
  38842. p->aData = (void*)&p[1];
  38843. memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
  38844. }
  38845. /*
  38846. ** Load pointers to all cells on sibling pages and the divider cells
  38847. ** into the local apCell[] array. Make copies of the divider cells
  38848. ** into space obtained form aSpace1[] and remove the the divider Cells
  38849. ** from pParent.
  38850. **
  38851. ** If the siblings are on leaf pages, then the child pointers of the
  38852. ** divider cells are stripped from the cells before they are copied
  38853. ** into aSpace1[]. In this way, all cells in apCell[] are without
  38854. ** child pointers. If siblings are not leaves, then all cell in
  38855. ** apCell[] include child pointers. Either way, all cells in apCell[]
  38856. ** are alike.
  38857. **
  38858. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  38859. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  38860. */
  38861. nCell = 0;
  38862. leafCorrection = pPage->leaf*4;
  38863. leafData = pPage->hasData;
  38864. for(i=0; i<nOld; i++){
  38865. MemPage *pOld = apCopy[i];
  38866. int limit = pOld->nCell+pOld->nOverflow;
  38867. for(j=0; j<limit; j++){
  38868. assert( nCell<nMaxCells );
  38869. apCell[nCell] = findOverflowCell(pOld, j);
  38870. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  38871. if( ISAUTOVACUUM ){
  38872. int a;
  38873. aFrom[nCell] = (u8)i; assert( i>=0 && i<6 );
  38874. for(a=0; a<pOld->nOverflow; a++){
  38875. if( pOld->aOvfl[a].pCell==apCell[nCell] ){
  38876. aFrom[nCell] = 0xFF;
  38877. break;
  38878. }
  38879. }
  38880. }
  38881. nCell++;
  38882. }
  38883. if( i<nOld-1 ){
  38884. u16 sz = cellSizePtr(pParent, apDiv[i]);
  38885. if( leafData ){
  38886. /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
  38887. ** are duplicates of keys on the child pages. We need to remove
  38888. ** the divider cells from pParent, but the dividers cells are not
  38889. ** added to apCell[] because they are duplicates of child cells.
  38890. */
  38891. dropCell(pParent, nxDiv, sz);
  38892. }else{
  38893. u8 *pTemp;
  38894. assert( nCell<nMaxCells );
  38895. szCell[nCell] = sz;
  38896. pTemp = &aSpace1[iSpace1];
  38897. iSpace1 += sz;
  38898. assert( sz<=pBt->pageSize/4 );
  38899. assert( iSpace1<=pBt->pageSize );
  38900. memcpy(pTemp, apDiv[i], sz);
  38901. apCell[nCell] = pTemp+leafCorrection;
  38902. if( ISAUTOVACUUM ){
  38903. aFrom[nCell] = 0xFF;
  38904. }
  38905. dropCell(pParent, nxDiv, sz);
  38906. assert( leafCorrection==0 || leafCorrection==4 );
  38907. szCell[nCell] -= (u16)leafCorrection;
  38908. assert( get4byte(pTemp)==pgnoOld[i] );
  38909. if( !pOld->leaf ){
  38910. assert( leafCorrection==0 );
  38911. /* The right pointer of the child page pOld becomes the left
  38912. ** pointer of the divider cell */
  38913. memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
  38914. }else{
  38915. assert( leafCorrection==4 );
  38916. if( szCell[nCell]<4 ){
  38917. /* Do not allow any cells smaller than 4 bytes. */
  38918. szCell[nCell] = 4;
  38919. }
  38920. }
  38921. nCell++;
  38922. }
  38923. }
  38924. }
  38925. /*
  38926. ** Figure out the number of pages needed to hold all nCell cells.
  38927. ** Store this number in "k". Also compute szNew[] which is the total
  38928. ** size of all cells on the i-th page and cntNew[] which is the index
  38929. ** in apCell[] of the cell that divides page i from page i+1.
  38930. ** cntNew[k] should equal nCell.
  38931. **
  38932. ** Values computed by this block:
  38933. **
  38934. ** k: The total number of sibling pages
  38935. ** szNew[i]: Spaced used on the i-th sibling page.
  38936. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  38937. ** the right of the i-th sibling page.
  38938. ** usableSpace: Number of bytes of space available on each sibling.
  38939. **
  38940. */
  38941. usableSpace = pBt->usableSize - 12 + leafCorrection;
  38942. for(subtotal=k=i=0; i<nCell; i++){
  38943. assert( i<nMaxCells );
  38944. subtotal += szCell[i] + 2;
  38945. if( subtotal > usableSpace ){
  38946. szNew[k] = subtotal - szCell[i];
  38947. cntNew[k] = i;
  38948. if( leafData ){ i--; }
  38949. subtotal = 0;
  38950. k++;
  38951. }
  38952. }
  38953. szNew[k] = subtotal;
  38954. cntNew[k] = nCell;
  38955. k++;
  38956. /*
  38957. ** The packing computed by the previous block is biased toward the siblings
  38958. ** on the left side. The left siblings are always nearly full, while the
  38959. ** right-most sibling might be nearly empty. This block of code attempts
  38960. ** to adjust the packing of siblings to get a better balance.
  38961. **
  38962. ** This adjustment is more than an optimization. The packing above might
  38963. ** be so out of balance as to be illegal. For example, the right-most
  38964. ** sibling might be completely empty. This adjustment is not optional.
  38965. */
  38966. for(i=k-1; i>0; i--){
  38967. int szRight = szNew[i]; /* Size of sibling on the right */
  38968. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  38969. int r; /* Index of right-most cell in left sibling */
  38970. int d; /* Index of first cell to the left of right sibling */
  38971. r = cntNew[i-1] - 1;
  38972. d = r + 1 - leafData;
  38973. assert( d<nMaxCells );
  38974. assert( r<nMaxCells );
  38975. while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
  38976. szRight += szCell[d] + 2;
  38977. szLeft -= szCell[r] + 2;
  38978. cntNew[i-1]--;
  38979. r = cntNew[i-1] - 1;
  38980. d = r + 1 - leafData;
  38981. }
  38982. szNew[i] = szRight;
  38983. szNew[i-1] = szLeft;
  38984. }
  38985. /* Either we found one or more cells (cntnew[0])>0) or we are the
  38986. ** a virtual root page. A virtual root page is when the real root
  38987. ** page is page 1 and we are the only child of that page.
  38988. */
  38989. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  38990. /*
  38991. ** Allocate k new pages. Reuse old pages where possible.
  38992. */
  38993. assert( pPage->pgno>1 );
  38994. pageFlags = pPage->aData[0];
  38995. for(i=0; i<k; i++){
  38996. MemPage *pNew;
  38997. if( i<nOld ){
  38998. pNew = apNew[i] = apOld[i];
  38999. pgnoNew[i] = pgnoOld[i];
  39000. apOld[i] = 0;
  39001. rc = sqlite3PagerWrite(pNew->pDbPage);
  39002. nNew++;
  39003. if( rc ) goto balance_cleanup;
  39004. }else{
  39005. assert( i>0 );
  39006. rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
  39007. if( rc ) goto balance_cleanup;
  39008. apNew[i] = pNew;
  39009. nNew++;
  39010. }
  39011. }
  39012. /* Free any old pages that were not reused as new pages.
  39013. */
  39014. while( i<nOld ){
  39015. rc = freePage(apOld[i]);
  39016. if( rc ) goto balance_cleanup;
  39017. releasePage(apOld[i]);
  39018. apOld[i] = 0;
  39019. i++;
  39020. }
  39021. /*
  39022. ** Put the new pages in accending order. This helps to
  39023. ** keep entries in the disk file in order so that a scan
  39024. ** of the table is a linear scan through the file. That
  39025. ** in turn helps the operating system to deliver pages
  39026. ** from the disk more rapidly.
  39027. **
  39028. ** An O(n^2) insertion sort algorithm is used, but since
  39029. ** n is never more than NB (a small constant), that should
  39030. ** not be a problem.
  39031. **
  39032. ** When NB==3, this one optimization makes the database
  39033. ** about 25% faster for large insertions and deletions.
  39034. */
  39035. for(i=0; i<k-1; i++){
  39036. int minV = pgnoNew[i];
  39037. int minI = i;
  39038. for(j=i+1; j<k; j++){
  39039. if( pgnoNew[j]<(unsigned)minV ){
  39040. minI = j;
  39041. minV = pgnoNew[j];
  39042. }
  39043. }
  39044. if( minI>i ){
  39045. int t;
  39046. MemPage *pT;
  39047. t = pgnoNew[i];
  39048. pT = apNew[i];
  39049. pgnoNew[i] = pgnoNew[minI];
  39050. apNew[i] = apNew[minI];
  39051. pgnoNew[minI] = t;
  39052. apNew[minI] = pT;
  39053. }
  39054. }
  39055. TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  39056. pgnoOld[0],
  39057. nOld>=2 ? pgnoOld[1] : 0,
  39058. nOld>=3 ? pgnoOld[2] : 0,
  39059. pgnoNew[0], szNew[0],
  39060. nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
  39061. nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
  39062. nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
  39063. nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
  39064. /*
  39065. ** Evenly distribute the data in apCell[] across the new pages.
  39066. ** Insert divider cells into pParent as necessary.
  39067. */
  39068. j = 0;
  39069. for(i=0; i<nNew; i++){
  39070. /* Assemble the new sibling page. */
  39071. MemPage *pNew = apNew[i];
  39072. assert( j<nMaxCells );
  39073. assert( pNew->pgno==pgnoNew[i] );
  39074. zeroPage(pNew, pageFlags);
  39075. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  39076. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  39077. assert( pNew->nOverflow==0 );
  39078. /* If this is an auto-vacuum database, update the pointer map entries
  39079. ** that point to the siblings that were rearranged. These can be: left
  39080. ** children of cells, the right-child of the page, or overflow pages
  39081. ** pointed to by cells.
  39082. */
  39083. if( ISAUTOVACUUM ){
  39084. for(k=j; k<cntNew[i]; k++){
  39085. assert( k<nMaxCells );
  39086. if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
  39087. rc = ptrmapPutOvfl(pNew, k-j);
  39088. if( rc==SQLITE_OK && leafCorrection==0 ){
  39089. rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
  39090. }
  39091. if( rc!=SQLITE_OK ){
  39092. goto balance_cleanup;
  39093. }
  39094. }
  39095. }
  39096. }
  39097. j = cntNew[i];
  39098. /* If the sibling page assembled above was not the right-most sibling,
  39099. ** insert a divider cell into the parent page.
  39100. */
  39101. if( i<nNew-1 && j<nCell ){
  39102. u8 *pCell;
  39103. u8 *pTemp;
  39104. int sz;
  39105. assert( j<nMaxCells );
  39106. pCell = apCell[j];
  39107. sz = szCell[j] + leafCorrection;
  39108. pTemp = &aSpace2[iSpace2];
  39109. if( !pNew->leaf ){
  39110. memcpy(&pNew->aData[8], pCell, 4);
  39111. if( ISAUTOVACUUM
  39112. && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
  39113. ){
  39114. rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
  39115. if( rc!=SQLITE_OK ){
  39116. goto balance_cleanup;
  39117. }
  39118. }
  39119. }else if( leafData ){
  39120. /* If the tree is a leaf-data tree, and the siblings are leaves,
  39121. ** then there is no divider cell in apCell[]. Instead, the divider
  39122. ** cell consists of the integer key for the right-most cell of
  39123. ** the sibling-page assembled above only.
  39124. */
  39125. CellInfo info;
  39126. j--;
  39127. sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
  39128. pCell = pTemp;
  39129. fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
  39130. pTemp = 0;
  39131. }else{
  39132. pCell -= 4;
  39133. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  39134. ** previously stored on a leaf node, and its reported size was 4
  39135. ** bytes, then it may actually be smaller than this
  39136. ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
  39137. ** any cell). But it is important to pass the correct size to
  39138. ** insertCell(), so reparse the cell now.
  39139. **
  39140. ** Note that this can never happen in an SQLite data file, as all
  39141. ** cells are at least 4 bytes. It only happens in b-trees used
  39142. ** to evaluate "IN (SELECT ...)" and similar clauses.
  39143. */
  39144. if( szCell[j]==4 ){
  39145. assert(leafCorrection==4);
  39146. sz = cellSizePtr(pParent, pCell);
  39147. }
  39148. }
  39149. iSpace2 += sz;
  39150. assert( sz<=pBt->pageSize/4 );
  39151. assert( iSpace2<=pBt->pageSize );
  39152. rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
  39153. if( rc!=SQLITE_OK ) goto balance_cleanup;
  39154. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  39155. put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
  39156. /* If this is an auto-vacuum database, and not a leaf-data tree,
  39157. ** then update the pointer map with an entry for the overflow page
  39158. ** that the cell just inserted points to (if any).
  39159. */
  39160. if( ISAUTOVACUUM && !leafData ){
  39161. rc = ptrmapPutOvfl(pParent, nxDiv);
  39162. if( rc!=SQLITE_OK ){
  39163. goto balance_cleanup;
  39164. }
  39165. }
  39166. j++;
  39167. nxDiv++;
  39168. }
  39169. /* Set the pointer-map entry for the new sibling page. */
  39170. if( ISAUTOVACUUM ){
  39171. rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
  39172. if( rc!=SQLITE_OK ){
  39173. goto balance_cleanup;
  39174. }
  39175. }
  39176. }
  39177. assert( j==nCell );
  39178. assert( nOld>0 );
  39179. assert( nNew>0 );
  39180. if( (pageFlags & PTF_LEAF)==0 ){
  39181. u8 *zChild = &apCopy[nOld-1]->aData[8];
  39182. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  39183. if( ISAUTOVACUUM ){
  39184. rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
  39185. if( rc!=SQLITE_OK ){
  39186. goto balance_cleanup;
  39187. }
  39188. }
  39189. }
  39190. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  39191. if( nxDiv==pParent->nCell+pParent->nOverflow ){
  39192. /* Right-most sibling is the right-most child of pParent */
  39193. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
  39194. }else{
  39195. /* Right-most sibling is the left child of the first entry in pParent
  39196. ** past the right-most divider entry */
  39197. put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
  39198. }
  39199. /*
  39200. ** Balance the parent page. Note that the current page (pPage) might
  39201. ** have been added to the freelist so it might no longer be initialized.
  39202. ** But the parent page will always be initialized.
  39203. */
  39204. assert( pParent->isInit );
  39205. sqlite3ScratchFree(apCell);
  39206. apCell = 0;
  39207. TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
  39208. pPage->pgno, nOld, nNew, nCell));
  39209. pPage->nOverflow = 0;
  39210. releasePage(pPage);
  39211. pCur->iPage--;
  39212. rc = balance(pCur, 0);
  39213. /*
  39214. ** Cleanup before returning.
  39215. */
  39216. balance_cleanup:
  39217. sqlite3PageFree(aSpace2);
  39218. sqlite3ScratchFree(apCell);
  39219. for(i=0; i<nOld; i++){
  39220. releasePage(apOld[i]);
  39221. }
  39222. for(i=0; i<nNew; i++){
  39223. releasePage(apNew[i]);
  39224. }
  39225. pCur->apPage[pCur->iPage]->nOverflow = 0;
  39226. return rc;
  39227. }
  39228. /*
  39229. ** This routine is called for the root page of a btree when the root
  39230. ** page contains no cells. This is an opportunity to make the tree
  39231. ** shallower by one level.
  39232. */
  39233. static int balance_shallower(BtCursor *pCur){
  39234. MemPage *pPage; /* Root page of B-Tree */
  39235. MemPage *pChild; /* The only child page of pPage */
  39236. Pgno pgnoChild; /* Page number for pChild */
  39237. int rc = SQLITE_OK; /* Return code from subprocedures */
  39238. BtShared *pBt; /* The main BTree structure */
  39239. int mxCellPerPage; /* Maximum number of cells per page */
  39240. u8 **apCell; /* All cells from pages being balanced */
  39241. u16 *szCell; /* Local size of all cells */
  39242. assert( pCur->iPage==0 );
  39243. pPage = pCur->apPage[0];
  39244. assert( pPage->nCell==0 );
  39245. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  39246. pBt = pPage->pBt;
  39247. mxCellPerPage = MX_CELL(pBt);
  39248. apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
  39249. if( apCell==0 ) return SQLITE_NOMEM;
  39250. szCell = (u16*)&apCell[mxCellPerPage];
  39251. if( pPage->leaf ){
  39252. /* The table is completely empty */
  39253. TRACE(("BALANCE: empty table %d\n", pPage->pgno));
  39254. }else{
  39255. /* The root page is empty but has one child. Transfer the
  39256. ** information from that one child into the root page if it
  39257. ** will fit. This reduces the depth of the tree by one.
  39258. **
  39259. ** If the root page is page 1, it has less space available than
  39260. ** its child (due to the 100 byte header that occurs at the beginning
  39261. ** of the database fle), so it might not be able to hold all of the
  39262. ** information currently contained in the child. If this is the
  39263. ** case, then do not do the transfer. Leave page 1 empty except
  39264. ** for the right-pointer to the child page. The child page becomes
  39265. ** the virtual root of the tree.
  39266. */
  39267. VVA_ONLY( pCur->pagesShuffled = 1 );
  39268. pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  39269. assert( pgnoChild>0 );
  39270. assert( pgnoChild<=pagerPagecount(pPage->pBt) );
  39271. rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
  39272. if( rc ) goto end_shallow_balance;
  39273. if( pPage->pgno==1 ){
  39274. rc = sqlite3BtreeInitPage(pChild);
  39275. if( rc ) goto end_shallow_balance;
  39276. assert( pChild->nOverflow==0 );
  39277. if( pChild->nFree>=100 ){
  39278. /* The child information will fit on the root page, so do the
  39279. ** copy */
  39280. int i;
  39281. zeroPage(pPage, pChild->aData[0]);
  39282. for(i=0; i<pChild->nCell; i++){
  39283. apCell[i] = findCell(pChild,i);
  39284. szCell[i] = cellSizePtr(pChild, apCell[i]);
  39285. }
  39286. assemblePage(pPage, pChild->nCell, apCell, szCell);
  39287. /* Copy the right-pointer of the child to the parent. */
  39288. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  39289. put4byte(&pPage->aData[pPage->hdrOffset+8],
  39290. get4byte(&pChild->aData[pChild->hdrOffset+8]));
  39291. rc = freePage(pChild);
  39292. TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
  39293. }else{
  39294. /* The child has more information that will fit on the root.
  39295. ** The tree is already balanced. Do nothing. */
  39296. TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
  39297. }
  39298. }else{
  39299. memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
  39300. pPage->isInit = 0;
  39301. rc = sqlite3BtreeInitPage(pPage);
  39302. assert( rc==SQLITE_OK );
  39303. freePage(pChild);
  39304. TRACE(("BALANCE: transfer child %d into root %d\n",
  39305. pChild->pgno, pPage->pgno));
  39306. }
  39307. assert( pPage->nOverflow==0 );
  39308. #ifndef SQLITE_OMIT_AUTOVACUUM
  39309. if( ISAUTOVACUUM && rc==SQLITE_OK ){
  39310. rc = setChildPtrmaps(pPage);
  39311. }
  39312. #endif
  39313. releasePage(pChild);
  39314. }
  39315. end_shallow_balance:
  39316. sqlite3_free(apCell);
  39317. return rc;
  39318. }
  39319. /*
  39320. ** The root page is overfull
  39321. **
  39322. ** When this happens, Create a new child page and copy the
  39323. ** contents of the root into the child. Then make the root
  39324. ** page an empty page with rightChild pointing to the new
  39325. ** child. Finally, call balance_internal() on the new child
  39326. ** to cause it to split.
  39327. */
  39328. static int balance_deeper(BtCursor *pCur){
  39329. int rc; /* Return value from subprocedures */
  39330. MemPage *pPage; /* Pointer to the root page */
  39331. MemPage *pChild; /* Pointer to a new child page */
  39332. Pgno pgnoChild; /* Page number of the new child page */
  39333. BtShared *pBt; /* The BTree */
  39334. int usableSize; /* Total usable size of a page */
  39335. u8 *data; /* Content of the parent page */
  39336. u8 *cdata; /* Content of the child page */
  39337. int hdr; /* Offset to page header in parent */
  39338. int cbrk; /* Offset to content of first cell in parent */
  39339. assert( pCur->iPage==0 );
  39340. assert( pCur->apPage[0]->nOverflow>0 );
  39341. VVA_ONLY( pCur->pagesShuffled = 1 );
  39342. pPage = pCur->apPage[0];
  39343. pBt = pPage->pBt;
  39344. assert( sqlite3_mutex_held(pBt->mutex) );
  39345. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  39346. rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
  39347. if( rc ) return rc;
  39348. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  39349. usableSize = pBt->usableSize;
  39350. data = pPage->aData;
  39351. hdr = pPage->hdrOffset;
  39352. cbrk = get2byte(&data[hdr+5]);
  39353. cdata = pChild->aData;
  39354. memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
  39355. memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
  39356. assert( pChild->isInit==0 );
  39357. rc = sqlite3BtreeInitPage(pChild);
  39358. if( rc==SQLITE_OK ){
  39359. int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
  39360. memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
  39361. pChild->nOverflow = pPage->nOverflow;
  39362. if( pChild->nOverflow ){
  39363. pChild->nFree = 0;
  39364. }
  39365. assert( pChild->nCell==pPage->nCell );
  39366. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  39367. zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
  39368. put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
  39369. TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
  39370. if( ISAUTOVACUUM ){
  39371. rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
  39372. #ifndef SQLITE_OMIT_AUTOVACUUM
  39373. if( rc==SQLITE_OK ){
  39374. rc = setChildPtrmaps(pChild);
  39375. }
  39376. if( rc ){
  39377. pChild->nOverflow = 0;
  39378. }
  39379. #endif
  39380. }
  39381. }
  39382. if( rc==SQLITE_OK ){
  39383. pCur->iPage++;
  39384. pCur->apPage[1] = pChild;
  39385. pCur->aiIdx[0] = 0;
  39386. rc = balance_nonroot(pCur);
  39387. }else{
  39388. releasePage(pChild);
  39389. }
  39390. return rc;
  39391. }
  39392. /*
  39393. ** The page that pCur currently points to has just been modified in
  39394. ** some way. This function figures out if this modification means the
  39395. ** tree needs to be balanced, and if so calls the appropriate balancing
  39396. ** routine.
  39397. **
  39398. ** Parameter isInsert is true if a new cell was just inserted into the
  39399. ** page, or false otherwise.
  39400. */
  39401. static int balance(BtCursor *pCur, int isInsert){
  39402. int rc = SQLITE_OK;
  39403. MemPage *pPage = pCur->apPage[pCur->iPage];
  39404. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  39405. if( pCur->iPage==0 ){
  39406. rc = sqlite3PagerWrite(pPage->pDbPage);
  39407. if( rc==SQLITE_OK && pPage->nOverflow>0 ){
  39408. rc = balance_deeper(pCur);
  39409. assert( pCur->apPage[0]==pPage );
  39410. assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
  39411. }
  39412. if( rc==SQLITE_OK && pPage->nCell==0 ){
  39413. rc = balance_shallower(pCur);
  39414. assert( pCur->apPage[0]==pPage );
  39415. assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
  39416. }
  39417. }else{
  39418. if( pPage->nOverflow>0 ||
  39419. (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
  39420. rc = balance_nonroot(pCur);
  39421. }
  39422. }
  39423. return rc;
  39424. }
  39425. /*
  39426. ** This routine checks all cursors that point to table pgnoRoot.
  39427. ** If any of those cursors were opened with wrFlag==0 in a different
  39428. ** database connection (a database connection that shares the pager
  39429. ** cache with the current connection) and that other connection
  39430. ** is not in the ReadUncommmitted state, then this routine returns
  39431. ** SQLITE_LOCKED.
  39432. **
  39433. ** As well as cursors with wrFlag==0, cursors with wrFlag==1 and
  39434. ** isIncrblobHandle==1 are also considered 'read' cursors. Incremental
  39435. ** blob cursors are used for both reading and writing.
  39436. **
  39437. ** When pgnoRoot is the root page of an intkey table, this function is also
  39438. ** responsible for invalidating incremental blob cursors when the table row
  39439. ** on which they are opened is deleted or modified. Cursors are invalidated
  39440. ** according to the following rules:
  39441. **
  39442. ** 1) When BtreeClearTable() is called to completely delete the contents
  39443. ** of a B-Tree table, pExclude is set to zero and parameter iRow is
  39444. ** set to non-zero. In this case all incremental blob cursors open
  39445. ** on the table rooted at pgnoRoot are invalidated.
  39446. **
  39447. ** 2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to
  39448. ** modify a table row via an SQL statement, pExclude is set to the
  39449. ** write cursor used to do the modification and parameter iRow is set
  39450. ** to the integer row id of the B-Tree entry being modified. Unless
  39451. ** pExclude is itself an incremental blob cursor, then all incremental
  39452. ** blob cursors open on row iRow of the B-Tree are invalidated.
  39453. **
  39454. ** 3) If both pExclude and iRow are set to zero, no incremental blob
  39455. ** cursors are invalidated.
  39456. */
  39457. static int checkReadLocks(
  39458. Btree *pBtree,
  39459. Pgno pgnoRoot,
  39460. BtCursor *pExclude,
  39461. i64 iRow
  39462. ){
  39463. BtCursor *p;
  39464. BtShared *pBt = pBtree->pBt;
  39465. sqlite3 *db = pBtree->db;
  39466. assert( sqlite3BtreeHoldsMutex(pBtree) );
  39467. for(p=pBt->pCursor; p; p=p->pNext){
  39468. if( p==pExclude ) continue;
  39469. if( p->pgnoRoot!=pgnoRoot ) continue;
  39470. #ifndef SQLITE_OMIT_INCRBLOB
  39471. if( p->isIncrblobHandle && (
  39472. (!pExclude && iRow)
  39473. || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
  39474. )){
  39475. p->eState = CURSOR_INVALID;
  39476. }
  39477. #endif
  39478. if( p->eState!=CURSOR_VALID ) continue;
  39479. if( p->wrFlag==0
  39480. #ifndef SQLITE_OMIT_INCRBLOB
  39481. || p->isIncrblobHandle
  39482. #endif
  39483. ){
  39484. sqlite3 *dbOther = p->pBtree->db;
  39485. if( dbOther==0 ||
  39486. (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
  39487. return SQLITE_LOCKED;
  39488. }
  39489. }
  39490. }
  39491. return SQLITE_OK;
  39492. }
  39493. /*
  39494. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  39495. ** and the data is given by (pData,nData). The cursor is used only to
  39496. ** define what table the record should be inserted into. The cursor
  39497. ** is left pointing at a random location.
  39498. **
  39499. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  39500. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  39501. */
  39502. SQLITE_PRIVATE int sqlite3BtreeInsert(
  39503. BtCursor *pCur, /* Insert data into the table of this cursor */
  39504. const void *pKey, i64 nKey, /* The key of the new record */
  39505. const void *pData, int nData, /* The data of the new record */
  39506. int nZero, /* Number of extra 0 bytes to append to data */
  39507. int appendBias /* True if this is likely an append */
  39508. ){
  39509. int rc;
  39510. int loc;
  39511. int szNew;
  39512. int idx;
  39513. MemPage *pPage;
  39514. Btree *p = pCur->pBtree;
  39515. BtShared *pBt = p->pBt;
  39516. unsigned char *oldCell;
  39517. unsigned char *newCell = 0;
  39518. assert( cursorHoldsMutex(pCur) );
  39519. assert( pBt->inTransaction==TRANS_WRITE );
  39520. assert( !pBt->readOnly );
  39521. assert( pCur->wrFlag );
  39522. if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
  39523. return SQLITE_LOCKED; /* The table pCur points to has a read lock */
  39524. }
  39525. if( pCur->eState==CURSOR_FAULT ){
  39526. return pCur->skip;
  39527. }
  39528. /* Save the positions of any other cursors open on this table */
  39529. sqlite3BtreeClearCursor(pCur);
  39530. if(
  39531. SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
  39532. SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
  39533. ){
  39534. return rc;
  39535. }
  39536. pPage = pCur->apPage[pCur->iPage];
  39537. assert( pPage->intKey || nKey>=0 );
  39538. assert( pPage->leaf || !pPage->intKey );
  39539. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  39540. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  39541. loc==0 ? "overwrite" : "new entry"));
  39542. assert( pPage->isInit );
  39543. allocateTempSpace(pBt);
  39544. newCell = pBt->pTmpSpace;
  39545. if( newCell==0 ) return SQLITE_NOMEM;
  39546. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  39547. if( rc ) goto end_insert;
  39548. assert( szNew==cellSizePtr(pPage, newCell) );
  39549. assert( szNew<=MX_CELL_SIZE(pBt) );
  39550. idx = pCur->aiIdx[pCur->iPage];
  39551. if( loc==0 && CURSOR_VALID==pCur->eState ){
  39552. u16 szOld;
  39553. assert( idx<pPage->nCell );
  39554. rc = sqlite3PagerWrite(pPage->pDbPage);
  39555. if( rc ){
  39556. goto end_insert;
  39557. }
  39558. oldCell = findCell(pPage, idx);
  39559. if( !pPage->leaf ){
  39560. memcpy(newCell, oldCell, 4);
  39561. }
  39562. szOld = cellSizePtr(pPage, oldCell);
  39563. rc = clearCell(pPage, oldCell);
  39564. if( rc ) goto end_insert;
  39565. rc = dropCell(pPage, idx, szOld);
  39566. if( rc!=SQLITE_OK ) {
  39567. goto end_insert;
  39568. }
  39569. }else if( loc<0 && pPage->nCell>0 ){
  39570. assert( pPage->leaf );
  39571. idx = ++pCur->aiIdx[pCur->iPage];
  39572. pCur->info.nSize = 0;
  39573. pCur->validNKey = 0;
  39574. }else{
  39575. assert( pPage->leaf );
  39576. }
  39577. rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
  39578. if( rc==SQLITE_OK ){
  39579. rc = balance(pCur, 1);
  39580. }
  39581. /* Must make sure nOverflow is reset to zero even if the balance()
  39582. ** fails. Internal data structure corruption will result otherwise. */
  39583. pCur->apPage[pCur->iPage]->nOverflow = 0;
  39584. if( rc==SQLITE_OK ){
  39585. moveToRoot(pCur);
  39586. }
  39587. end_insert:
  39588. return rc;
  39589. }
  39590. /*
  39591. ** Delete the entry that the cursor is pointing to. The cursor
  39592. ** is left pointing at a arbitrary location.
  39593. */
  39594. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  39595. MemPage *pPage = pCur->apPage[pCur->iPage];
  39596. int idx;
  39597. unsigned char *pCell;
  39598. int rc;
  39599. Pgno pgnoChild = 0;
  39600. Btree *p = pCur->pBtree;
  39601. BtShared *pBt = p->pBt;
  39602. assert( cursorHoldsMutex(pCur) );
  39603. assert( pPage->isInit );
  39604. assert( pBt->inTransaction==TRANS_WRITE );
  39605. assert( !pBt->readOnly );
  39606. if( pCur->eState==CURSOR_FAULT ){
  39607. return pCur->skip;
  39608. }
  39609. if( NEVER(pCur->aiIdx[pCur->iPage]>=pPage->nCell) ){
  39610. return SQLITE_ERROR; /* The cursor is not pointing to anything */
  39611. }
  39612. assert( pCur->wrFlag );
  39613. if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
  39614. return SQLITE_LOCKED; /* The table pCur points to has a read lock */
  39615. }
  39616. /* Restore the current cursor position (a no-op if the cursor is not in
  39617. ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
  39618. ** open on the same table. Then call sqlite3PagerWrite() on the page
  39619. ** that the entry will be deleted from.
  39620. */
  39621. if(
  39622. (rc = restoreCursorPosition(pCur))!=0 ||
  39623. (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
  39624. (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
  39625. ){
  39626. return rc;
  39627. }
  39628. /* Locate the cell within its page and leave pCell pointing to the
  39629. ** data. The clearCell() call frees any overflow pages associated with the
  39630. ** cell. The cell itself is still intact.
  39631. */
  39632. idx = pCur->aiIdx[pCur->iPage];
  39633. pCell = findCell(pPage, idx);
  39634. if( !pPage->leaf ){
  39635. pgnoChild = get4byte(pCell);
  39636. }
  39637. rc = clearCell(pPage, pCell);
  39638. if( rc ){
  39639. return rc;
  39640. }
  39641. if( !pPage->leaf ){
  39642. /*
  39643. ** The entry we are about to delete is not a leaf so if we do not
  39644. ** do something we will leave a hole on an internal page.
  39645. ** We have to fill the hole by moving in a cell from a leaf. The
  39646. ** next Cell after the one to be deleted is guaranteed to exist and
  39647. ** to be a leaf so we can use it.
  39648. */
  39649. BtCursor leafCur;
  39650. MemPage *pLeafPage = 0;
  39651. unsigned char *pNext;
  39652. int notUsed;
  39653. unsigned char *tempCell = 0;
  39654. assert( !pPage->intKey );
  39655. sqlite3BtreeGetTempCursor(pCur, &leafCur);
  39656. rc = sqlite3BtreeNext(&leafCur, &notUsed);
  39657. if( rc==SQLITE_OK ){
  39658. assert( leafCur.aiIdx[leafCur.iPage]==0 );
  39659. pLeafPage = leafCur.apPage[leafCur.iPage];
  39660. rc = sqlite3PagerWrite(pLeafPage->pDbPage);
  39661. }
  39662. if( rc==SQLITE_OK ){
  39663. int leafCursorInvalid = 0;
  39664. u16 szNext;
  39665. TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
  39666. pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
  39667. dropCell(pPage, idx, cellSizePtr(pPage, pCell));
  39668. pNext = findCell(pLeafPage, 0);
  39669. szNext = cellSizePtr(pLeafPage, pNext);
  39670. assert( MX_CELL_SIZE(pBt)>=szNext+4 );
  39671. allocateTempSpace(pBt);
  39672. tempCell = pBt->pTmpSpace;
  39673. if( tempCell==0 ){
  39674. rc = SQLITE_NOMEM;
  39675. }
  39676. if( rc==SQLITE_OK ){
  39677. rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
  39678. }
  39679. /* The "if" statement in the next code block is critical. The
  39680. ** slightest error in that statement would allow SQLite to operate
  39681. ** correctly most of the time but produce very rare failures. To
  39682. ** guard against this, the following macros help to verify that
  39683. ** the "if" statement is well tested.
  39684. */
  39685. testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3
  39686. && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
  39687. testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3
  39688. && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
  39689. testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1
  39690. && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
  39691. testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
  39692. && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
  39693. testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
  39694. && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
  39695. if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
  39696. (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
  39697. ){
  39698. /* This branch is taken if the internal node is now either overflowing
  39699. ** or underfull and the leaf node will be underfull after the just cell
  39700. ** copied to the internal node is deleted from it. This is a special
  39701. ** case because the call to balance() to correct the internal node
  39702. ** may change the tree structure and invalidate the contents of
  39703. ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
  39704. ** used by the balance() required to correct the underfull leaf
  39705. ** node.
  39706. **
  39707. ** The formula used in the expression above are based on facets of
  39708. ** the SQLite file-format that do not change over time.
  39709. */
  39710. testcase( pPage->nFree==pBt->usableSize*2/3+1 );
  39711. testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
  39712. leafCursorInvalid = 1;
  39713. }
  39714. if( rc==SQLITE_OK ){
  39715. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  39716. put4byte(findOverflowCell(pPage, idx), pgnoChild);
  39717. VVA_ONLY( pCur->pagesShuffled = 0 );
  39718. rc = balance(pCur, 0);
  39719. }
  39720. if( rc==SQLITE_OK && leafCursorInvalid ){
  39721. /* The leaf-node is now underfull and so the tree needs to be
  39722. ** rebalanced. However, the balance() operation on the internal
  39723. ** node above may have modified the structure of the B-Tree and
  39724. ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
  39725. ** may not be trusted.
  39726. **
  39727. ** It is not possible to copy the ancestry from pCur, as the same
  39728. ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
  39729. ** arrays.
  39730. **
  39731. ** The call to saveCursorPosition() below internally saves the
  39732. ** key that leafCur is currently pointing to. Currently, there
  39733. ** are two copies of that key in the tree - one here on the leaf
  39734. ** page and one on some internal node in the tree. The copy on
  39735. ** the leaf node is always the next key in tree-order after the
  39736. ** copy on the internal node. So, the call to sqlite3BtreeNext()
  39737. ** calls restoreCursorPosition() to point the cursor to the copy
  39738. ** stored on the internal node, then advances to the next entry,
  39739. ** which happens to be the copy of the key on the internal node.
  39740. ** Net effect: leafCur is pointing back to the duplicate cell
  39741. ** that needs to be removed, and the leafCur.apPage[] and
  39742. ** leafCur.aiIdx[] arrays are correct.
  39743. */
  39744. VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
  39745. rc = saveCursorPosition(&leafCur);
  39746. if( rc==SQLITE_OK ){
  39747. rc = sqlite3BtreeNext(&leafCur, &notUsed);
  39748. }
  39749. pLeafPage = leafCur.apPage[leafCur.iPage];
  39750. assert( pLeafPage->pgno==leafPgno );
  39751. assert( leafCur.aiIdx[leafCur.iPage]==0 );
  39752. }
  39753. if( SQLITE_OK==rc
  39754. && SQLITE_OK==(rc = sqlite3PagerWrite(pLeafPage->pDbPage))
  39755. ){
  39756. dropCell(pLeafPage, 0, szNext);
  39757. VVA_ONLY( leafCur.pagesShuffled = 0 );
  39758. rc = balance(&leafCur, 0);
  39759. assert( leafCursorInvalid || !leafCur.pagesShuffled
  39760. || !pCur->pagesShuffled );
  39761. }
  39762. }
  39763. sqlite3BtreeReleaseTempCursor(&leafCur);
  39764. }else{
  39765. TRACE(("DELETE: table=%d delete from leaf %d\n",
  39766. pCur->pgnoRoot, pPage->pgno));
  39767. rc = dropCell(pPage, idx, cellSizePtr(pPage, pCell));
  39768. if( rc==SQLITE_OK ){
  39769. rc = balance(pCur, 0);
  39770. }
  39771. }
  39772. if( rc==SQLITE_OK ){
  39773. moveToRoot(pCur);
  39774. }
  39775. return rc;
  39776. }
  39777. /*
  39778. ** Create a new BTree table. Write into *piTable the page
  39779. ** number for the root page of the new table.
  39780. **
  39781. ** The type of type is determined by the flags parameter. Only the
  39782. ** following values of flags are currently in use. Other values for
  39783. ** flags might not work:
  39784. **
  39785. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  39786. ** BTREE_ZERODATA Used for SQL indices
  39787. */
  39788. static int btreeCreateTable(Btree *p, int *piTable, int flags){
  39789. BtShared *pBt = p->pBt;
  39790. MemPage *pRoot;
  39791. Pgno pgnoRoot;
  39792. int rc;
  39793. assert( sqlite3BtreeHoldsMutex(p) );
  39794. assert( pBt->inTransaction==TRANS_WRITE );
  39795. assert( !pBt->readOnly );
  39796. #ifdef SQLITE_OMIT_AUTOVACUUM
  39797. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  39798. if( rc ){
  39799. return rc;
  39800. }
  39801. #else
  39802. if( pBt->autoVacuum ){
  39803. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  39804. MemPage *pPageMove; /* The page to move to. */
  39805. /* Creating a new table may probably require moving an existing database
  39806. ** to make room for the new tables root page. In case this page turns
  39807. ** out to be an overflow page, delete all overflow page-map caches
  39808. ** held by open cursors.
  39809. */
  39810. invalidateAllOverflowCache(pBt);
  39811. /* Read the value of meta[3] from the database to determine where the
  39812. ** root page of the new table should go. meta[3] is the largest root-page
  39813. ** created so far, so the new root-page is (meta[3]+1).
  39814. */
  39815. rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
  39816. if( rc!=SQLITE_OK ){
  39817. return rc;
  39818. }
  39819. pgnoRoot++;
  39820. /* The new root-page may not be allocated on a pointer-map page, or the
  39821. ** PENDING_BYTE page.
  39822. */
  39823. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  39824. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  39825. pgnoRoot++;
  39826. }
  39827. assert( pgnoRoot>=3 );
  39828. /* Allocate a page. The page that currently resides at pgnoRoot will
  39829. ** be moved to the allocated page (unless the allocated page happens
  39830. ** to reside at pgnoRoot).
  39831. */
  39832. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
  39833. if( rc!=SQLITE_OK ){
  39834. return rc;
  39835. }
  39836. if( pgnoMove!=pgnoRoot ){
  39837. /* pgnoRoot is the page that will be used for the root-page of
  39838. ** the new table (assuming an error did not occur). But we were
  39839. ** allocated pgnoMove. If required (i.e. if it was not allocated
  39840. ** by extending the file), the current page at position pgnoMove
  39841. ** is already journaled.
  39842. */
  39843. u8 eType;
  39844. Pgno iPtrPage;
  39845. releasePage(pPageMove);
  39846. /* Move the page currently at pgnoRoot to pgnoMove. */
  39847. rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  39848. if( rc!=SQLITE_OK ){
  39849. return rc;
  39850. }
  39851. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  39852. if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  39853. releasePage(pRoot);
  39854. return rc;
  39855. }
  39856. assert( eType!=PTRMAP_ROOTPAGE );
  39857. assert( eType!=PTRMAP_FREEPAGE );
  39858. rc = sqlite3PagerWrite(pRoot->pDbPage);
  39859. if( rc!=SQLITE_OK ){
  39860. releasePage(pRoot);
  39861. return rc;
  39862. }
  39863. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  39864. releasePage(pRoot);
  39865. /* Obtain the page at pgnoRoot */
  39866. if( rc!=SQLITE_OK ){
  39867. return rc;
  39868. }
  39869. rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  39870. if( rc!=SQLITE_OK ){
  39871. return rc;
  39872. }
  39873. rc = sqlite3PagerWrite(pRoot->pDbPage);
  39874. if( rc!=SQLITE_OK ){
  39875. releasePage(pRoot);
  39876. return rc;
  39877. }
  39878. }else{
  39879. pRoot = pPageMove;
  39880. }
  39881. /* Update the pointer-map and meta-data with the new root-page number. */
  39882. rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
  39883. if( rc ){
  39884. releasePage(pRoot);
  39885. return rc;
  39886. }
  39887. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  39888. if( rc ){
  39889. releasePage(pRoot);
  39890. return rc;
  39891. }
  39892. }else{
  39893. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  39894. if( rc ) return rc;
  39895. }
  39896. #endif
  39897. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  39898. zeroPage(pRoot, flags | PTF_LEAF);
  39899. sqlite3PagerUnref(pRoot->pDbPage);
  39900. *piTable = (int)pgnoRoot;
  39901. return SQLITE_OK;
  39902. }
  39903. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  39904. int rc;
  39905. sqlite3BtreeEnter(p);
  39906. p->pBt->db = p->db;
  39907. rc = btreeCreateTable(p, piTable, flags);
  39908. sqlite3BtreeLeave(p);
  39909. return rc;
  39910. }
  39911. /*
  39912. ** Erase the given database page and all its children. Return
  39913. ** the page to the freelist.
  39914. */
  39915. static int clearDatabasePage(
  39916. BtShared *pBt, /* The BTree that contains the table */
  39917. Pgno pgno, /* Page number to clear */
  39918. int freePageFlag, /* Deallocate page if true */
  39919. int *pnChange
  39920. ){
  39921. MemPage *pPage = 0;
  39922. int rc;
  39923. unsigned char *pCell;
  39924. int i;
  39925. assert( sqlite3_mutex_held(pBt->mutex) );
  39926. if( pgno>pagerPagecount(pBt) ){
  39927. return SQLITE_CORRUPT_BKPT;
  39928. }
  39929. rc = getAndInitPage(pBt, pgno, &pPage);
  39930. if( rc ) goto cleardatabasepage_out;
  39931. for(i=0; i<pPage->nCell; i++){
  39932. pCell = findCell(pPage, i);
  39933. if( !pPage->leaf ){
  39934. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  39935. if( rc ) goto cleardatabasepage_out;
  39936. }
  39937. rc = clearCell(pPage, pCell);
  39938. if( rc ) goto cleardatabasepage_out;
  39939. }
  39940. if( !pPage->leaf ){
  39941. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
  39942. if( rc ) goto cleardatabasepage_out;
  39943. }else if( pnChange ){
  39944. assert( pPage->intKey );
  39945. *pnChange += pPage->nCell;
  39946. }
  39947. if( freePageFlag ){
  39948. rc = freePage(pPage);
  39949. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  39950. zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  39951. }
  39952. cleardatabasepage_out:
  39953. releasePage(pPage);
  39954. return rc;
  39955. }
  39956. /*
  39957. ** Delete all information from a single table in the database. iTable is
  39958. ** the page number of the root of the table. After this routine returns,
  39959. ** the root page is empty, but still exists.
  39960. **
  39961. ** This routine will fail with SQLITE_LOCKED if there are any open
  39962. ** read cursors on the table. Open write cursors are moved to the
  39963. ** root of the table.
  39964. **
  39965. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  39966. ** integer value pointed to by pnChange is incremented by the number of
  39967. ** entries in the table.
  39968. */
  39969. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  39970. int rc;
  39971. BtShared *pBt = p->pBt;
  39972. sqlite3BtreeEnter(p);
  39973. pBt->db = p->db;
  39974. assert( p->inTrans==TRANS_WRITE );
  39975. if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
  39976. /* nothing to do */
  39977. }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
  39978. /* nothing to do */
  39979. }else{
  39980. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  39981. }
  39982. sqlite3BtreeLeave(p);
  39983. return rc;
  39984. }
  39985. /*
  39986. ** Erase all information in a table and add the root of the table to
  39987. ** the freelist. Except, the root of the principle table (the one on
  39988. ** page 1) is never added to the freelist.
  39989. **
  39990. ** This routine will fail with SQLITE_LOCKED if there are any open
  39991. ** cursors on the table.
  39992. **
  39993. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  39994. ** root page in the database file, then the last root page
  39995. ** in the database file is moved into the slot formerly occupied by
  39996. ** iTable and that last slot formerly occupied by the last root page
  39997. ** is added to the freelist instead of iTable. In this say, all
  39998. ** root pages are kept at the beginning of the database file, which
  39999. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  40000. ** page number that used to be the last root page in the file before
  40001. ** the move. If no page gets moved, *piMoved is set to 0.
  40002. ** The last root page is recorded in meta[3] and the value of
  40003. ** meta[3] is updated by this procedure.
  40004. */
  40005. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  40006. int rc;
  40007. MemPage *pPage = 0;
  40008. BtShared *pBt = p->pBt;
  40009. assert( sqlite3BtreeHoldsMutex(p) );
  40010. assert( p->inTrans==TRANS_WRITE );
  40011. /* It is illegal to drop a table if any cursors are open on the
  40012. ** database. This is because in auto-vacuum mode the backend may
  40013. ** need to move another root-page to fill a gap left by the deleted
  40014. ** root page. If an open cursor was using this page a problem would
  40015. ** occur.
  40016. */
  40017. if( pBt->pCursor ){
  40018. return SQLITE_LOCKED;
  40019. }
  40020. rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  40021. if( rc ) return rc;
  40022. rc = sqlite3BtreeClearTable(p, iTable, 0);
  40023. if( rc ){
  40024. releasePage(pPage);
  40025. return rc;
  40026. }
  40027. *piMoved = 0;
  40028. if( iTable>1 ){
  40029. #ifdef SQLITE_OMIT_AUTOVACUUM
  40030. rc = freePage(pPage);
  40031. releasePage(pPage);
  40032. #else
  40033. if( pBt->autoVacuum ){
  40034. Pgno maxRootPgno;
  40035. rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
  40036. if( rc!=SQLITE_OK ){
  40037. releasePage(pPage);
  40038. return rc;
  40039. }
  40040. if( iTable==maxRootPgno ){
  40041. /* If the table being dropped is the table with the largest root-page
  40042. ** number in the database, put the root page on the free list.
  40043. */
  40044. rc = freePage(pPage);
  40045. releasePage(pPage);
  40046. if( rc!=SQLITE_OK ){
  40047. return rc;
  40048. }
  40049. }else{
  40050. /* The table being dropped does not have the largest root-page
  40051. ** number in the database. So move the page that does into the
  40052. ** gap left by the deleted root-page.
  40053. */
  40054. MemPage *pMove;
  40055. releasePage(pPage);
  40056. rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
  40057. if( rc!=SQLITE_OK ){
  40058. return rc;
  40059. }
  40060. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  40061. releasePage(pMove);
  40062. if( rc!=SQLITE_OK ){
  40063. return rc;
  40064. }
  40065. rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
  40066. if( rc!=SQLITE_OK ){
  40067. return rc;
  40068. }
  40069. rc = freePage(pMove);
  40070. releasePage(pMove);
  40071. if( rc!=SQLITE_OK ){
  40072. return rc;
  40073. }
  40074. *piMoved = maxRootPgno;
  40075. }
  40076. /* Set the new 'max-root-page' value in the database header. This
  40077. ** is the old value less one, less one more if that happens to
  40078. ** be a root-page number, less one again if that is the
  40079. ** PENDING_BYTE_PAGE.
  40080. */
  40081. maxRootPgno--;
  40082. if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
  40083. maxRootPgno--;
  40084. }
  40085. if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
  40086. maxRootPgno--;
  40087. }
  40088. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  40089. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  40090. }else{
  40091. rc = freePage(pPage);
  40092. releasePage(pPage);
  40093. }
  40094. #endif
  40095. }else{
  40096. /* If sqlite3BtreeDropTable was called on page 1. */
  40097. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  40098. releasePage(pPage);
  40099. }
  40100. return rc;
  40101. }
  40102. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  40103. int rc;
  40104. sqlite3BtreeEnter(p);
  40105. p->pBt->db = p->db;
  40106. rc = btreeDropTable(p, iTable, piMoved);
  40107. sqlite3BtreeLeave(p);
  40108. return rc;
  40109. }
  40110. /*
  40111. ** Read the meta-information out of a database file. Meta[0]
  40112. ** is the number of free pages currently in the database. Meta[1]
  40113. ** through meta[15] are available for use by higher layers. Meta[0]
  40114. ** is read-only, the others are read/write.
  40115. **
  40116. ** The schema layer numbers meta values differently. At the schema
  40117. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  40118. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  40119. */
  40120. SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  40121. DbPage *pDbPage = 0;
  40122. int rc;
  40123. unsigned char *pP1;
  40124. BtShared *pBt = p->pBt;
  40125. sqlite3BtreeEnter(p);
  40126. pBt->db = p->db;
  40127. /* Reading a meta-data value requires a read-lock on page 1 (and hence
  40128. ** the sqlite_master table. We grab this lock regardless of whether or
  40129. ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
  40130. ** 1 is treated as a special case by queryTableLock() and lockTable()).
  40131. */
  40132. rc = queryTableLock(p, 1, READ_LOCK);
  40133. if( rc!=SQLITE_OK ){
  40134. sqlite3BtreeLeave(p);
  40135. return rc;
  40136. }
  40137. assert( idx>=0 && idx<=15 );
  40138. if( pBt->pPage1 ){
  40139. /* The b-tree is already holding a reference to page 1 of the database
  40140. ** file. In this case the required meta-data value can be read directly
  40141. ** from the page data of this reference. This is slightly faster than
  40142. ** requesting a new reference from the pager layer.
  40143. */
  40144. pP1 = (unsigned char *)pBt->pPage1->aData;
  40145. }else{
  40146. /* The b-tree does not have a reference to page 1 of the database file.
  40147. ** Obtain one from the pager layer.
  40148. */
  40149. rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
  40150. if( rc ){
  40151. sqlite3BtreeLeave(p);
  40152. return rc;
  40153. }
  40154. pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
  40155. }
  40156. *pMeta = get4byte(&pP1[36 + idx*4]);
  40157. /* If the b-tree is not holding a reference to page 1, then one was
  40158. ** requested from the pager layer in the above block. Release it now.
  40159. */
  40160. if( !pBt->pPage1 ){
  40161. sqlite3PagerUnref(pDbPage);
  40162. }
  40163. /* If autovacuumed is disabled in this build but we are trying to
  40164. ** access an autovacuumed database, then make the database readonly.
  40165. */
  40166. #ifdef SQLITE_OMIT_AUTOVACUUM
  40167. if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
  40168. #endif
  40169. /* Grab the read-lock on page 1. */
  40170. rc = lockTable(p, 1, READ_LOCK);
  40171. sqlite3BtreeLeave(p);
  40172. return rc;
  40173. }
  40174. /*
  40175. ** Write meta-information back into the database. Meta[0] is
  40176. ** read-only and may not be written.
  40177. */
  40178. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  40179. BtShared *pBt = p->pBt;
  40180. unsigned char *pP1;
  40181. int rc;
  40182. assert( idx>=1 && idx<=15 );
  40183. sqlite3BtreeEnter(p);
  40184. pBt->db = p->db;
  40185. assert( p->inTrans==TRANS_WRITE );
  40186. assert( pBt->pPage1!=0 );
  40187. pP1 = pBt->pPage1->aData;
  40188. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  40189. if( rc==SQLITE_OK ){
  40190. put4byte(&pP1[36 + idx*4], iMeta);
  40191. #ifndef SQLITE_OMIT_AUTOVACUUM
  40192. if( idx==7 ){
  40193. assert( pBt->autoVacuum || iMeta==0 );
  40194. assert( iMeta==0 || iMeta==1 );
  40195. pBt->incrVacuum = (u8)iMeta;
  40196. }
  40197. #endif
  40198. }
  40199. sqlite3BtreeLeave(p);
  40200. return rc;
  40201. }
  40202. /*
  40203. ** Return the flag byte at the beginning of the page that the cursor
  40204. ** is currently pointing to.
  40205. */
  40206. SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
  40207. /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
  40208. ** restoreCursorPosition() here.
  40209. */
  40210. MemPage *pPage;
  40211. restoreCursorPosition(pCur);
  40212. pPage = pCur->apPage[pCur->iPage];
  40213. assert( cursorHoldsMutex(pCur) );
  40214. assert( pPage!=0 );
  40215. assert( pPage->pBt==pCur->pBt );
  40216. return pPage->aData[pPage->hdrOffset];
  40217. }
  40218. /*
  40219. ** Return the pager associated with a BTree. This routine is used for
  40220. ** testing and debugging only.
  40221. */
  40222. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  40223. return p->pBt->pPager;
  40224. }
  40225. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  40226. /*
  40227. ** Append a message to the error message string.
  40228. */
  40229. static void checkAppendMsg(
  40230. IntegrityCk *pCheck,
  40231. char *zMsg1,
  40232. const char *zFormat,
  40233. ...
  40234. ){
  40235. va_list ap;
  40236. if( !pCheck->mxErr ) return;
  40237. pCheck->mxErr--;
  40238. pCheck->nErr++;
  40239. va_start(ap, zFormat);
  40240. if( pCheck->errMsg.nChar ){
  40241. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  40242. }
  40243. if( zMsg1 ){
  40244. sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  40245. }
  40246. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  40247. va_end(ap);
  40248. if( pCheck->errMsg.mallocFailed ){
  40249. pCheck->mallocFailed = 1;
  40250. }
  40251. }
  40252. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  40253. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  40254. /*
  40255. ** Add 1 to the reference count for page iPage. If this is the second
  40256. ** reference to the page, add an error message to pCheck->zErrMsg.
  40257. ** Return 1 if there are 2 ore more references to the page and 0 if
  40258. ** if this is the first reference to the page.
  40259. **
  40260. ** Also check that the page number is in bounds.
  40261. */
  40262. static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  40263. if( iPage==0 ) return 1;
  40264. if( iPage>pCheck->nPage ){
  40265. checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
  40266. return 1;
  40267. }
  40268. if( pCheck->anRef[iPage]==1 ){
  40269. checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
  40270. return 1;
  40271. }
  40272. return (pCheck->anRef[iPage]++)>1;
  40273. }
  40274. #ifndef SQLITE_OMIT_AUTOVACUUM
  40275. /*
  40276. ** Check that the entry in the pointer-map for page iChild maps to
  40277. ** page iParent, pointer type ptrType. If not, append an error message
  40278. ** to pCheck.
  40279. */
  40280. static void checkPtrmap(
  40281. IntegrityCk *pCheck, /* Integrity check context */
  40282. Pgno iChild, /* Child page number */
  40283. u8 eType, /* Expected pointer map type */
  40284. Pgno iParent, /* Expected pointer map parent page number */
  40285. char *zContext /* Context description (used for error msg) */
  40286. ){
  40287. int rc;
  40288. u8 ePtrmapType;
  40289. Pgno iPtrmapParent;
  40290. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  40291. if( rc!=SQLITE_OK ){
  40292. if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
  40293. checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
  40294. return;
  40295. }
  40296. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  40297. checkAppendMsg(pCheck, zContext,
  40298. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  40299. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  40300. }
  40301. }
  40302. #endif
  40303. /*
  40304. ** Check the integrity of the freelist or of an overflow page list.
  40305. ** Verify that the number of pages on the list is N.
  40306. */
  40307. static void checkList(
  40308. IntegrityCk *pCheck, /* Integrity checking context */
  40309. int isFreeList, /* True for a freelist. False for overflow page list */
  40310. int iPage, /* Page number for first page in the list */
  40311. int N, /* Expected number of pages in the list */
  40312. char *zContext /* Context for error messages */
  40313. ){
  40314. int i;
  40315. int expected = N;
  40316. int iFirst = iPage;
  40317. while( N-- > 0 && pCheck->mxErr ){
  40318. DbPage *pOvflPage;
  40319. unsigned char *pOvflData;
  40320. if( iPage<1 ){
  40321. checkAppendMsg(pCheck, zContext,
  40322. "%d of %d pages missing from overflow list starting at %d",
  40323. N+1, expected, iFirst);
  40324. break;
  40325. }
  40326. if( checkRef(pCheck, iPage, zContext) ) break;
  40327. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  40328. checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
  40329. break;
  40330. }
  40331. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  40332. if( isFreeList ){
  40333. int n = get4byte(&pOvflData[4]);
  40334. #ifndef SQLITE_OMIT_AUTOVACUUM
  40335. if( pCheck->pBt->autoVacuum ){
  40336. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
  40337. }
  40338. #endif
  40339. if( n>pCheck->pBt->usableSize/4-2 ){
  40340. checkAppendMsg(pCheck, zContext,
  40341. "freelist leaf count too big on page %d", iPage);
  40342. N--;
  40343. }else{
  40344. for(i=0; i<n; i++){
  40345. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  40346. #ifndef SQLITE_OMIT_AUTOVACUUM
  40347. if( pCheck->pBt->autoVacuum ){
  40348. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
  40349. }
  40350. #endif
  40351. checkRef(pCheck, iFreePage, zContext);
  40352. }
  40353. N -= n;
  40354. }
  40355. }
  40356. #ifndef SQLITE_OMIT_AUTOVACUUM
  40357. else{
  40358. /* If this database supports auto-vacuum and iPage is not the last
  40359. ** page in this overflow list, check that the pointer-map entry for
  40360. ** the following page matches iPage.
  40361. */
  40362. if( pCheck->pBt->autoVacuum && N>0 ){
  40363. i = get4byte(pOvflData);
  40364. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
  40365. }
  40366. }
  40367. #endif
  40368. iPage = get4byte(pOvflData);
  40369. sqlite3PagerUnref(pOvflPage);
  40370. }
  40371. }
  40372. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  40373. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  40374. /*
  40375. ** Do various sanity checks on a single page of a tree. Return
  40376. ** the tree depth. Root pages return 0. Parents of root pages
  40377. ** return 1, and so forth.
  40378. **
  40379. ** These checks are done:
  40380. **
  40381. ** 1. Make sure that cells and freeblocks do not overlap
  40382. ** but combine to completely cover the page.
  40383. ** NO 2. Make sure cell keys are in order.
  40384. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  40385. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  40386. ** 5. Check the integrity of overflow pages.
  40387. ** 6. Recursively call checkTreePage on all children.
  40388. ** 7. Verify that the depth of all children is the same.
  40389. ** 8. Make sure this page is at least 33% full or else it is
  40390. ** the root of the tree.
  40391. */
  40392. static int checkTreePage(
  40393. IntegrityCk *pCheck, /* Context for the sanity check */
  40394. int iPage, /* Page number of the page to check */
  40395. char *zParentContext /* Parent context */
  40396. ){
  40397. MemPage *pPage;
  40398. int i, rc, depth, d2, pgno, cnt;
  40399. int hdr, cellStart;
  40400. int nCell;
  40401. u8 *data;
  40402. BtShared *pBt;
  40403. int usableSize;
  40404. char zContext[100];
  40405. char *hit = 0;
  40406. sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
  40407. /* Check that the page exists
  40408. */
  40409. pBt = pCheck->pBt;
  40410. usableSize = pBt->usableSize;
  40411. if( iPage==0 ) return 0;
  40412. if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  40413. if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  40414. if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
  40415. checkAppendMsg(pCheck, zContext,
  40416. "unable to get the page. error code=%d", rc);
  40417. return 0;
  40418. }
  40419. if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
  40420. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  40421. checkAppendMsg(pCheck, zContext,
  40422. "sqlite3BtreeInitPage() returns error code %d", rc);
  40423. releasePage(pPage);
  40424. return 0;
  40425. }
  40426. /* Check out all the cells.
  40427. */
  40428. depth = 0;
  40429. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  40430. u8 *pCell;
  40431. u32 sz;
  40432. CellInfo info;
  40433. /* Check payload overflow pages
  40434. */
  40435. sqlite3_snprintf(sizeof(zContext), zContext,
  40436. "On tree page %d cell %d: ", iPage, i);
  40437. pCell = findCell(pPage,i);
  40438. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  40439. sz = info.nData;
  40440. if( !pPage->intKey ) sz += (int)info.nKey;
  40441. assert( sz==info.nPayload );
  40442. if( sz>info.nLocal ){
  40443. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  40444. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  40445. #ifndef SQLITE_OMIT_AUTOVACUUM
  40446. if( pBt->autoVacuum ){
  40447. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
  40448. }
  40449. #endif
  40450. checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
  40451. }
  40452. /* Check sanity of left child page.
  40453. */
  40454. if( !pPage->leaf ){
  40455. pgno = get4byte(pCell);
  40456. #ifndef SQLITE_OMIT_AUTOVACUUM
  40457. if( pBt->autoVacuum ){
  40458. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  40459. }
  40460. #endif
  40461. d2 = checkTreePage(pCheck, pgno, zContext);
  40462. if( i>0 && d2!=depth ){
  40463. checkAppendMsg(pCheck, zContext, "Child page depth differs");
  40464. }
  40465. depth = d2;
  40466. }
  40467. }
  40468. if( !pPage->leaf ){
  40469. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  40470. sqlite3_snprintf(sizeof(zContext), zContext,
  40471. "On page %d at right child: ", iPage);
  40472. #ifndef SQLITE_OMIT_AUTOVACUUM
  40473. if( pBt->autoVacuum ){
  40474. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
  40475. }
  40476. #endif
  40477. checkTreePage(pCheck, pgno, zContext);
  40478. }
  40479. /* Check for complete coverage of the page
  40480. */
  40481. data = pPage->aData;
  40482. hdr = pPage->hdrOffset;
  40483. hit = sqlite3PageMalloc( pBt->pageSize );
  40484. if( hit==0 ){
  40485. pCheck->mallocFailed = 1;
  40486. }else{
  40487. u16 contentOffset = get2byte(&data[hdr+5]);
  40488. if (contentOffset > usableSize) {
  40489. checkAppendMsg(pCheck, 0,
  40490. "Corruption detected in header on page %d",iPage,0);
  40491. goto check_page_abort;
  40492. }
  40493. memset(hit+contentOffset, 0, usableSize-contentOffset);
  40494. memset(hit, 1, contentOffset);
  40495. nCell = get2byte(&data[hdr+3]);
  40496. cellStart = hdr + 12 - 4*pPage->leaf;
  40497. for(i=0; i<nCell; i++){
  40498. int pc = get2byte(&data[cellStart+i*2]);
  40499. u16 size = 1024;
  40500. int j;
  40501. if( pc<=usableSize ){
  40502. size = cellSizePtr(pPage, &data[pc]);
  40503. }
  40504. if( (pc+size-1)>=usableSize || pc<0 ){
  40505. checkAppendMsg(pCheck, 0,
  40506. "Corruption detected in cell %d on page %d",i,iPage,0);
  40507. }else{
  40508. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  40509. }
  40510. }
  40511. for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
  40512. cnt++){
  40513. int size = get2byte(&data[i+2]);
  40514. int j;
  40515. if( (i+size-1)>=usableSize || i<0 ){
  40516. checkAppendMsg(pCheck, 0,
  40517. "Corruption detected in cell %d on page %d",i,iPage,0);
  40518. }else{
  40519. for(j=i+size-1; j>=i; j--) hit[j]++;
  40520. }
  40521. i = get2byte(&data[i]);
  40522. }
  40523. for(i=cnt=0; i<usableSize; i++){
  40524. if( hit[i]==0 ){
  40525. cnt++;
  40526. }else if( hit[i]>1 ){
  40527. checkAppendMsg(pCheck, 0,
  40528. "Multiple uses for byte %d of page %d", i, iPage);
  40529. break;
  40530. }
  40531. }
  40532. if( cnt!=data[hdr+7] ){
  40533. checkAppendMsg(pCheck, 0,
  40534. "Fragmented space is %d byte reported as %d on page %d",
  40535. cnt, data[hdr+7], iPage);
  40536. }
  40537. }
  40538. check_page_abort:
  40539. if (hit) sqlite3PageFree(hit);
  40540. releasePage(pPage);
  40541. return depth+1;
  40542. }
  40543. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  40544. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  40545. /*
  40546. ** This routine does a complete check of the given BTree file. aRoot[] is
  40547. ** an array of pages numbers were each page number is the root page of
  40548. ** a table. nRoot is the number of entries in aRoot.
  40549. **
  40550. ** Write the number of error seen in *pnErr. Except for some memory
  40551. ** allocation errors, an error message held in memory obtained from
  40552. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  40553. ** returned. If a memory allocation error occurs, NULL is returned.
  40554. */
  40555. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  40556. Btree *p, /* The btree to be checked */
  40557. int *aRoot, /* An array of root pages numbers for individual trees */
  40558. int nRoot, /* Number of entries in aRoot[] */
  40559. int mxErr, /* Stop reporting errors after this many */
  40560. int *pnErr /* Write number of errors seen to this variable */
  40561. ){
  40562. Pgno i;
  40563. int nRef;
  40564. IntegrityCk sCheck;
  40565. BtShared *pBt = p->pBt;
  40566. char zErr[100];
  40567. sqlite3BtreeEnter(p);
  40568. pBt->db = p->db;
  40569. nRef = sqlite3PagerRefcount(pBt->pPager);
  40570. if( lockBtreeWithRetry(p)!=SQLITE_OK ){
  40571. *pnErr = 1;
  40572. sqlite3BtreeLeave(p);
  40573. return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
  40574. }
  40575. sCheck.pBt = pBt;
  40576. sCheck.pPager = pBt->pPager;
  40577. sCheck.nPage = pagerPagecount(sCheck.pBt);
  40578. sCheck.mxErr = mxErr;
  40579. sCheck.nErr = 0;
  40580. sCheck.mallocFailed = 0;
  40581. *pnErr = 0;
  40582. if( sCheck.nPage==0 ){
  40583. unlockBtreeIfUnused(pBt);
  40584. sqlite3BtreeLeave(p);
  40585. return 0;
  40586. }
  40587. sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
  40588. if( !sCheck.anRef ){
  40589. unlockBtreeIfUnused(pBt);
  40590. *pnErr = 1;
  40591. sqlite3BtreeLeave(p);
  40592. return 0;
  40593. }
  40594. for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
  40595. i = PENDING_BYTE_PAGE(pBt);
  40596. if( i<=sCheck.nPage ){
  40597. sCheck.anRef[i] = 1;
  40598. }
  40599. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
  40600. /* Check the integrity of the freelist
  40601. */
  40602. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  40603. get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
  40604. /* Check all the tables.
  40605. */
  40606. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  40607. if( aRoot[i]==0 ) continue;
  40608. #ifndef SQLITE_OMIT_AUTOVACUUM
  40609. if( pBt->autoVacuum && aRoot[i]>1 ){
  40610. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
  40611. }
  40612. #endif
  40613. checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
  40614. }
  40615. /* Make sure every page in the file is referenced
  40616. */
  40617. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  40618. #ifdef SQLITE_OMIT_AUTOVACUUM
  40619. if( sCheck.anRef[i]==0 ){
  40620. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  40621. }
  40622. #else
  40623. /* If the database supports auto-vacuum, make sure no tables contain
  40624. ** references to pointer-map pages.
  40625. */
  40626. if( sCheck.anRef[i]==0 &&
  40627. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  40628. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  40629. }
  40630. if( sCheck.anRef[i]!=0 &&
  40631. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  40632. checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
  40633. }
  40634. #endif
  40635. }
  40636. /* Make sure this analysis did not leave any unref() pages.
  40637. ** This is an internal consistency check; an integrity check
  40638. ** of the integrity check.
  40639. */
  40640. unlockBtreeIfUnused(pBt);
  40641. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  40642. checkAppendMsg(&sCheck, 0,
  40643. "Outstanding page count goes from %d to %d during this analysis",
  40644. nRef, sqlite3PagerRefcount(pBt->pPager)
  40645. );
  40646. }
  40647. /* Clean up and report errors.
  40648. */
  40649. sqlite3BtreeLeave(p);
  40650. sqlite3_free(sCheck.anRef);
  40651. if( sCheck.mallocFailed ){
  40652. sqlite3StrAccumReset(&sCheck.errMsg);
  40653. *pnErr = sCheck.nErr+1;
  40654. return 0;
  40655. }
  40656. *pnErr = sCheck.nErr;
  40657. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  40658. return sqlite3StrAccumFinish(&sCheck.errMsg);
  40659. }
  40660. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  40661. /*
  40662. ** Return the full pathname of the underlying database file.
  40663. **
  40664. ** The pager filename is invariant as long as the pager is
  40665. ** open so it is safe to access without the BtShared mutex.
  40666. */
  40667. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  40668. assert( p->pBt->pPager!=0 );
  40669. return sqlite3PagerFilename(p->pBt->pPager);
  40670. }
  40671. /*
  40672. ** Return the pathname of the directory that contains the database file.
  40673. **
  40674. ** The pager directory name is invariant as long as the pager is
  40675. ** open so it is safe to access without the BtShared mutex.
  40676. */
  40677. SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *p){
  40678. assert( p->pBt->pPager!=0 );
  40679. return sqlite3PagerDirname(p->pBt->pPager);
  40680. }
  40681. /*
  40682. ** Return the pathname of the journal file for this database. The return
  40683. ** value of this routine is the same regardless of whether the journal file
  40684. ** has been created or not.
  40685. **
  40686. ** The pager journal filename is invariant as long as the pager is
  40687. ** open so it is safe to access without the BtShared mutex.
  40688. */
  40689. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  40690. assert( p->pBt->pPager!=0 );
  40691. return sqlite3PagerJournalname(p->pBt->pPager);
  40692. }
  40693. #ifndef SQLITE_OMIT_VACUUM
  40694. /*
  40695. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  40696. ** must be active for both files.
  40697. **
  40698. ** The size of file pTo may be reduced by this operation.
  40699. ** If anything goes wrong, the transaction on pTo is rolled back.
  40700. **
  40701. ** If successful, CommitPhaseOne() may be called on pTo before returning.
  40702. ** The caller should finish committing the transaction on pTo by calling
  40703. ** sqlite3BtreeCommit().
  40704. */
  40705. static int btreeCopyFile(Btree *pTo, Btree *pFrom){
  40706. int rc = SQLITE_OK;
  40707. Pgno i;
  40708. Pgno nFromPage; /* Number of pages in pFrom */
  40709. Pgno nToPage; /* Number of pages in pTo */
  40710. Pgno nNewPage; /* Number of pages in pTo after the copy */
  40711. Pgno iSkip; /* Pending byte page in pTo */
  40712. int nToPageSize; /* Page size of pTo in bytes */
  40713. int nFromPageSize; /* Page size of pFrom in bytes */
  40714. BtShared *pBtTo = pTo->pBt;
  40715. BtShared *pBtFrom = pFrom->pBt;
  40716. pBtTo->db = pTo->db;
  40717. pBtFrom->db = pFrom->db;
  40718. nToPageSize = pBtTo->pageSize;
  40719. nFromPageSize = pBtFrom->pageSize;
  40720. assert( pTo->inTrans==TRANS_WRITE );
  40721. assert( pFrom->inTrans==TRANS_WRITE );
  40722. if( NEVER(pBtTo->pCursor) ){
  40723. return SQLITE_BUSY;
  40724. }
  40725. nToPage = pagerPagecount(pBtTo);
  40726. nFromPage = pagerPagecount(pBtFrom);
  40727. iSkip = PENDING_BYTE_PAGE(pBtTo);
  40728. /* Variable nNewPage is the number of pages required to store the
  40729. ** contents of pFrom using the current page-size of pTo.
  40730. */
  40731. nNewPage = (Pgno)
  40732. (((i64)nFromPage*(i64)nFromPageSize+(i64)nToPageSize-1)/(i64)nToPageSize);
  40733. for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
  40734. /* Journal the original page.
  40735. **
  40736. ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
  40737. ** in database *pTo (before the copy). This page is never written
  40738. ** into the journal file. Unless i==iSkip or the page was not
  40739. ** present in pTo before the copy operation, journal page i from pTo.
  40740. */
  40741. if( i!=iSkip && i<=nToPage ){
  40742. DbPage *pDbPage = 0;
  40743. rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
  40744. if( rc==SQLITE_OK ){
  40745. rc = sqlite3PagerWrite(pDbPage);
  40746. if( rc==SQLITE_OK && i>nFromPage ){
  40747. /* Yeah. It seems wierd to call DontWrite() right after Write(). But
  40748. ** that is because the names of those procedures do not exactly
  40749. ** represent what they do. Write() really means "put this page in the
  40750. ** rollback journal and mark it as dirty so that it will be written
  40751. ** to the database file later." DontWrite() undoes the second part of
  40752. ** that and prevents the page from being written to the database. The
  40753. ** page is still on the rollback journal, though. And that is the
  40754. ** whole point of this block: to put pages on the rollback journal.
  40755. */
  40756. rc = sqlite3PagerDontWrite(pDbPage);
  40757. }
  40758. sqlite3PagerUnref(pDbPage);
  40759. }
  40760. }
  40761. /* Overwrite the data in page i of the target database */
  40762. if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
  40763. DbPage *pToPage = 0;
  40764. sqlite3_int64 iOff;
  40765. rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
  40766. if( rc==SQLITE_OK ){
  40767. rc = sqlite3PagerWrite(pToPage);
  40768. }
  40769. for(
  40770. iOff=(i-1)*nToPageSize;
  40771. rc==SQLITE_OK && iOff<i*nToPageSize;
  40772. iOff += nFromPageSize
  40773. ){
  40774. DbPage *pFromPage = 0;
  40775. Pgno iFrom = (Pgno)(iOff/nFromPageSize)+1;
  40776. if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
  40777. continue;
  40778. }
  40779. rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
  40780. if( rc==SQLITE_OK ){
  40781. char *zTo = sqlite3PagerGetData(pToPage);
  40782. char *zFrom = sqlite3PagerGetData(pFromPage);
  40783. int nCopy;
  40784. if( nFromPageSize>=nToPageSize ){
  40785. zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
  40786. nCopy = nToPageSize;
  40787. }else{
  40788. zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
  40789. nCopy = nFromPageSize;
  40790. }
  40791. memcpy(zTo, zFrom, nCopy);
  40792. sqlite3PagerUnref(pFromPage);
  40793. }
  40794. }
  40795. if( pToPage ){
  40796. MemPage *p = (MemPage *)sqlite3PagerGetExtra(pToPage);
  40797. p->isInit = 0;
  40798. sqlite3PagerUnref(pToPage);
  40799. }
  40800. }
  40801. }
  40802. /* If things have worked so far, the database file may need to be
  40803. ** truncated. The complex part is that it may need to be truncated to
  40804. ** a size that is not an integer multiple of nToPageSize - the current
  40805. ** page size used by the pager associated with B-Tree pTo.
  40806. **
  40807. ** For example, say the page-size of pTo is 2048 bytes and the original
  40808. ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024
  40809. ** bytes and 9 pages, then the file needs to be truncated to 9KB.
  40810. */
  40811. if( rc==SQLITE_OK ){
  40812. sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
  40813. i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
  40814. i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize;
  40815. i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
  40816. assert( iSize<=iNow );
  40817. /* Commit phase one syncs the journal file associated with pTo
  40818. ** containing the original data. It does not sync the database file
  40819. ** itself. After doing this it is safe to use OsTruncate() and other
  40820. ** file APIs on the database file directly.
  40821. */
  40822. pBtTo->db = pTo->db;
  40823. rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 1);
  40824. if( iSize<iNow && rc==SQLITE_OK ){
  40825. rc = sqlite3OsTruncate(pFile, iSize);
  40826. }
  40827. /* The loop that copied data from database pFrom to pTo did not
  40828. ** populate the locking page of database pTo. If the page-size of
  40829. ** pFrom is smaller than that of pTo, this means some data will
  40830. ** not have been copied.
  40831. **
  40832. ** This block copies the missing data from database pFrom to pTo
  40833. ** using file APIs. This is safe because at this point we know that
  40834. ** all of the original data from pTo has been synced into the
  40835. ** journal file. At this point it would be safe to do anything at
  40836. ** all to the database file except truncate it to zero bytes.
  40837. */
  40838. if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
  40839. i64 iOff;
  40840. for(
  40841. iOff=iPending;
  40842. rc==SQLITE_OK && iOff<(iPending+nToPageSize);
  40843. iOff += nFromPageSize
  40844. ){
  40845. DbPage *pFromPage = 0;
  40846. Pgno iFrom = (Pgno)(iOff/nFromPageSize)+1;
  40847. if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
  40848. continue;
  40849. }
  40850. rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
  40851. if( rc==SQLITE_OK ){
  40852. char *zFrom = sqlite3PagerGetData(pFromPage);
  40853. rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
  40854. sqlite3PagerUnref(pFromPage);
  40855. }
  40856. }
  40857. }
  40858. }
  40859. /* Sync the database file */
  40860. if( rc==SQLITE_OK ){
  40861. rc = sqlite3PagerSync(pBtTo->pPager);
  40862. }
  40863. if( rc==SQLITE_OK ){
  40864. pBtTo->pageSizeFixed = 0;
  40865. }else{
  40866. sqlite3BtreeRollback(pTo);
  40867. }
  40868. return rc;
  40869. }
  40870. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  40871. int rc;
  40872. sqlite3BtreeEnter(pTo);
  40873. sqlite3BtreeEnter(pFrom);
  40874. rc = btreeCopyFile(pTo, pFrom);
  40875. sqlite3BtreeLeave(pFrom);
  40876. sqlite3BtreeLeave(pTo);
  40877. return rc;
  40878. }
  40879. #endif /* SQLITE_OMIT_VACUUM */
  40880. /*
  40881. ** Return non-zero if a transaction is active.
  40882. */
  40883. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  40884. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  40885. return (p && (p->inTrans==TRANS_WRITE));
  40886. }
  40887. /*
  40888. ** Return non-zero if a statement transaction is active.
  40889. */
  40890. SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree *p){
  40891. assert( sqlite3BtreeHoldsMutex(p) );
  40892. return ALWAYS(p->pBt) && p->pBt->inStmt;
  40893. }
  40894. /*
  40895. ** Return non-zero if a read (or write) transaction is active.
  40896. */
  40897. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  40898. assert( p );
  40899. assert( sqlite3_mutex_held(p->db->mutex) );
  40900. return p->inTrans!=TRANS_NONE;
  40901. }
  40902. /*
  40903. ** This function returns a pointer to a blob of memory associated with
  40904. ** a single shared-btree. The memory is used by client code for its own
  40905. ** purposes (for example, to store a high-level schema associated with
  40906. ** the shared-btree). The btree layer manages reference counting issues.
  40907. **
  40908. ** The first time this is called on a shared-btree, nBytes bytes of memory
  40909. ** are allocated, zeroed, and returned to the caller. For each subsequent
  40910. ** call the nBytes parameter is ignored and a pointer to the same blob
  40911. ** of memory returned.
  40912. **
  40913. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  40914. ** allocated, a null pointer is returned. If the blob has already been
  40915. ** allocated, it is returned as normal.
  40916. **
  40917. ** Just before the shared-btree is closed, the function passed as the
  40918. ** xFree argument when the memory allocation was made is invoked on the
  40919. ** blob of allocated memory. This function should not call sqlite3_free()
  40920. ** on the memory, the btree layer does that.
  40921. */
  40922. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  40923. BtShared *pBt = p->pBt;
  40924. sqlite3BtreeEnter(p);
  40925. if( !pBt->pSchema && nBytes ){
  40926. pBt->pSchema = sqlite3MallocZero(nBytes);
  40927. pBt->xFreeSchema = xFree;
  40928. }
  40929. sqlite3BtreeLeave(p);
  40930. return pBt->pSchema;
  40931. }
  40932. /*
  40933. ** Return true if another user of the same shared btree as the argument
  40934. ** handle holds an exclusive lock on the sqlite_master table.
  40935. */
  40936. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  40937. int rc;
  40938. assert( sqlite3_mutex_held(p->db->mutex) );
  40939. sqlite3BtreeEnter(p);
  40940. rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
  40941. sqlite3BtreeLeave(p);
  40942. return rc;
  40943. }
  40944. #ifndef SQLITE_OMIT_SHARED_CACHE
  40945. /*
  40946. ** Obtain a lock on the table whose root page is iTab. The
  40947. ** lock is a write lock if isWritelock is true or a read lock
  40948. ** if it is false.
  40949. */
  40950. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  40951. int rc = SQLITE_OK;
  40952. if( p->sharable ){
  40953. u8 lockType = READ_LOCK + isWriteLock;
  40954. assert( READ_LOCK+1==WRITE_LOCK );
  40955. assert( isWriteLock==0 || isWriteLock==1 );
  40956. sqlite3BtreeEnter(p);
  40957. rc = queryTableLock(p, iTab, lockType);
  40958. if( rc==SQLITE_OK ){
  40959. rc = lockTable(p, iTab, lockType);
  40960. }
  40961. sqlite3BtreeLeave(p);
  40962. }
  40963. return rc;
  40964. }
  40965. #endif
  40966. #ifndef SQLITE_OMIT_INCRBLOB
  40967. /*
  40968. ** Argument pCsr must be a cursor opened for writing on an
  40969. ** INTKEY table currently pointing at a valid table entry.
  40970. ** This function modifies the data stored as part of that entry.
  40971. ** Only the data content may only be modified, it is not possible
  40972. ** to change the length of the data stored.
  40973. */
  40974. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  40975. assert( cursorHoldsMutex(pCsr) );
  40976. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  40977. assert(pCsr->isIncrblobHandle);
  40978. restoreCursorPosition(pCsr);
  40979. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  40980. if( pCsr->eState!=CURSOR_VALID ){
  40981. return SQLITE_ABORT;
  40982. }
  40983. /* Check some preconditions:
  40984. ** (a) the cursor is open for writing,
  40985. ** (b) there is no read-lock on the table being modified and
  40986. ** (c) the cursor points at a valid row of an intKey table.
  40987. */
  40988. if( !pCsr->wrFlag ){
  40989. return SQLITE_READONLY;
  40990. }
  40991. assert( !pCsr->pBt->readOnly
  40992. && pCsr->pBt->inTransaction==TRANS_WRITE );
  40993. if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
  40994. return SQLITE_LOCKED; /* The table pCur points to has a read lock */
  40995. }
  40996. if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
  40997. return SQLITE_ERROR;
  40998. }
  40999. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
  41000. }
  41001. /*
  41002. ** Set a flag on this cursor to cache the locations of pages from the
  41003. ** overflow list for the current row. This is used by cursors opened
  41004. ** for incremental blob IO only.
  41005. **
  41006. ** This function sets a flag only. The actual page location cache
  41007. ** (stored in BtCursor.aOverflow[]) is allocated and used by function
  41008. ** accessPayload() (the worker function for sqlite3BtreeData() and
  41009. ** sqlite3BtreePutData()).
  41010. */
  41011. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  41012. assert( cursorHoldsMutex(pCur) );
  41013. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41014. assert(!pCur->isIncrblobHandle);
  41015. assert(!pCur->aOverflow);
  41016. pCur->isIncrblobHandle = 1;
  41017. }
  41018. #endif
  41019. /************** End of btree.c ***********************************************/
  41020. /************** Begin file vdbemem.c *****************************************/
  41021. /*
  41022. ** 2004 May 26
  41023. **
  41024. ** The author disclaims copyright to this source code. In place of
  41025. ** a legal notice, here is a blessing:
  41026. **
  41027. ** May you do good and not evil.
  41028. ** May you find forgiveness for yourself and forgive others.
  41029. ** May you share freely, never taking more than you give.
  41030. **
  41031. *************************************************************************
  41032. **
  41033. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  41034. ** stores a single value in the VDBE. Mem is an opaque structure visible
  41035. ** only within the VDBE. Interface routines refer to a Mem using the
  41036. ** name sqlite_value
  41037. **
  41038. ** $Id: vdbemem.c,v 1.134 2009/01/05 22:30:39 drh Exp $
  41039. */
  41040. /*
  41041. ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
  41042. ** P if required.
  41043. */
  41044. #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  41045. /*
  41046. ** If pMem is an object with a valid string representation, this routine
  41047. ** ensures the internal encoding for the string representation is
  41048. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  41049. **
  41050. ** If pMem is not a string object, or the encoding of the string
  41051. ** representation is already stored using the requested encoding, then this
  41052. ** routine is a no-op.
  41053. **
  41054. ** SQLITE_OK is returned if the conversion is successful (or not required).
  41055. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  41056. ** between formats.
  41057. */
  41058. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  41059. int rc;
  41060. assert( (pMem->flags&MEM_RowSet)==0 );
  41061. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  41062. || desiredEnc==SQLITE_UTF16BE );
  41063. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  41064. return SQLITE_OK;
  41065. }
  41066. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41067. #ifdef SQLITE_OMIT_UTF16
  41068. return SQLITE_ERROR;
  41069. #else
  41070. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  41071. ** then the encoding of the value may not have changed.
  41072. */
  41073. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  41074. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  41075. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  41076. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  41077. return rc;
  41078. #endif
  41079. }
  41080. /*
  41081. ** Make sure pMem->z points to a writable allocation of at least
  41082. ** n bytes.
  41083. **
  41084. ** If the memory cell currently contains string or blob data
  41085. ** and the third argument passed to this function is true, the
  41086. ** current content of the cell is preserved. Otherwise, it may
  41087. ** be discarded.
  41088. **
  41089. ** This function sets the MEM_Dyn flag and clears any xDel callback.
  41090. ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
  41091. ** not set, Mem.n is zeroed.
  41092. */
  41093. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  41094. assert( 1 >=
  41095. ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
  41096. (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
  41097. ((pMem->flags&MEM_Ephem) ? 1 : 0) +
  41098. ((pMem->flags&MEM_Static) ? 1 : 0)
  41099. );
  41100. assert( (pMem->flags&MEM_RowSet)==0 );
  41101. if( n<32 ) n = 32;
  41102. if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
  41103. if( preserve && pMem->z==pMem->zMalloc ){
  41104. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  41105. preserve = 0;
  41106. }else{
  41107. sqlite3DbFree(pMem->db, pMem->zMalloc);
  41108. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  41109. }
  41110. }
  41111. if( preserve && pMem->z && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
  41112. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  41113. }
  41114. if( pMem->flags&MEM_Dyn && pMem->xDel ){
  41115. pMem->xDel((void *)(pMem->z));
  41116. }
  41117. pMem->z = pMem->zMalloc;
  41118. if( pMem->z==0 ){
  41119. pMem->flags = MEM_Null;
  41120. }else{
  41121. pMem->flags &= ~(MEM_Ephem|MEM_Static);
  41122. }
  41123. pMem->xDel = 0;
  41124. return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
  41125. }
  41126. /*
  41127. ** Make the given Mem object MEM_Dyn. In other words, make it so
  41128. ** that any TEXT or BLOB content is stored in memory obtained from
  41129. ** malloc(). In this way, we know that the memory is safe to be
  41130. ** overwritten or altered.
  41131. **
  41132. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  41133. */
  41134. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  41135. int f;
  41136. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41137. assert( (pMem->flags&MEM_RowSet)==0 );
  41138. expandBlob(pMem);
  41139. f = pMem->flags;
  41140. if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
  41141. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  41142. return SQLITE_NOMEM;
  41143. }
  41144. pMem->z[pMem->n] = 0;
  41145. pMem->z[pMem->n+1] = 0;
  41146. pMem->flags |= MEM_Term;
  41147. }
  41148. return SQLITE_OK;
  41149. }
  41150. /*
  41151. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  41152. ** blob stored in dynamically allocated space.
  41153. */
  41154. #ifndef SQLITE_OMIT_INCRBLOB
  41155. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  41156. if( pMem->flags & MEM_Zero ){
  41157. int nByte;
  41158. assert( pMem->flags&MEM_Blob );
  41159. assert( (pMem->flags&MEM_RowSet)==0 );
  41160. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41161. /* Set nByte to the number of bytes required to store the expanded blob. */
  41162. nByte = pMem->n + pMem->u.nZero;
  41163. if( nByte<=0 ){
  41164. nByte = 1;
  41165. }
  41166. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  41167. return SQLITE_NOMEM;
  41168. }
  41169. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  41170. pMem->n += pMem->u.nZero;
  41171. pMem->flags &= ~(MEM_Zero|MEM_Term);
  41172. }
  41173. return SQLITE_OK;
  41174. }
  41175. #endif
  41176. /*
  41177. ** Make sure the given Mem is \u0000 terminated.
  41178. */
  41179. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  41180. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41181. if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
  41182. return SQLITE_OK; /* Nothing to do */
  41183. }
  41184. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  41185. return SQLITE_NOMEM;
  41186. }
  41187. pMem->z[pMem->n] = 0;
  41188. pMem->z[pMem->n+1] = 0;
  41189. pMem->flags |= MEM_Term;
  41190. return SQLITE_OK;
  41191. }
  41192. /*
  41193. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  41194. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  41195. ** is a no-op.
  41196. **
  41197. ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
  41198. **
  41199. ** A MEM_Null value will never be passed to this function. This function is
  41200. ** used for converting values to text for returning to the user (i.e. via
  41201. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  41202. ** keys are strings. In the former case a NULL pointer is returned the
  41203. ** user and the later is an internal programming error.
  41204. */
  41205. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  41206. int rc = SQLITE_OK;
  41207. int fg = pMem->flags;
  41208. const int nByte = 32;
  41209. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41210. assert( !(fg&MEM_Zero) );
  41211. assert( !(fg&(MEM_Str|MEM_Blob)) );
  41212. assert( fg&(MEM_Int|MEM_Real) );
  41213. assert( (pMem->flags&MEM_RowSet)==0 );
  41214. if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  41215. return SQLITE_NOMEM;
  41216. }
  41217. /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  41218. ** string representation of the value. Then, if the required encoding
  41219. ** is UTF-16le or UTF-16be do a translation.
  41220. **
  41221. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  41222. */
  41223. if( fg & MEM_Int ){
  41224. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  41225. }else{
  41226. assert( fg & MEM_Real );
  41227. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  41228. }
  41229. pMem->n = sqlite3Strlen30(pMem->z);
  41230. pMem->enc = SQLITE_UTF8;
  41231. pMem->flags |= MEM_Str|MEM_Term;
  41232. sqlite3VdbeChangeEncoding(pMem, enc);
  41233. return rc;
  41234. }
  41235. /*
  41236. ** Memory cell pMem contains the context of an aggregate function.
  41237. ** This routine calls the finalize method for that function. The
  41238. ** result of the aggregate is stored back into pMem.
  41239. **
  41240. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  41241. ** otherwise.
  41242. */
  41243. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  41244. int rc = SQLITE_OK;
  41245. if( pFunc && pFunc->xFinalize ){
  41246. sqlite3_context ctx;
  41247. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  41248. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41249. memset(&ctx, 0, sizeof(ctx));
  41250. ctx.s.flags = MEM_Null;
  41251. ctx.s.db = pMem->db;
  41252. ctx.pMem = pMem;
  41253. ctx.pFunc = pFunc;
  41254. pFunc->xFinalize(&ctx);
  41255. assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
  41256. sqlite3DbFree(pMem->db, pMem->zMalloc);
  41257. memcpy(pMem, &ctx.s, sizeof(ctx.s));
  41258. rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
  41259. }
  41260. return rc;
  41261. }
  41262. /*
  41263. ** If the memory cell contains a string value that must be freed by
  41264. ** invoking an external callback, free it now. Calling this function
  41265. ** does not free any Mem.zMalloc buffer.
  41266. */
  41267. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
  41268. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  41269. if( p->flags&MEM_Agg ){
  41270. sqlite3VdbeMemFinalize(p, p->u.pDef);
  41271. assert( (p->flags & MEM_Agg)==0 );
  41272. sqlite3VdbeMemRelease(p);
  41273. }else if( p->flags&MEM_Dyn && p->xDel ){
  41274. assert( (p->flags&MEM_RowSet)==0 );
  41275. p->xDel((void *)p->z);
  41276. p->xDel = 0;
  41277. }else if( p->flags&MEM_RowSet ){
  41278. sqlite3RowSetClear(p->u.pRowSet);
  41279. }
  41280. }
  41281. /*
  41282. ** Release any memory held by the Mem. This may leave the Mem in an
  41283. ** inconsistent state, for example with (Mem.z==0) and
  41284. ** (Mem.type==SQLITE_TEXT).
  41285. */
  41286. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  41287. sqlite3VdbeMemReleaseExternal(p);
  41288. sqlite3DbFree(p->db, p->zMalloc);
  41289. p->z = 0;
  41290. p->zMalloc = 0;
  41291. p->xDel = 0;
  41292. }
  41293. /*
  41294. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  41295. ** If the double is too large, return 0x8000000000000000.
  41296. **
  41297. ** Most systems appear to do this simply by assigning
  41298. ** variables and without the extra range tests. But
  41299. ** there are reports that windows throws an expection
  41300. ** if the floating point value is out of range. (See ticket #2880.)
  41301. ** Because we do not completely understand the problem, we will
  41302. ** take the conservative approach and always do range tests
  41303. ** before attempting the conversion.
  41304. */
  41305. static i64 doubleToInt64(double r){
  41306. /*
  41307. ** Many compilers we encounter do not define constants for the
  41308. ** minimum and maximum 64-bit integers, or they define them
  41309. ** inconsistently. And many do not understand the "LL" notation.
  41310. ** So we define our own static constants here using nothing
  41311. ** larger than a 32-bit integer constant.
  41312. */
  41313. static const i64 maxInt = LARGEST_INT64;
  41314. static const i64 minInt = SMALLEST_INT64;
  41315. if( r<(double)minInt ){
  41316. return minInt;
  41317. }else if( r>(double)maxInt ){
  41318. return minInt;
  41319. }else{
  41320. return (i64)r;
  41321. }
  41322. }
  41323. /*
  41324. ** Return some kind of integer value which is the best we can do
  41325. ** at representing the value that *pMem describes as an integer.
  41326. ** If pMem is an integer, then the value is exact. If pMem is
  41327. ** a floating-point then the value returned is the integer part.
  41328. ** If pMem is a string or blob, then we make an attempt to convert
  41329. ** it into a integer and return that. If pMem is NULL, return 0.
  41330. **
  41331. ** If pMem is a string, its encoding might be changed.
  41332. */
  41333. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  41334. int flags;
  41335. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41336. flags = pMem->flags;
  41337. if( flags & MEM_Int ){
  41338. return pMem->u.i;
  41339. }else if( flags & MEM_Real ){
  41340. return doubleToInt64(pMem->r);
  41341. }else if( flags & (MEM_Str|MEM_Blob) ){
  41342. i64 value;
  41343. pMem->flags |= MEM_Str;
  41344. if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
  41345. || sqlite3VdbeMemNulTerminate(pMem) ){
  41346. return 0;
  41347. }
  41348. assert( pMem->z );
  41349. sqlite3Atoi64(pMem->z, &value);
  41350. return value;
  41351. }else{
  41352. return 0;
  41353. }
  41354. }
  41355. /*
  41356. ** Return the best representation of pMem that we can get into a
  41357. ** double. If pMem is already a double or an integer, return its
  41358. ** value. If it is a string or blob, try to convert it to a double.
  41359. ** If it is a NULL, return 0.0.
  41360. */
  41361. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  41362. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41363. if( pMem->flags & MEM_Real ){
  41364. return pMem->r;
  41365. }else if( pMem->flags & MEM_Int ){
  41366. return (double)pMem->u.i;
  41367. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  41368. double val = 0.0;
  41369. pMem->flags |= MEM_Str;
  41370. if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
  41371. || sqlite3VdbeMemNulTerminate(pMem) ){
  41372. return 0.0;
  41373. }
  41374. assert( pMem->z );
  41375. sqlite3AtoF(pMem->z, &val);
  41376. return val;
  41377. }else{
  41378. return 0.0;
  41379. }
  41380. }
  41381. /*
  41382. ** The MEM structure is already a MEM_Real. Try to also make it a
  41383. ** MEM_Int if we can.
  41384. */
  41385. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  41386. assert( pMem->flags & MEM_Real );
  41387. assert( (pMem->flags & MEM_RowSet)==0 );
  41388. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41389. pMem->u.i = doubleToInt64(pMem->r);
  41390. if( pMem->r==(double)pMem->u.i ){
  41391. pMem->flags |= MEM_Int;
  41392. }
  41393. }
  41394. /*
  41395. ** Convert pMem to type integer. Invalidate any prior representations.
  41396. */
  41397. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  41398. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41399. assert( (pMem->flags & MEM_RowSet)==0 );
  41400. pMem->u.i = sqlite3VdbeIntValue(pMem);
  41401. MemSetTypeFlag(pMem, MEM_Int);
  41402. return SQLITE_OK;
  41403. }
  41404. /*
  41405. ** Convert pMem so that it is of type MEM_Real.
  41406. ** Invalidate any prior representations.
  41407. */
  41408. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  41409. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41410. pMem->r = sqlite3VdbeRealValue(pMem);
  41411. MemSetTypeFlag(pMem, MEM_Real);
  41412. return SQLITE_OK;
  41413. }
  41414. /*
  41415. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  41416. ** Invalidate any prior representations.
  41417. */
  41418. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  41419. double r1, r2;
  41420. i64 i;
  41421. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
  41422. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  41423. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41424. r1 = sqlite3VdbeRealValue(pMem);
  41425. i = doubleToInt64(r1);
  41426. r2 = (double)i;
  41427. if( r1==r2 ){
  41428. sqlite3VdbeMemIntegerify(pMem);
  41429. }else{
  41430. pMem->r = r1;
  41431. MemSetTypeFlag(pMem, MEM_Real);
  41432. }
  41433. return SQLITE_OK;
  41434. }
  41435. /*
  41436. ** Delete any previous value and set the value stored in *pMem to NULL.
  41437. */
  41438. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  41439. if( pMem->flags & MEM_RowSet ){
  41440. sqlite3RowSetClear(pMem->u.pRowSet);
  41441. }
  41442. MemSetTypeFlag(pMem, MEM_Null);
  41443. pMem->type = SQLITE_NULL;
  41444. }
  41445. /*
  41446. ** Delete any previous value and set the value to be a BLOB of length
  41447. ** n containing all zeros.
  41448. */
  41449. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  41450. sqlite3VdbeMemRelease(pMem);
  41451. pMem->flags = MEM_Blob|MEM_Zero;
  41452. pMem->type = SQLITE_BLOB;
  41453. pMem->n = 0;
  41454. if( n<0 ) n = 0;
  41455. pMem->u.nZero = n;
  41456. pMem->enc = SQLITE_UTF8;
  41457. }
  41458. /*
  41459. ** Delete any previous value and set the value stored in *pMem to val,
  41460. ** manifest type INTEGER.
  41461. */
  41462. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  41463. sqlite3VdbeMemRelease(pMem);
  41464. pMem->u.i = val;
  41465. pMem->flags = MEM_Int;
  41466. pMem->type = SQLITE_INTEGER;
  41467. }
  41468. /*
  41469. ** Delete any previous value and set the value stored in *pMem to val,
  41470. ** manifest type REAL.
  41471. */
  41472. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  41473. if( sqlite3IsNaN(val) ){
  41474. sqlite3VdbeMemSetNull(pMem);
  41475. }else{
  41476. sqlite3VdbeMemRelease(pMem);
  41477. pMem->r = val;
  41478. pMem->flags = MEM_Real;
  41479. pMem->type = SQLITE_FLOAT;
  41480. }
  41481. }
  41482. /*
  41483. ** Delete any previous value and set the value of pMem to be an
  41484. ** empty boolean index.
  41485. */
  41486. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  41487. sqlite3 *db = pMem->db;
  41488. assert( db!=0 );
  41489. if( pMem->flags & MEM_RowSet ){
  41490. sqlite3RowSetClear(pMem->u.pRowSet);
  41491. }else{
  41492. sqlite3VdbeMemRelease(pMem);
  41493. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  41494. }
  41495. if( db->mallocFailed ){
  41496. pMem->flags = MEM_Null;
  41497. }else{
  41498. assert( pMem->zMalloc );
  41499. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
  41500. sqlite3DbMallocSize(db, pMem->zMalloc));
  41501. assert( pMem->u.pRowSet!=0 );
  41502. pMem->flags = MEM_RowSet;
  41503. }
  41504. }
  41505. /*
  41506. ** Return true if the Mem object contains a TEXT or BLOB that is
  41507. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  41508. */
  41509. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  41510. assert( p->db!=0 );
  41511. if( p->flags & (MEM_Str|MEM_Blob) ){
  41512. int n = p->n;
  41513. if( p->flags & MEM_Zero ){
  41514. n += p->u.nZero;
  41515. }
  41516. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  41517. }
  41518. return 0;
  41519. }
  41520. /*
  41521. ** Size of struct Mem not including the Mem.zMalloc member.
  41522. */
  41523. #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
  41524. /*
  41525. ** Make an shallow copy of pFrom into pTo. Prior contents of
  41526. ** pTo are freed. The pFrom->z field is not duplicated. If
  41527. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  41528. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  41529. */
  41530. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  41531. assert( (pFrom->flags & MEM_RowSet)==0 );
  41532. sqlite3VdbeMemReleaseExternal(pTo);
  41533. memcpy(pTo, pFrom, MEMCELLSIZE);
  41534. pTo->xDel = 0;
  41535. if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
  41536. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  41537. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  41538. pTo->flags |= srcType;
  41539. }
  41540. }
  41541. /*
  41542. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  41543. ** freed before the copy is made.
  41544. */
  41545. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  41546. int rc = SQLITE_OK;
  41547. assert( (pFrom->flags & MEM_RowSet)==0 );
  41548. sqlite3VdbeMemReleaseExternal(pTo);
  41549. memcpy(pTo, pFrom, MEMCELLSIZE);
  41550. pTo->flags &= ~MEM_Dyn;
  41551. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  41552. if( 0==(pFrom->flags&MEM_Static) ){
  41553. pTo->flags |= MEM_Ephem;
  41554. rc = sqlite3VdbeMemMakeWriteable(pTo);
  41555. }
  41556. }
  41557. return rc;
  41558. }
  41559. /*
  41560. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  41561. ** freed. If pFrom contains ephemeral data, a copy is made.
  41562. **
  41563. ** pFrom contains an SQL NULL when this routine returns.
  41564. */
  41565. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  41566. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  41567. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  41568. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  41569. sqlite3VdbeMemRelease(pTo);
  41570. memcpy(pTo, pFrom, sizeof(Mem));
  41571. pFrom->flags = MEM_Null;
  41572. pFrom->xDel = 0;
  41573. pFrom->zMalloc = 0;
  41574. }
  41575. /*
  41576. ** Change the value of a Mem to be a string or a BLOB.
  41577. **
  41578. ** The memory management strategy depends on the value of the xDel
  41579. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  41580. ** string is copied into a (possibly existing) buffer managed by the
  41581. ** Mem structure. Otherwise, any existing buffer is freed and the
  41582. ** pointer copied.
  41583. */
  41584. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  41585. Mem *pMem, /* Memory cell to set to string value */
  41586. const char *z, /* String pointer */
  41587. int n, /* Bytes in string, or negative */
  41588. u8 enc, /* Encoding of z. 0 for BLOBs */
  41589. void (*xDel)(void*) /* Destructor function */
  41590. ){
  41591. int nByte = n; /* New value for pMem->n */
  41592. int iLimit; /* Maximum allowed string or blob size */
  41593. u16 flags = 0; /* New value for pMem->flags */
  41594. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41595. assert( (pMem->flags & MEM_RowSet)==0 );
  41596. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  41597. if( !z ){
  41598. sqlite3VdbeMemSetNull(pMem);
  41599. return SQLITE_OK;
  41600. }
  41601. if( pMem->db ){
  41602. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  41603. }else{
  41604. iLimit = SQLITE_MAX_LENGTH;
  41605. }
  41606. flags = (enc==0?MEM_Blob:MEM_Str);
  41607. if( nByte<0 ){
  41608. assert( enc!=0 );
  41609. if( enc==SQLITE_UTF8 ){
  41610. for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
  41611. }else{
  41612. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  41613. }
  41614. flags |= MEM_Term;
  41615. }
  41616. /* The following block sets the new values of Mem.z and Mem.xDel. It
  41617. ** also sets a flag in local variable "flags" to indicate the memory
  41618. ** management (one of MEM_Dyn or MEM_Static).
  41619. */
  41620. if( xDel==SQLITE_TRANSIENT ){
  41621. int nAlloc = nByte;
  41622. if( flags&MEM_Term ){
  41623. nAlloc += (enc==SQLITE_UTF8?1:2);
  41624. }
  41625. if( nByte>iLimit ){
  41626. return SQLITE_TOOBIG;
  41627. }
  41628. if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
  41629. return SQLITE_NOMEM;
  41630. }
  41631. memcpy(pMem->z, z, nAlloc);
  41632. }else if( xDel==SQLITE_DYNAMIC ){
  41633. sqlite3VdbeMemRelease(pMem);
  41634. pMem->zMalloc = pMem->z = (char *)z;
  41635. pMem->xDel = 0;
  41636. }else{
  41637. sqlite3VdbeMemRelease(pMem);
  41638. pMem->z = (char *)z;
  41639. pMem->xDel = xDel;
  41640. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  41641. }
  41642. if( nByte>iLimit ){
  41643. return SQLITE_TOOBIG;
  41644. }
  41645. pMem->n = nByte;
  41646. pMem->flags = flags;
  41647. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  41648. pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
  41649. #ifndef SQLITE_OMIT_UTF16
  41650. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  41651. return SQLITE_NOMEM;
  41652. }
  41653. #endif
  41654. return SQLITE_OK;
  41655. }
  41656. /*
  41657. ** Compare the values contained by the two memory cells, returning
  41658. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  41659. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  41660. ** and reals) sorted numerically, followed by text ordered by the collating
  41661. ** sequence pColl and finally blob's ordered by memcmp().
  41662. **
  41663. ** Two NULL values are considered equal by this function.
  41664. */
  41665. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  41666. int rc;
  41667. int f1, f2;
  41668. int combined_flags;
  41669. /* Interchange pMem1 and pMem2 if the collating sequence specifies
  41670. ** DESC order.
  41671. */
  41672. f1 = pMem1->flags;
  41673. f2 = pMem2->flags;
  41674. combined_flags = f1|f2;
  41675. assert( (combined_flags & MEM_RowSet)==0 );
  41676. /* If one value is NULL, it is less than the other. If both values
  41677. ** are NULL, return 0.
  41678. */
  41679. if( combined_flags&MEM_Null ){
  41680. return (f2&MEM_Null) - (f1&MEM_Null);
  41681. }
  41682. /* If one value is a number and the other is not, the number is less.
  41683. ** If both are numbers, compare as reals if one is a real, or as integers
  41684. ** if both values are integers.
  41685. */
  41686. if( combined_flags&(MEM_Int|MEM_Real) ){
  41687. if( !(f1&(MEM_Int|MEM_Real)) ){
  41688. return 1;
  41689. }
  41690. if( !(f2&(MEM_Int|MEM_Real)) ){
  41691. return -1;
  41692. }
  41693. if( (f1 & f2 & MEM_Int)==0 ){
  41694. double r1, r2;
  41695. if( (f1&MEM_Real)==0 ){
  41696. r1 = (double)pMem1->u.i;
  41697. }else{
  41698. r1 = pMem1->r;
  41699. }
  41700. if( (f2&MEM_Real)==0 ){
  41701. r2 = (double)pMem2->u.i;
  41702. }else{
  41703. r2 = pMem2->r;
  41704. }
  41705. if( r1<r2 ) return -1;
  41706. if( r1>r2 ) return 1;
  41707. return 0;
  41708. }else{
  41709. assert( f1&MEM_Int );
  41710. assert( f2&MEM_Int );
  41711. if( pMem1->u.i < pMem2->u.i ) return -1;
  41712. if( pMem1->u.i > pMem2->u.i ) return 1;
  41713. return 0;
  41714. }
  41715. }
  41716. /* If one value is a string and the other is a blob, the string is less.
  41717. ** If both are strings, compare using the collating functions.
  41718. */
  41719. if( combined_flags&MEM_Str ){
  41720. if( (f1 & MEM_Str)==0 ){
  41721. return 1;
  41722. }
  41723. if( (f2 & MEM_Str)==0 ){
  41724. return -1;
  41725. }
  41726. assert( pMem1->enc==pMem2->enc );
  41727. assert( pMem1->enc==SQLITE_UTF8 ||
  41728. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  41729. /* The collation sequence must be defined at this point, even if
  41730. ** the user deletes the collation sequence after the vdbe program is
  41731. ** compiled (this was not always the case).
  41732. */
  41733. assert( !pColl || pColl->xCmp );
  41734. if( pColl ){
  41735. if( pMem1->enc==pColl->enc ){
  41736. /* The strings are already in the correct encoding. Call the
  41737. ** comparison function directly */
  41738. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  41739. }else{
  41740. const void *v1, *v2;
  41741. int n1, n2;
  41742. Mem c1;
  41743. Mem c2;
  41744. memset(&c1, 0, sizeof(c1));
  41745. memset(&c2, 0, sizeof(c2));
  41746. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  41747. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  41748. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  41749. n1 = v1==0 ? 0 : c1.n;
  41750. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  41751. n2 = v2==0 ? 0 : c2.n;
  41752. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  41753. sqlite3VdbeMemRelease(&c1);
  41754. sqlite3VdbeMemRelease(&c2);
  41755. return rc;
  41756. }
  41757. }
  41758. /* If a NULL pointer was passed as the collate function, fall through
  41759. ** to the blob case and use memcmp(). */
  41760. }
  41761. /* Both values must be blobs. Compare using memcmp(). */
  41762. rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  41763. if( rc==0 ){
  41764. rc = pMem1->n - pMem2->n;
  41765. }
  41766. return rc;
  41767. }
  41768. /*
  41769. ** Move data out of a btree key or data field and into a Mem structure.
  41770. ** The data or key is taken from the entry that pCur is currently pointing
  41771. ** to. offset and amt determine what portion of the data or key to retrieve.
  41772. ** key is true to get the key or false to get data. The result is written
  41773. ** into the pMem element.
  41774. **
  41775. ** The pMem structure is assumed to be uninitialized. Any prior content
  41776. ** is overwritten without being freed.
  41777. **
  41778. ** If this routine fails for any reason (malloc returns NULL or unable
  41779. ** to read from the disk) then the pMem is left in an inconsistent state.
  41780. */
  41781. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  41782. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  41783. int offset, /* Offset from the start of data to return bytes from. */
  41784. int amt, /* Number of bytes to return. */
  41785. int key, /* If true, retrieve from the btree key, not data. */
  41786. Mem *pMem /* OUT: Return data in this Mem structure. */
  41787. ){
  41788. char *zData; /* Data from the btree layer */
  41789. int available = 0; /* Number of bytes available on the local btree page */
  41790. sqlite3 *db; /* Database connection */
  41791. int rc = SQLITE_OK;
  41792. db = sqlite3BtreeCursorDb(pCur);
  41793. assert( sqlite3_mutex_held(db->mutex) );
  41794. assert( (pMem->flags & MEM_RowSet)==0 );
  41795. if( key ){
  41796. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  41797. }else{
  41798. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  41799. }
  41800. assert( zData!=0 );
  41801. if( offset+amt<=available && ((pMem->flags&MEM_Dyn)==0 || pMem->xDel) ){
  41802. sqlite3VdbeMemRelease(pMem);
  41803. pMem->z = &zData[offset];
  41804. pMem->flags = MEM_Blob|MEM_Ephem;
  41805. }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
  41806. pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
  41807. pMem->enc = 0;
  41808. pMem->type = SQLITE_BLOB;
  41809. if( key ){
  41810. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  41811. }else{
  41812. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  41813. }
  41814. pMem->z[amt] = 0;
  41815. pMem->z[amt+1] = 0;
  41816. if( rc!=SQLITE_OK ){
  41817. sqlite3VdbeMemRelease(pMem);
  41818. }
  41819. }
  41820. pMem->n = amt;
  41821. return rc;
  41822. }
  41823. #if 0
  41824. /*
  41825. ** Perform various checks on the memory cell pMem. An assert() will
  41826. ** fail if pMem is internally inconsistent.
  41827. */
  41828. SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem *pMem){
  41829. int flags = pMem->flags;
  41830. assert( flags!=0 ); /* Must define some type */
  41831. if( flags & (MEM_Str|MEM_Blob) ){
  41832. int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
  41833. assert( x!=0 ); /* Strings must define a string subtype */
  41834. assert( (x & (x-1))==0 ); /* Only one string subtype can be defined */
  41835. assert( pMem->z!=0 ); /* Strings must have a value */
  41836. /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
  41837. assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
  41838. assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
  41839. /* No destructor unless there is MEM_Dyn */
  41840. assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
  41841. if( (flags & MEM_Str) ){
  41842. assert( pMem->enc==SQLITE_UTF8 ||
  41843. pMem->enc==SQLITE_UTF16BE ||
  41844. pMem->enc==SQLITE_UTF16LE
  41845. );
  41846. /* If the string is UTF-8 encoded and nul terminated, then pMem->n
  41847. ** must be the length of the string. (Later:) If the database file
  41848. ** has been corrupted, '\000' characters might have been inserted
  41849. ** into the middle of the string. In that case, the sqlite3Strlen30()
  41850. ** might be less.
  41851. */
  41852. if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){
  41853. assert( sqlite3Strlen30(pMem->z)<=pMem->n );
  41854. assert( pMem->z[pMem->n]==0 );
  41855. }
  41856. }
  41857. }else{
  41858. /* Cannot define a string subtype for non-string objects */
  41859. assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
  41860. assert( pMem->xDel==0 );
  41861. }
  41862. /* MEM_Null excludes all other types */
  41863. assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
  41864. || (pMem->flags&MEM_Null)==0 );
  41865. /* If the MEM is both real and integer, the values are equal */
  41866. assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real)
  41867. || pMem->r==pMem->u.i );
  41868. }
  41869. #endif
  41870. /* This function is only available internally, it is not part of the
  41871. ** external API. It works in a similar way to sqlite3_value_text(),
  41872. ** except the data returned is in the encoding specified by the second
  41873. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  41874. ** SQLITE_UTF8.
  41875. **
  41876. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  41877. ** If that is the case, then the result must be aligned on an even byte
  41878. ** boundary.
  41879. */
  41880. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  41881. if( !pVal ) return 0;
  41882. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  41883. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  41884. assert( (pVal->flags & MEM_RowSet)==0 );
  41885. if( pVal->flags&MEM_Null ){
  41886. return 0;
  41887. }
  41888. assert( (MEM_Blob>>3) == MEM_Str );
  41889. pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  41890. expandBlob(pVal);
  41891. if( pVal->flags&MEM_Str ){
  41892. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  41893. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  41894. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  41895. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  41896. return 0;
  41897. }
  41898. }
  41899. sqlite3VdbeMemNulTerminate(pVal);
  41900. }else{
  41901. assert( (pVal->flags&MEM_Blob)==0 );
  41902. sqlite3VdbeMemStringify(pVal, enc);
  41903. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  41904. }
  41905. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  41906. || pVal->db->mallocFailed );
  41907. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  41908. return pVal->z;
  41909. }else{
  41910. return 0;
  41911. }
  41912. }
  41913. /*
  41914. ** Create a new sqlite3_value object.
  41915. */
  41916. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  41917. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  41918. if( p ){
  41919. p->flags = MEM_Null;
  41920. p->type = SQLITE_NULL;
  41921. p->db = db;
  41922. }
  41923. return p;
  41924. }
  41925. /*
  41926. ** Create a new sqlite3_value object, containing the value of pExpr.
  41927. **
  41928. ** This only works for very simple expressions that consist of one constant
  41929. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  41930. ** be converted directly into a value, then the value is allocated and
  41931. ** a pointer written to *ppVal. The caller is responsible for deallocating
  41932. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  41933. ** cannot be converted to a value, then *ppVal is set to NULL.
  41934. */
  41935. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  41936. sqlite3 *db, /* The database connection */
  41937. Expr *pExpr, /* The expression to evaluate */
  41938. u8 enc, /* Encoding to use */
  41939. u8 affinity, /* Affinity to use */
  41940. sqlite3_value **ppVal /* Write the new value here */
  41941. ){
  41942. int op;
  41943. char *zVal = 0;
  41944. sqlite3_value *pVal = 0;
  41945. if( !pExpr ){
  41946. *ppVal = 0;
  41947. return SQLITE_OK;
  41948. }
  41949. op = pExpr->op;
  41950. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  41951. zVal = sqlite3DbStrNDup(db, (char*)pExpr->token.z, pExpr->token.n);
  41952. pVal = sqlite3ValueNew(db);
  41953. if( !zVal || !pVal ) goto no_mem;
  41954. sqlite3Dequote(zVal);
  41955. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  41956. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  41957. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
  41958. }else{
  41959. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  41960. }
  41961. }else if( op==TK_UMINUS ) {
  41962. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
  41963. pVal->u.i = -1 * pVal->u.i;
  41964. pVal->r = -1.0 * pVal->r;
  41965. }
  41966. }
  41967. #ifndef SQLITE_OMIT_BLOB_LITERAL
  41968. else if( op==TK_BLOB ){
  41969. int nVal;
  41970. assert( pExpr->token.n>=3 );
  41971. assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
  41972. assert( pExpr->token.z[1]=='\'' );
  41973. assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
  41974. pVal = sqlite3ValueNew(db);
  41975. if( !pVal ) goto no_mem;
  41976. nVal = pExpr->token.n - 3;
  41977. zVal = (char*)pExpr->token.z + 2;
  41978. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  41979. 0, SQLITE_DYNAMIC);
  41980. }
  41981. #endif
  41982. *ppVal = pVal;
  41983. return SQLITE_OK;
  41984. no_mem:
  41985. db->mallocFailed = 1;
  41986. sqlite3DbFree(db, zVal);
  41987. sqlite3ValueFree(pVal);
  41988. *ppVal = 0;
  41989. return SQLITE_NOMEM;
  41990. }
  41991. /*
  41992. ** Change the string value of an sqlite3_value object
  41993. */
  41994. SQLITE_PRIVATE void sqlite3ValueSetStr(
  41995. sqlite3_value *v, /* Value to be set */
  41996. int n, /* Length of string z */
  41997. const void *z, /* Text of the new string */
  41998. u8 enc, /* Encoding to use */
  41999. void (*xDel)(void*) /* Destructor for the string */
  42000. ){
  42001. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  42002. }
  42003. /*
  42004. ** Free an sqlite3_value object
  42005. */
  42006. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  42007. if( !v ) return;
  42008. sqlite3VdbeMemRelease((Mem *)v);
  42009. sqlite3DbFree(((Mem*)v)->db, v);
  42010. }
  42011. /*
  42012. ** Return the number of bytes in the sqlite3_value object assuming
  42013. ** that it uses the encoding "enc"
  42014. */
  42015. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  42016. Mem *p = (Mem*)pVal;
  42017. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  42018. if( p->flags & MEM_Zero ){
  42019. return p->n + p->u.nZero;
  42020. }else{
  42021. return p->n;
  42022. }
  42023. }
  42024. return 0;
  42025. }
  42026. /************** End of vdbemem.c *********************************************/
  42027. /************** Begin file vdbeaux.c *****************************************/
  42028. /*
  42029. ** 2003 September 6
  42030. **
  42031. ** The author disclaims copyright to this source code. In place of
  42032. ** a legal notice, here is a blessing:
  42033. **
  42034. ** May you do good and not evil.
  42035. ** May you find forgiveness for yourself and forgive others.
  42036. ** May you share freely, never taking more than you give.
  42037. **
  42038. *************************************************************************
  42039. ** This file contains code used for creating, destroying, and populating
  42040. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
  42041. ** to version 2.8.7, all this code was combined into the vdbe.c source file.
  42042. ** But that file was getting too big so this subroutines were split out.
  42043. **
  42044. ** $Id: vdbeaux.c,v 1.430 2009/01/07 08:12:16 danielk1977 Exp $
  42045. */
  42046. /*
  42047. ** When debugging the code generator in a symbolic debugger, one can
  42048. ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
  42049. ** as they are added to the instruction stream.
  42050. */
  42051. #ifdef SQLITE_DEBUG
  42052. SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
  42053. #endif
  42054. /*
  42055. ** Create a new virtual database engine.
  42056. */
  42057. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  42058. Vdbe *p;
  42059. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  42060. if( p==0 ) return 0;
  42061. p->db = db;
  42062. if( db->pVdbe ){
  42063. db->pVdbe->pPrev = p;
  42064. }
  42065. p->pNext = db->pVdbe;
  42066. p->pPrev = 0;
  42067. db->pVdbe = p;
  42068. p->magic = VDBE_MAGIC_INIT;
  42069. return p;
  42070. }
  42071. /*
  42072. ** Remember the SQL string for a prepared statement.
  42073. */
  42074. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
  42075. if( p==0 ) return;
  42076. assert( p->zSql==0 );
  42077. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  42078. }
  42079. /*
  42080. ** Return the SQL associated with a prepared statement
  42081. */
  42082. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  42083. return ((Vdbe *)pStmt)->zSql;
  42084. }
  42085. /*
  42086. ** Swap all content between two VDBE structures.
  42087. */
  42088. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  42089. Vdbe tmp, *pTmp;
  42090. char *zTmp;
  42091. int nTmp;
  42092. tmp = *pA;
  42093. *pA = *pB;
  42094. *pB = tmp;
  42095. pTmp = pA->pNext;
  42096. pA->pNext = pB->pNext;
  42097. pB->pNext = pTmp;
  42098. pTmp = pA->pPrev;
  42099. pA->pPrev = pB->pPrev;
  42100. pB->pPrev = pTmp;
  42101. zTmp = pA->zSql;
  42102. pA->zSql = pB->zSql;
  42103. pB->zSql = zTmp;
  42104. nTmp = pA->nSql;
  42105. pA->nSql = pB->nSql;
  42106. pB->nSql = nTmp;
  42107. }
  42108. #ifdef SQLITE_DEBUG
  42109. /*
  42110. ** Turn tracing on or off
  42111. */
  42112. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  42113. p->trace = trace;
  42114. }
  42115. #endif
  42116. /*
  42117. ** Resize the Vdbe.aOp array so that it is at least one op larger than
  42118. ** it was.
  42119. **
  42120. ** If an out-of-memory error occurs while resizing the array, return
  42121. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  42122. ** unchanged (this is so that any opcodes already allocated can be
  42123. ** correctly deallocated along with the rest of the Vdbe).
  42124. */
  42125. static int growOpArray(Vdbe *p){
  42126. VdbeOp *pNew;
  42127. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  42128. pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  42129. if( pNew ){
  42130. p->nOpAlloc = nNew;
  42131. p->aOp = pNew;
  42132. }
  42133. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  42134. }
  42135. /*
  42136. ** Add a new instruction to the list of instructions current in the
  42137. ** VDBE. Return the address of the new instruction.
  42138. **
  42139. ** Parameters:
  42140. **
  42141. ** p Pointer to the VDBE
  42142. **
  42143. ** op The opcode for this instruction
  42144. **
  42145. ** p1, p2, p3 Operands
  42146. **
  42147. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  42148. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  42149. ** operand.
  42150. */
  42151. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  42152. int i;
  42153. VdbeOp *pOp;
  42154. i = p->nOp;
  42155. assert( p->magic==VDBE_MAGIC_INIT );
  42156. assert( op>0 && op<0xff );
  42157. if( p->nOpAlloc<=i ){
  42158. if( growOpArray(p) ){
  42159. return 0;
  42160. }
  42161. }
  42162. p->nOp++;
  42163. pOp = &p->aOp[i];
  42164. pOp->opcode = (u8)op;
  42165. pOp->p5 = 0;
  42166. pOp->p1 = p1;
  42167. pOp->p2 = p2;
  42168. pOp->p3 = p3;
  42169. pOp->p4.p = 0;
  42170. pOp->p4type = P4_NOTUSED;
  42171. p->expired = 0;
  42172. #ifdef SQLITE_DEBUG
  42173. pOp->zComment = 0;
  42174. if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  42175. #endif
  42176. #ifdef VDBE_PROFILE
  42177. pOp->cycles = 0;
  42178. pOp->cnt = 0;
  42179. #endif
  42180. return i;
  42181. }
  42182. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  42183. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  42184. }
  42185. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  42186. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  42187. }
  42188. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  42189. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  42190. }
  42191. /*
  42192. ** Add an opcode that includes the p4 value as a pointer.
  42193. */
  42194. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  42195. Vdbe *p, /* Add the opcode to this VM */
  42196. int op, /* The new opcode */
  42197. int p1, /* The P1 operand */
  42198. int p2, /* The P2 operand */
  42199. int p3, /* The P3 operand */
  42200. const char *zP4, /* The P4 operand */
  42201. int p4type /* P4 operand type */
  42202. ){
  42203. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  42204. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  42205. return addr;
  42206. }
  42207. /*
  42208. ** Create a new symbolic label for an instruction that has yet to be
  42209. ** coded. The symbolic label is really just a negative number. The
  42210. ** label can be used as the P2 value of an operation. Later, when
  42211. ** the label is resolved to a specific address, the VDBE will scan
  42212. ** through its operation list and change all values of P2 which match
  42213. ** the label into the resolved address.
  42214. **
  42215. ** The VDBE knows that a P2 value is a label because labels are
  42216. ** always negative and P2 values are suppose to be non-negative.
  42217. ** Hence, a negative P2 value is a label that has yet to be resolved.
  42218. **
  42219. ** Zero is returned if a malloc() fails.
  42220. */
  42221. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  42222. int i;
  42223. i = p->nLabel++;
  42224. assert( p->magic==VDBE_MAGIC_INIT );
  42225. if( i>=p->nLabelAlloc ){
  42226. int n = p->nLabelAlloc*2 + 5;
  42227. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  42228. n*sizeof(p->aLabel[0]));
  42229. p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
  42230. }
  42231. if( p->aLabel ){
  42232. p->aLabel[i] = -1;
  42233. }
  42234. return -1-i;
  42235. }
  42236. /*
  42237. ** Resolve label "x" to be the address of the next instruction to
  42238. ** be inserted. The parameter "x" must have been obtained from
  42239. ** a prior call to sqlite3VdbeMakeLabel().
  42240. */
  42241. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  42242. int j = -1-x;
  42243. assert( p->magic==VDBE_MAGIC_INIT );
  42244. assert( j>=0 && j<p->nLabel );
  42245. if( p->aLabel ){
  42246. p->aLabel[j] = p->nOp;
  42247. }
  42248. }
  42249. /*
  42250. ** Loop through the program looking for P2 values that are negative
  42251. ** on jump instructions. Each such value is a label. Resolve the
  42252. ** label by setting the P2 value to its correct non-zero value.
  42253. **
  42254. ** This routine is called once after all opcodes have been inserted.
  42255. **
  42256. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  42257. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  42258. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  42259. **
  42260. ** This routine also does the following optimization: It scans for
  42261. ** instructions that might cause a statement rollback. Such instructions
  42262. ** are:
  42263. **
  42264. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  42265. ** * OP_Destroy
  42266. ** * OP_VUpdate
  42267. ** * OP_VRename
  42268. **
  42269. ** If no such instruction is found, then every Statement instruction
  42270. ** is changed to a Noop. In this way, we avoid creating the statement
  42271. ** journal file unnecessarily.
  42272. */
  42273. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  42274. int i;
  42275. int nMaxArgs = 0;
  42276. Op *pOp;
  42277. int *aLabel = p->aLabel;
  42278. int doesStatementRollback = 0;
  42279. int hasStatementBegin = 0;
  42280. p->readOnly = 1;
  42281. p->usesStmtJournal = 0;
  42282. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  42283. u8 opcode = pOp->opcode;
  42284. if( opcode==OP_Function || opcode==OP_AggStep ){
  42285. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  42286. #ifndef SQLITE_OMIT_VIRTUALTABLE
  42287. }else if( opcode==OP_VUpdate ){
  42288. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  42289. #endif
  42290. }
  42291. if( opcode==OP_Halt ){
  42292. if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
  42293. doesStatementRollback = 1;
  42294. }
  42295. }else if( opcode==OP_Statement ){
  42296. hasStatementBegin = 1;
  42297. p->usesStmtJournal = 1;
  42298. }else if( opcode==OP_Destroy ){
  42299. doesStatementRollback = 1;
  42300. }else if( opcode==OP_Transaction && pOp->p2!=0 ){
  42301. p->readOnly = 0;
  42302. #ifndef SQLITE_OMIT_VIRTUALTABLE
  42303. }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
  42304. doesStatementRollback = 1;
  42305. }else if( opcode==OP_VFilter ){
  42306. int n;
  42307. assert( p->nOp - i >= 3 );
  42308. assert( pOp[-1].opcode==OP_Integer );
  42309. n = pOp[-1].p1;
  42310. if( n>nMaxArgs ) nMaxArgs = n;
  42311. #endif
  42312. }
  42313. if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
  42314. assert( -1-pOp->p2<p->nLabel );
  42315. pOp->p2 = aLabel[-1-pOp->p2];
  42316. }
  42317. }
  42318. sqlite3DbFree(p->db, p->aLabel);
  42319. p->aLabel = 0;
  42320. *pMaxFuncArgs = nMaxArgs;
  42321. /* If we never rollback a statement transaction, then statement
  42322. ** transactions are not needed. So change every OP_Statement
  42323. ** opcode into an OP_Noop. This avoid a call to sqlite3OsOpenExclusive()
  42324. ** which can be expensive on some platforms.
  42325. */
  42326. if( hasStatementBegin && !doesStatementRollback ){
  42327. p->usesStmtJournal = 0;
  42328. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  42329. if( pOp->opcode==OP_Statement ){
  42330. pOp->opcode = OP_Noop;
  42331. }
  42332. }
  42333. }
  42334. }
  42335. /*
  42336. ** Return the address of the next instruction to be inserted.
  42337. */
  42338. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  42339. assert( p->magic==VDBE_MAGIC_INIT );
  42340. return p->nOp;
  42341. }
  42342. /*
  42343. ** Add a whole list of operations to the operation stack. Return the
  42344. ** address of the first operation added.
  42345. */
  42346. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  42347. int addr;
  42348. assert( p->magic==VDBE_MAGIC_INIT );
  42349. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
  42350. return 0;
  42351. }
  42352. addr = p->nOp;
  42353. if( nOp>0 ){
  42354. int i;
  42355. VdbeOpList const *pIn = aOp;
  42356. for(i=0; i<nOp; i++, pIn++){
  42357. int p2 = pIn->p2;
  42358. VdbeOp *pOut = &p->aOp[i+addr];
  42359. pOut->opcode = pIn->opcode;
  42360. pOut->p1 = pIn->p1;
  42361. if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
  42362. pOut->p2 = addr + ADDR(p2);
  42363. }else{
  42364. pOut->p2 = p2;
  42365. }
  42366. pOut->p3 = pIn->p3;
  42367. pOut->p4type = P4_NOTUSED;
  42368. pOut->p4.p = 0;
  42369. pOut->p5 = 0;
  42370. #ifdef SQLITE_DEBUG
  42371. pOut->zComment = 0;
  42372. if( sqlite3VdbeAddopTrace ){
  42373. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  42374. }
  42375. #endif
  42376. }
  42377. p->nOp += nOp;
  42378. }
  42379. return addr;
  42380. }
  42381. /*
  42382. ** Change the value of the P1 operand for a specific instruction.
  42383. ** This routine is useful when a large program is loaded from a
  42384. ** static array using sqlite3VdbeAddOpList but we want to make a
  42385. ** few minor changes to the program.
  42386. */
  42387. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
  42388. assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  42389. if( p && addr>=0 && p->nOp>addr && p->aOp ){
  42390. p->aOp[addr].p1 = val;
  42391. }
  42392. }
  42393. /*
  42394. ** Change the value of the P2 operand for a specific instruction.
  42395. ** This routine is useful for setting a jump destination.
  42396. */
  42397. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
  42398. assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  42399. if( p && addr>=0 && p->nOp>addr && p->aOp ){
  42400. p->aOp[addr].p2 = val;
  42401. }
  42402. }
  42403. /*
  42404. ** Change the value of the P3 operand for a specific instruction.
  42405. */
  42406. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
  42407. assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  42408. if( p && addr>=0 && p->nOp>addr && p->aOp ){
  42409. p->aOp[addr].p3 = val;
  42410. }
  42411. }
  42412. /*
  42413. ** Change the value of the P5 operand for the most recently
  42414. ** added operation.
  42415. */
  42416. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  42417. assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  42418. if( p && p->aOp ){
  42419. assert( p->nOp>0 );
  42420. p->aOp[p->nOp-1].p5 = val;
  42421. }
  42422. }
  42423. /*
  42424. ** Change the P2 operand of instruction addr so that it points to
  42425. ** the address of the next instruction to be coded.
  42426. */
  42427. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  42428. sqlite3VdbeChangeP2(p, addr, p->nOp);
  42429. }
  42430. /*
  42431. ** If the input FuncDef structure is ephemeral, then free it. If
  42432. ** the FuncDef is not ephermal, then do nothing.
  42433. */
  42434. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  42435. if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
  42436. sqlite3DbFree(db, pDef);
  42437. }
  42438. }
  42439. /*
  42440. ** Delete a P4 value if necessary.
  42441. */
  42442. static void freeP4(sqlite3 *db, int p4type, void *p4){
  42443. if( p4 ){
  42444. switch( p4type ){
  42445. case P4_REAL:
  42446. case P4_INT64:
  42447. case P4_MPRINTF:
  42448. case P4_DYNAMIC:
  42449. case P4_KEYINFO:
  42450. case P4_INTARRAY:
  42451. case P4_KEYINFO_HANDOFF: {
  42452. sqlite3DbFree(db, p4);
  42453. break;
  42454. }
  42455. case P4_VDBEFUNC: {
  42456. VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
  42457. freeEphemeralFunction(db, pVdbeFunc->pFunc);
  42458. sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
  42459. sqlite3DbFree(db, pVdbeFunc);
  42460. break;
  42461. }
  42462. case P4_FUNCDEF: {
  42463. freeEphemeralFunction(db, (FuncDef*)p4);
  42464. break;
  42465. }
  42466. case P4_MEM: {
  42467. sqlite3ValueFree((sqlite3_value*)p4);
  42468. break;
  42469. }
  42470. }
  42471. }
  42472. }
  42473. /*
  42474. ** Change N opcodes starting at addr to No-ops.
  42475. */
  42476. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
  42477. if( p && p->aOp ){
  42478. VdbeOp *pOp = &p->aOp[addr];
  42479. sqlite3 *db = p->db;
  42480. while( N-- ){
  42481. freeP4(db, pOp->p4type, pOp->p4.p);
  42482. memset(pOp, 0, sizeof(pOp[0]));
  42483. pOp->opcode = OP_Noop;
  42484. pOp++;
  42485. }
  42486. }
  42487. }
  42488. /*
  42489. ** Change the value of the P4 operand for a specific instruction.
  42490. ** This routine is useful when a large program is loaded from a
  42491. ** static array using sqlite3VdbeAddOpList but we want to make a
  42492. ** few minor changes to the program.
  42493. **
  42494. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  42495. ** the string is made into memory obtained from sqlite3_malloc().
  42496. ** A value of n==0 means copy bytes of zP4 up to and including the
  42497. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  42498. **
  42499. ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
  42500. ** A copy is made of the KeyInfo structure into memory obtained from
  42501. ** sqlite3_malloc, to be freed when the Vdbe is finalized.
  42502. ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
  42503. ** stored in memory that the caller has obtained from sqlite3_malloc. The
  42504. ** caller should not free the allocation, it will be freed when the Vdbe is
  42505. ** finalized.
  42506. **
  42507. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  42508. ** to a string or structure that is guaranteed to exist for the lifetime of
  42509. ** the Vdbe. In these cases we can just copy the pointer.
  42510. **
  42511. ** If addr<0 then change P4 on the most recently inserted instruction.
  42512. */
  42513. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  42514. Op *pOp;
  42515. sqlite3 *db;
  42516. assert( p!=0 );
  42517. db = p->db;
  42518. assert( p->magic==VDBE_MAGIC_INIT );
  42519. if( p->aOp==0 || db->mallocFailed ){
  42520. if (n != P4_KEYINFO) {
  42521. freeP4(db, n, (void*)*(char**)&zP4);
  42522. }
  42523. return;
  42524. }
  42525. assert( addr<p->nOp );
  42526. if( addr<0 ){
  42527. addr = p->nOp - 1;
  42528. if( addr<0 ) return;
  42529. }
  42530. pOp = &p->aOp[addr];
  42531. freeP4(db, pOp->p4type, pOp->p4.p);
  42532. pOp->p4.p = 0;
  42533. if( n==P4_INT32 ){
  42534. /* Note: this cast is safe, because the origin data point was an int
  42535. ** that was cast to a (const char *). */
  42536. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  42537. pOp->p4type = P4_INT32;
  42538. }else if( zP4==0 ){
  42539. pOp->p4.p = 0;
  42540. pOp->p4type = P4_NOTUSED;
  42541. }else if( n==P4_KEYINFO ){
  42542. KeyInfo *pKeyInfo;
  42543. int nField, nByte;
  42544. nField = ((KeyInfo*)zP4)->nField;
  42545. nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
  42546. pKeyInfo = sqlite3Malloc( nByte );
  42547. pOp->p4.pKeyInfo = pKeyInfo;
  42548. if( pKeyInfo ){
  42549. u8 *aSortOrder;
  42550. memcpy(pKeyInfo, zP4, nByte);
  42551. aSortOrder = pKeyInfo->aSortOrder;
  42552. if( aSortOrder ){
  42553. pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
  42554. memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
  42555. }
  42556. pOp->p4type = P4_KEYINFO;
  42557. }else{
  42558. p->db->mallocFailed = 1;
  42559. pOp->p4type = P4_NOTUSED;
  42560. }
  42561. }else if( n==P4_KEYINFO_HANDOFF ){
  42562. pOp->p4.p = (void*)zP4;
  42563. pOp->p4type = P4_KEYINFO;
  42564. }else if( n<0 ){
  42565. pOp->p4.p = (void*)zP4;
  42566. pOp->p4type = (signed char)n;
  42567. }else{
  42568. if( n==0 ) n = sqlite3Strlen30(zP4);
  42569. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  42570. pOp->p4type = P4_DYNAMIC;
  42571. }
  42572. }
  42573. #ifndef NDEBUG
  42574. /*
  42575. ** Change the comment on the the most recently coded instruction. Or
  42576. ** insert a No-op and add the comment to that new instruction. This
  42577. ** makes the code easier to read during debugging. None of this happens
  42578. ** in a production build.
  42579. */
  42580. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  42581. va_list ap;
  42582. assert( p->nOp>0 || p->aOp==0 );
  42583. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  42584. if( p->nOp ){
  42585. char **pz = &p->aOp[p->nOp-1].zComment;
  42586. va_start(ap, zFormat);
  42587. sqlite3DbFree(p->db, *pz);
  42588. *pz = sqlite3VMPrintf(p->db, zFormat, ap);
  42589. va_end(ap);
  42590. }
  42591. }
  42592. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  42593. va_list ap;
  42594. sqlite3VdbeAddOp0(p, OP_Noop);
  42595. assert( p->nOp>0 || p->aOp==0 );
  42596. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  42597. if( p->nOp ){
  42598. char **pz = &p->aOp[p->nOp-1].zComment;
  42599. va_start(ap, zFormat);
  42600. sqlite3DbFree(p->db, *pz);
  42601. *pz = sqlite3VMPrintf(p->db, zFormat, ap);
  42602. va_end(ap);
  42603. }
  42604. }
  42605. #endif /* NDEBUG */
  42606. /*
  42607. ** Return the opcode for a given address.
  42608. */
  42609. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  42610. assert( p->magic==VDBE_MAGIC_INIT );
  42611. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  42612. return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
  42613. }
  42614. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  42615. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  42616. /*
  42617. ** Compute a string that describes the P4 parameter for an opcode.
  42618. ** Use zTemp for any required temporary buffer space.
  42619. */
  42620. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  42621. char *zP4 = zTemp;
  42622. assert( nTemp>=20 );
  42623. switch( pOp->p4type ){
  42624. case P4_KEYINFO_STATIC:
  42625. case P4_KEYINFO: {
  42626. int i, j;
  42627. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  42628. sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
  42629. i = sqlite3Strlen30(zTemp);
  42630. for(j=0; j<pKeyInfo->nField; j++){
  42631. CollSeq *pColl = pKeyInfo->aColl[j];
  42632. if( pColl ){
  42633. int n = sqlite3Strlen30(pColl->zName);
  42634. if( i+n>nTemp-6 ){
  42635. memcpy(&zTemp[i],",...",4);
  42636. break;
  42637. }
  42638. zTemp[i++] = ',';
  42639. if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
  42640. zTemp[i++] = '-';
  42641. }
  42642. memcpy(&zTemp[i], pColl->zName,n+1);
  42643. i += n;
  42644. }else if( i+4<nTemp-6 ){
  42645. memcpy(&zTemp[i],",nil",4);
  42646. i += 4;
  42647. }
  42648. }
  42649. zTemp[i++] = ')';
  42650. zTemp[i] = 0;
  42651. assert( i<nTemp );
  42652. break;
  42653. }
  42654. case P4_COLLSEQ: {
  42655. CollSeq *pColl = pOp->p4.pColl;
  42656. sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
  42657. break;
  42658. }
  42659. case P4_FUNCDEF: {
  42660. FuncDef *pDef = pOp->p4.pFunc;
  42661. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  42662. break;
  42663. }
  42664. case P4_INT64: {
  42665. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  42666. break;
  42667. }
  42668. case P4_INT32: {
  42669. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  42670. break;
  42671. }
  42672. case P4_REAL: {
  42673. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  42674. break;
  42675. }
  42676. case P4_MEM: {
  42677. Mem *pMem = pOp->p4.pMem;
  42678. assert( (pMem->flags & MEM_Null)==0 );
  42679. if( pMem->flags & MEM_Str ){
  42680. zP4 = pMem->z;
  42681. }else if( pMem->flags & MEM_Int ){
  42682. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  42683. }else if( pMem->flags & MEM_Real ){
  42684. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
  42685. }
  42686. break;
  42687. }
  42688. #ifndef SQLITE_OMIT_VIRTUALTABLE
  42689. case P4_VTAB: {
  42690. sqlite3_vtab *pVtab = pOp->p4.pVtab;
  42691. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  42692. break;
  42693. }
  42694. #endif
  42695. case P4_INTARRAY: {
  42696. sqlite3_snprintf(nTemp, zTemp, "intarray");
  42697. break;
  42698. }
  42699. default: {
  42700. zP4 = pOp->p4.z;
  42701. if( zP4==0 ){
  42702. zP4 = zTemp;
  42703. zTemp[0] = 0;
  42704. }
  42705. }
  42706. }
  42707. assert( zP4!=0 );
  42708. return zP4;
  42709. }
  42710. #endif
  42711. /*
  42712. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  42713. **
  42714. */
  42715. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  42716. int mask;
  42717. assert( i>=0 && i<p->db->nDb );
  42718. assert( i<(int)sizeof(p->btreeMask)*8 );
  42719. mask = 1<<i;
  42720. if( (p->btreeMask & mask)==0 ){
  42721. p->btreeMask |= mask;
  42722. sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
  42723. }
  42724. }
  42725. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  42726. /*
  42727. ** Print a single opcode. This routine is used for debugging only.
  42728. */
  42729. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  42730. char *zP4;
  42731. char zPtr[50];
  42732. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  42733. if( pOut==0 ) pOut = stdout;
  42734. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  42735. fprintf(pOut, zFormat1, pc,
  42736. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  42737. #ifdef SQLITE_DEBUG
  42738. pOp->zComment ? pOp->zComment : ""
  42739. #else
  42740. ""
  42741. #endif
  42742. );
  42743. fflush(pOut);
  42744. }
  42745. #endif
  42746. /*
  42747. ** Release an array of N Mem elements
  42748. */
  42749. static void releaseMemArray(Mem *p, int N){
  42750. if( p && N ){
  42751. Mem *pEnd;
  42752. sqlite3 *db = p->db;
  42753. u8 malloc_failed = db->mallocFailed;
  42754. for(pEnd=&p[N]; p<pEnd; p++){
  42755. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  42756. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  42757. ** that takes advantage of the fact that the memory cell value is
  42758. ** being set to NULL after releasing any dynamic resources.
  42759. **
  42760. ** The justification for duplicating code is that according to
  42761. ** callgrind, this causes a certain test case to hit the CPU 4.7
  42762. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  42763. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  42764. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  42765. ** with no indexes using a single prepared INSERT statement, bind()
  42766. ** and reset(). Inserts are grouped into a transaction.
  42767. */
  42768. if( p->flags&(MEM_Agg|MEM_Dyn) ){
  42769. sqlite3VdbeMemRelease(p);
  42770. }else if( p->zMalloc ){
  42771. sqlite3DbFree(db, p->zMalloc);
  42772. p->zMalloc = 0;
  42773. }
  42774. p->flags = MEM_Null;
  42775. }
  42776. db->mallocFailed = malloc_failed;
  42777. }
  42778. }
  42779. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  42780. SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p){
  42781. int ii;
  42782. int nFree = 0;
  42783. assert( sqlite3_mutex_held(p->db->mutex) );
  42784. for(ii=1; ii<=p->nMem; ii++){
  42785. Mem *pMem = &p->aMem[ii];
  42786. if( pMem->flags & MEM_RowSet ){
  42787. sqlite3RowSetClear(pMem->u.pRowSet);
  42788. }
  42789. if( pMem->z && pMem->flags&MEM_Dyn ){
  42790. assert( !pMem->xDel );
  42791. nFree += sqlite3DbMallocSize(pMem->db, pMem->z);
  42792. sqlite3VdbeMemRelease(pMem);
  42793. }
  42794. }
  42795. return nFree;
  42796. }
  42797. #endif
  42798. #ifndef SQLITE_OMIT_EXPLAIN
  42799. /*
  42800. ** Give a listing of the program in the virtual machine.
  42801. **
  42802. ** The interface is the same as sqlite3VdbeExec(). But instead of
  42803. ** running the code, it invokes the callback once for each instruction.
  42804. ** This feature is used to implement "EXPLAIN".
  42805. **
  42806. ** When p->explain==1, each instruction is listed. When
  42807. ** p->explain==2, only OP_Explain instructions are listed and these
  42808. ** are shown in a different format. p->explain==2 is used to implement
  42809. ** EXPLAIN QUERY PLAN.
  42810. */
  42811. SQLITE_PRIVATE int sqlite3VdbeList(
  42812. Vdbe *p /* The VDBE */
  42813. ){
  42814. sqlite3 *db = p->db;
  42815. int i;
  42816. int rc = SQLITE_OK;
  42817. Mem *pMem = p->pResultSet = &p->aMem[1];
  42818. assert( p->explain );
  42819. if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
  42820. assert( db->magic==SQLITE_MAGIC_BUSY );
  42821. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  42822. /* Even though this opcode does not use dynamic strings for
  42823. ** the result, result columns may become dynamic if the user calls
  42824. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  42825. */
  42826. releaseMemArray(pMem, p->nMem);
  42827. if( p->rc==SQLITE_NOMEM ){
  42828. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  42829. ** sqlite3_column_text16() failed. */
  42830. db->mallocFailed = 1;
  42831. return SQLITE_ERROR;
  42832. }
  42833. do{
  42834. i = p->pc++;
  42835. }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  42836. if( i>=p->nOp ){
  42837. p->rc = SQLITE_OK;
  42838. rc = SQLITE_DONE;
  42839. }else if( db->u1.isInterrupted ){
  42840. p->rc = SQLITE_INTERRUPT;
  42841. rc = SQLITE_ERROR;
  42842. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  42843. }else{
  42844. char *z;
  42845. Op *pOp = &p->aOp[i];
  42846. if( p->explain==1 ){
  42847. pMem->flags = MEM_Int;
  42848. pMem->type = SQLITE_INTEGER;
  42849. pMem->u.i = i; /* Program counter */
  42850. pMem++;
  42851. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  42852. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  42853. assert( pMem->z!=0 );
  42854. pMem->n = sqlite3Strlen30(pMem->z);
  42855. pMem->type = SQLITE_TEXT;
  42856. pMem->enc = SQLITE_UTF8;
  42857. pMem++;
  42858. }
  42859. pMem->flags = MEM_Int;
  42860. pMem->u.i = pOp->p1; /* P1 */
  42861. pMem->type = SQLITE_INTEGER;
  42862. pMem++;
  42863. pMem->flags = MEM_Int;
  42864. pMem->u.i = pOp->p2; /* P2 */
  42865. pMem->type = SQLITE_INTEGER;
  42866. pMem++;
  42867. if( p->explain==1 ){
  42868. pMem->flags = MEM_Int;
  42869. pMem->u.i = pOp->p3; /* P3 */
  42870. pMem->type = SQLITE_INTEGER;
  42871. pMem++;
  42872. }
  42873. if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
  42874. p->db->mallocFailed = 1;
  42875. return SQLITE_NOMEM;
  42876. }
  42877. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  42878. z = displayP4(pOp, pMem->z, 32);
  42879. if( z!=pMem->z ){
  42880. sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
  42881. }else{
  42882. assert( pMem->z!=0 );
  42883. pMem->n = sqlite3Strlen30(pMem->z);
  42884. pMem->enc = SQLITE_UTF8;
  42885. }
  42886. pMem->type = SQLITE_TEXT;
  42887. pMem++;
  42888. if( p->explain==1 ){
  42889. if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  42890. p->db->mallocFailed = 1;
  42891. return SQLITE_NOMEM;
  42892. }
  42893. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  42894. pMem->n = 2;
  42895. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  42896. pMem->type = SQLITE_TEXT;
  42897. pMem->enc = SQLITE_UTF8;
  42898. pMem++;
  42899. #ifdef SQLITE_DEBUG
  42900. if( pOp->zComment ){
  42901. pMem->flags = MEM_Str|MEM_Term;
  42902. pMem->z = pOp->zComment;
  42903. pMem->n = sqlite3Strlen30(pMem->z);
  42904. pMem->enc = SQLITE_UTF8;
  42905. pMem->type = SQLITE_TEXT;
  42906. }else
  42907. #endif
  42908. {
  42909. pMem->flags = MEM_Null; /* Comment */
  42910. pMem->type = SQLITE_NULL;
  42911. }
  42912. }
  42913. p->nResColumn = 8 - 5*(p->explain-1);
  42914. p->rc = SQLITE_OK;
  42915. rc = SQLITE_ROW;
  42916. }
  42917. return rc;
  42918. }
  42919. #endif /* SQLITE_OMIT_EXPLAIN */
  42920. #ifdef SQLITE_DEBUG
  42921. /*
  42922. ** Print the SQL that was used to generate a VDBE program.
  42923. */
  42924. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  42925. int nOp = p->nOp;
  42926. VdbeOp *pOp;
  42927. if( nOp<1 ) return;
  42928. pOp = &p->aOp[0];
  42929. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  42930. const char *z = pOp->p4.z;
  42931. while( isspace(*(u8*)z) ) z++;
  42932. printf("SQL: [%s]\n", z);
  42933. }
  42934. }
  42935. #endif
  42936. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  42937. /*
  42938. ** Print an IOTRACE message showing SQL content.
  42939. */
  42940. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  42941. int nOp = p->nOp;
  42942. VdbeOp *pOp;
  42943. if( sqlite3IoTrace==0 ) return;
  42944. if( nOp<1 ) return;
  42945. pOp = &p->aOp[0];
  42946. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  42947. int i, j;
  42948. char z[1000];
  42949. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  42950. for(i=0; isspace((unsigned char)z[i]); i++){}
  42951. for(j=0; z[i]; i++){
  42952. if( isspace((unsigned char)z[i]) ){
  42953. if( z[i-1]!=' ' ){
  42954. z[j++] = ' ';
  42955. }
  42956. }else{
  42957. z[j++] = z[i];
  42958. }
  42959. }
  42960. z[j] = 0;
  42961. sqlite3IoTrace("SQL %s\n", z);
  42962. }
  42963. }
  42964. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  42965. /*
  42966. ** Prepare a virtual machine for execution. This involves things such
  42967. ** as allocating stack space and initializing the program counter.
  42968. ** After the VDBE has be prepped, it can be executed by one or more
  42969. ** calls to sqlite3VdbeExec().
  42970. **
  42971. ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
  42972. ** VDBE_MAGIC_RUN.
  42973. */
  42974. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  42975. Vdbe *p, /* The VDBE */
  42976. int nVar, /* Number of '?' see in the SQL statement */
  42977. int nMem, /* Number of memory cells to allocate */
  42978. int nCursor, /* Number of cursors to allocate */
  42979. int isExplain /* True if the EXPLAIN keywords is present */
  42980. ){
  42981. int n;
  42982. sqlite3 *db = p->db;
  42983. assert( p!=0 );
  42984. assert( p->magic==VDBE_MAGIC_INIT );
  42985. /* There should be at least one opcode.
  42986. */
  42987. assert( p->nOp>0 );
  42988. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  42989. p->magic = VDBE_MAGIC_RUN;
  42990. /* For each cursor required, also allocate a memory cell. Memory
  42991. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  42992. ** the vdbe program. Instead they are used to allocate space for
  42993. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  42994. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  42995. ** stores the blob of memory associated with cursor 1, etc.
  42996. **
  42997. ** See also: allocateCursor().
  42998. */
  42999. nMem += nCursor;
  43000. /*
  43001. ** Allocation space for registers.
  43002. */
  43003. if( p->aMem==0 ){
  43004. int nArg; /* Maximum number of args passed to a user function. */
  43005. resolveP2Values(p, &nArg);
  43006. assert( nVar>=0 );
  43007. if( isExplain && nMem<10 ){
  43008. nMem = 10;
  43009. }
  43010. p->aMem = sqlite3DbMallocZero(db,
  43011. nMem*sizeof(Mem) /* aMem */
  43012. + nVar*sizeof(Mem) /* aVar */
  43013. + nArg*sizeof(Mem*) /* apArg */
  43014. + nVar*sizeof(char*) /* azVar */
  43015. + nCursor*sizeof(VdbeCursor*)+1 /* apCsr */
  43016. );
  43017. if( !db->mallocFailed ){
  43018. p->aMem--; /* aMem[] goes from 1..nMem */
  43019. p->nMem = nMem; /* not from 0..nMem-1 */
  43020. p->aVar = &p->aMem[nMem+1];
  43021. p->nVar = nVar;
  43022. p->okVar = 0;
  43023. p->apArg = (Mem**)&p->aVar[nVar];
  43024. p->azVar = (char**)&p->apArg[nArg];
  43025. p->apCsr = (VdbeCursor**)&p->azVar[nVar];
  43026. p->nCursor = nCursor;
  43027. for(n=0; n<nVar; n++){
  43028. p->aVar[n].flags = MEM_Null;
  43029. p->aVar[n].db = db;
  43030. }
  43031. for(n=1; n<=nMem; n++){
  43032. p->aMem[n].flags = MEM_Null;
  43033. p->aMem[n].db = db;
  43034. }
  43035. }
  43036. }
  43037. #ifdef SQLITE_DEBUG
  43038. for(n=1; n<p->nMem; n++){
  43039. assert( p->aMem[n].db==db );
  43040. }
  43041. #endif
  43042. p->pc = -1;
  43043. p->rc = SQLITE_OK;
  43044. p->uniqueCnt = 0;
  43045. p->errorAction = OE_Abort;
  43046. p->explain |= isExplain;
  43047. p->magic = VDBE_MAGIC_RUN;
  43048. p->nChange = 0;
  43049. p->cacheCtr = 1;
  43050. p->minWriteFileFormat = 255;
  43051. p->openedStatement = 0;
  43052. #ifdef VDBE_PROFILE
  43053. {
  43054. int i;
  43055. for(i=0; i<p->nOp; i++){
  43056. p->aOp[i].cnt = 0;
  43057. p->aOp[i].cycles = 0;
  43058. }
  43059. }
  43060. #endif
  43061. }
  43062. /*
  43063. ** Close a VDBE cursor and release all the resources that cursor
  43064. ** happens to hold.
  43065. */
  43066. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  43067. if( pCx==0 ){
  43068. return;
  43069. }
  43070. if( pCx->pBt ){
  43071. sqlite3BtreeClose(pCx->pBt);
  43072. /* The pCx->pCursor will be close automatically, if it exists, by
  43073. ** the call above. */
  43074. }else if( pCx->pCursor ){
  43075. sqlite3BtreeCloseCursor(pCx->pCursor);
  43076. }
  43077. #ifndef SQLITE_OMIT_VIRTUALTABLE
  43078. if( pCx->pVtabCursor ){
  43079. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  43080. const sqlite3_module *pModule = pCx->pModule;
  43081. p->inVtabMethod = 1;
  43082. (void)sqlite3SafetyOff(p->db);
  43083. pModule->xClose(pVtabCursor);
  43084. (void)sqlite3SafetyOn(p->db);
  43085. p->inVtabMethod = 0;
  43086. }
  43087. #endif
  43088. if( !pCx->ephemPseudoTable ){
  43089. sqlite3DbFree(p->db, pCx->pData);
  43090. }
  43091. }
  43092. /*
  43093. ** Close all cursors except for VTab cursors that are currently
  43094. ** in use.
  43095. */
  43096. static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
  43097. int i;
  43098. if( p->apCsr==0 ) return;
  43099. for(i=0; i<p->nCursor; i++){
  43100. VdbeCursor *pC = p->apCsr[i];
  43101. if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
  43102. sqlite3VdbeFreeCursor(p, pC);
  43103. p->apCsr[i] = 0;
  43104. }
  43105. }
  43106. }
  43107. /*
  43108. ** Clean up the VM after execution.
  43109. **
  43110. ** This routine will automatically close any cursors, lists, and/or
  43111. ** sorters that were left open. It also deletes the values of
  43112. ** variables in the aVar[] array.
  43113. */
  43114. static void Cleanup(Vdbe *p){
  43115. int i;
  43116. sqlite3 *db = p->db;
  43117. Mem *pMem;
  43118. closeAllCursorsExceptActiveVtabs(p);
  43119. for(pMem=&p->aMem[1], i=1; i<=p->nMem; i++, pMem++){
  43120. if( pMem->flags & MEM_RowSet ){
  43121. sqlite3RowSetClear(pMem->u.pRowSet);
  43122. }
  43123. MemSetTypeFlag(pMem, MEM_Null);
  43124. }
  43125. releaseMemArray(&p->aMem[1], p->nMem);
  43126. if( p->contextStack ){
  43127. sqlite3DbFree(db, p->contextStack);
  43128. }
  43129. p->contextStack = 0;
  43130. p->contextStackDepth = 0;
  43131. p->contextStackTop = 0;
  43132. sqlite3DbFree(db, p->zErrMsg);
  43133. p->zErrMsg = 0;
  43134. p->pResultSet = 0;
  43135. }
  43136. /*
  43137. ** Set the number of result columns that will be returned by this SQL
  43138. ** statement. This is now set at compile time, rather than during
  43139. ** execution of the vdbe program so that sqlite3_column_count() can
  43140. ** be called on an SQL statement before sqlite3_step().
  43141. */
  43142. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  43143. Mem *pColName;
  43144. int n;
  43145. sqlite3 *db = p->db;
  43146. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  43147. sqlite3DbFree(db, p->aColName);
  43148. n = nResColumn*COLNAME_N;
  43149. p->nResColumn = nResColumn;
  43150. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  43151. if( p->aColName==0 ) return;
  43152. while( n-- > 0 ){
  43153. pColName->flags = MEM_Null;
  43154. pColName->db = p->db;
  43155. pColName++;
  43156. }
  43157. }
  43158. /*
  43159. ** Set the name of the idx'th column to be returned by the SQL statement.
  43160. ** zName must be a pointer to a nul terminated string.
  43161. **
  43162. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  43163. **
  43164. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  43165. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  43166. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  43167. */
  43168. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  43169. Vdbe *p, /* Vdbe being configured */
  43170. int idx, /* Index of column zName applies to */
  43171. int var, /* One of the COLNAME_* constants */
  43172. const char *zName, /* Pointer to buffer containing name */
  43173. void (*xDel)(void*) /* Memory management strategy for zName */
  43174. ){
  43175. int rc;
  43176. Mem *pColName;
  43177. assert( idx<p->nResColumn );
  43178. assert( var<COLNAME_N );
  43179. if( p->db->mallocFailed ){
  43180. assert( !zName || xDel!=SQLITE_DYNAMIC );
  43181. return SQLITE_NOMEM;
  43182. }
  43183. assert( p->aColName!=0 );
  43184. pColName = &(p->aColName[idx+var*p->nResColumn]);
  43185. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  43186. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  43187. return rc;
  43188. }
  43189. /*
  43190. ** A read or write transaction may or may not be active on database handle
  43191. ** db. If a transaction is active, commit it. If there is a
  43192. ** write-transaction spanning more than one database file, this routine
  43193. ** takes care of the master journal trickery.
  43194. */
  43195. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  43196. int i;
  43197. int nTrans = 0; /* Number of databases with an active write-transaction */
  43198. int rc = SQLITE_OK;
  43199. int needXcommit = 0;
  43200. /* Before doing anything else, call the xSync() callback for any
  43201. ** virtual module tables written in this transaction. This has to
  43202. ** be done before determining whether a master journal file is
  43203. ** required, as an xSync() callback may add an attached database
  43204. ** to the transaction.
  43205. */
  43206. rc = sqlite3VtabSync(db, &p->zErrMsg);
  43207. if( rc!=SQLITE_OK ){
  43208. return rc;
  43209. }
  43210. /* This loop determines (a) if the commit hook should be invoked and
  43211. ** (b) how many database files have open write transactions, not
  43212. ** including the temp database. (b) is important because if more than
  43213. ** one database file has an open write transaction, a master journal
  43214. ** file is required for an atomic commit.
  43215. */
  43216. for(i=0; i<db->nDb; i++){
  43217. Btree *pBt = db->aDb[i].pBt;
  43218. if( sqlite3BtreeIsInTrans(pBt) ){
  43219. needXcommit = 1;
  43220. if( i!=1 ) nTrans++;
  43221. }
  43222. }
  43223. /* If there are any write-transactions at all, invoke the commit hook */
  43224. if( needXcommit && db->xCommitCallback ){
  43225. assert( (db->flags & SQLITE_CommitBusy)==0 );
  43226. db->flags |= SQLITE_CommitBusy;
  43227. (void)sqlite3SafetyOff(db);
  43228. rc = db->xCommitCallback(db->pCommitArg);
  43229. (void)sqlite3SafetyOn(db);
  43230. db->flags &= ~SQLITE_CommitBusy;
  43231. if( rc ){
  43232. return SQLITE_CONSTRAINT;
  43233. }
  43234. }
  43235. /* The simple case - no more than one database file (not counting the
  43236. ** TEMP database) has a transaction active. There is no need for the
  43237. ** master-journal.
  43238. **
  43239. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  43240. ** string, it means the main database is :memory: or a temp file. In
  43241. ** that case we do not support atomic multi-file commits, so use the
  43242. ** simple case then too.
  43243. */
  43244. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  43245. || nTrans<=1
  43246. ){
  43247. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  43248. Btree *pBt = db->aDb[i].pBt;
  43249. if( pBt ){
  43250. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  43251. }
  43252. }
  43253. /* Do the commit only if all databases successfully complete phase 1.
  43254. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  43255. ** IO error while deleting or truncating a journal file. It is unlikely,
  43256. ** but could happen. In this case abandon processing and return the error.
  43257. */
  43258. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  43259. Btree *pBt = db->aDb[i].pBt;
  43260. if( pBt ){
  43261. rc = sqlite3BtreeCommitPhaseTwo(pBt);
  43262. }
  43263. }
  43264. if( rc==SQLITE_OK ){
  43265. sqlite3VtabCommit(db);
  43266. }
  43267. }
  43268. /* The complex case - There is a multi-file write-transaction active.
  43269. ** This requires a master journal file to ensure the transaction is
  43270. ** committed atomicly.
  43271. */
  43272. #ifndef SQLITE_OMIT_DISKIO
  43273. else{
  43274. sqlite3_vfs *pVfs = db->pVfs;
  43275. int needSync = 0;
  43276. char *zMaster = 0; /* File-name for the master journal */
  43277. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  43278. sqlite3_file *pMaster = 0;
  43279. i64 offset = 0;
  43280. int res;
  43281. /* Select a master journal file name */
  43282. do {
  43283. u32 iRandom;
  43284. sqlite3DbFree(db, zMaster);
  43285. sqlite3_randomness(sizeof(iRandom), &iRandom);
  43286. zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
  43287. if( !zMaster ){
  43288. return SQLITE_NOMEM;
  43289. }
  43290. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  43291. }while( rc==SQLITE_OK && res );
  43292. if( rc==SQLITE_OK ){
  43293. /* Open the master journal. */
  43294. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  43295. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  43296. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  43297. );
  43298. }
  43299. if( rc!=SQLITE_OK ){
  43300. sqlite3DbFree(db, zMaster);
  43301. return rc;
  43302. }
  43303. /* Write the name of each database file in the transaction into the new
  43304. ** master journal file. If an error occurs at this point close
  43305. ** and delete the master journal file. All the individual journal files
  43306. ** still have 'null' as the master journal pointer, so they will roll
  43307. ** back independently if a failure occurs.
  43308. */
  43309. for(i=0; i<db->nDb; i++){
  43310. Btree *pBt = db->aDb[i].pBt;
  43311. if( i==1 ) continue; /* Ignore the TEMP database */
  43312. if( sqlite3BtreeIsInTrans(pBt) ){
  43313. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  43314. if( zFile[0]==0 ) continue; /* Ignore :memory: databases */
  43315. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  43316. needSync = 1;
  43317. }
  43318. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  43319. offset += sqlite3Strlen30(zFile)+1;
  43320. if( rc!=SQLITE_OK ){
  43321. sqlite3OsCloseFree(pMaster);
  43322. sqlite3OsDelete(pVfs, zMaster, 0);
  43323. sqlite3DbFree(db, zMaster);
  43324. return rc;
  43325. }
  43326. }
  43327. }
  43328. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  43329. ** flag is set this is not required.
  43330. */
  43331. zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
  43332. if( (needSync
  43333. && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
  43334. && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
  43335. sqlite3OsCloseFree(pMaster);
  43336. sqlite3OsDelete(pVfs, zMaster, 0);
  43337. sqlite3DbFree(db, zMaster);
  43338. return rc;
  43339. }
  43340. /* Sync all the db files involved in the transaction. The same call
  43341. ** sets the master journal pointer in each individual journal. If
  43342. ** an error occurs here, do not delete the master journal file.
  43343. **
  43344. ** If the error occurs during the first call to
  43345. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  43346. ** master journal file will be orphaned. But we cannot delete it,
  43347. ** in case the master journal file name was written into the journal
  43348. ** file before the failure occured.
  43349. */
  43350. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  43351. Btree *pBt = db->aDb[i].pBt;
  43352. if( pBt ){
  43353. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  43354. }
  43355. }
  43356. sqlite3OsCloseFree(pMaster);
  43357. if( rc!=SQLITE_OK ){
  43358. sqlite3DbFree(db, zMaster);
  43359. return rc;
  43360. }
  43361. /* Delete the master journal file. This commits the transaction. After
  43362. ** doing this the directory is synced again before any individual
  43363. ** transaction files are deleted.
  43364. */
  43365. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  43366. sqlite3DbFree(db, zMaster);
  43367. zMaster = 0;
  43368. if( rc ){
  43369. return rc;
  43370. }
  43371. /* All files and directories have already been synced, so the following
  43372. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  43373. ** deleting or truncating journals. If something goes wrong while
  43374. ** this is happening we don't really care. The integrity of the
  43375. ** transaction is already guaranteed, but some stray 'cold' journals
  43376. ** may be lying around. Returning an error code won't help matters.
  43377. */
  43378. disable_simulated_io_errors();
  43379. sqlite3BeginBenignMalloc();
  43380. for(i=0; i<db->nDb; i++){
  43381. Btree *pBt = db->aDb[i].pBt;
  43382. if( pBt ){
  43383. sqlite3BtreeCommitPhaseTwo(pBt);
  43384. }
  43385. }
  43386. sqlite3EndBenignMalloc();
  43387. enable_simulated_io_errors();
  43388. sqlite3VtabCommit(db);
  43389. }
  43390. #endif
  43391. return rc;
  43392. }
  43393. /*
  43394. ** This routine checks that the sqlite3.activeVdbeCnt count variable
  43395. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  43396. ** currently active. An assertion fails if the two counts do not match.
  43397. ** This is an internal self-check only - it is not an essential processing
  43398. ** step.
  43399. **
  43400. ** This is a no-op if NDEBUG is defined.
  43401. */
  43402. #ifndef NDEBUG
  43403. static void checkActiveVdbeCnt(sqlite3 *db){
  43404. Vdbe *p;
  43405. int cnt = 0;
  43406. int nWrite = 0;
  43407. p = db->pVdbe;
  43408. while( p ){
  43409. if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  43410. cnt++;
  43411. if( p->readOnly==0 ) nWrite++;
  43412. }
  43413. p = p->pNext;
  43414. }
  43415. assert( cnt==db->activeVdbeCnt );
  43416. assert( nWrite==db->writeVdbeCnt );
  43417. }
  43418. #else
  43419. #define checkActiveVdbeCnt(x)
  43420. #endif
  43421. /*
  43422. ** For every Btree that in database connection db which
  43423. ** has been modified, "trip" or invalidate each cursor in
  43424. ** that Btree might have been modified so that the cursor
  43425. ** can never be used again. This happens when a rollback
  43426. *** occurs. We have to trip all the other cursors, even
  43427. ** cursor from other VMs in different database connections,
  43428. ** so that none of them try to use the data at which they
  43429. ** were pointing and which now may have been changed due
  43430. ** to the rollback.
  43431. **
  43432. ** Remember that a rollback can delete tables complete and
  43433. ** reorder rootpages. So it is not sufficient just to save
  43434. ** the state of the cursor. We have to invalidate the cursor
  43435. ** so that it is never used again.
  43436. */
  43437. static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
  43438. int i;
  43439. for(i=0; i<db->nDb; i++){
  43440. Btree *p = db->aDb[i].pBt;
  43441. if( p && sqlite3BtreeIsInTrans(p) ){
  43442. sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
  43443. }
  43444. }
  43445. }
  43446. /*
  43447. ** This routine is called the when a VDBE tries to halt. If the VDBE
  43448. ** has made changes and is in autocommit mode, then commit those
  43449. ** changes. If a rollback is needed, then do the rollback.
  43450. **
  43451. ** This routine is the only way to move the state of a VM from
  43452. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  43453. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  43454. **
  43455. ** Return an error code. If the commit could not complete because of
  43456. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  43457. ** means the close did not happen and needs to be repeated.
  43458. */
  43459. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  43460. sqlite3 *db = p->db;
  43461. int i;
  43462. int (*xFunc)(Btree *pBt) = 0; /* Function to call on each btree backend */
  43463. int isSpecialError; /* Set to true if SQLITE_NOMEM or IOERR */
  43464. /* This function contains the logic that determines if a statement or
  43465. ** transaction will be committed or rolled back as a result of the
  43466. ** execution of this virtual machine.
  43467. **
  43468. ** If any of the following errors occur:
  43469. **
  43470. ** SQLITE_NOMEM
  43471. ** SQLITE_IOERR
  43472. ** SQLITE_FULL
  43473. ** SQLITE_INTERRUPT
  43474. **
  43475. ** Then the internal cache might have been left in an inconsistent
  43476. ** state. We need to rollback the statement transaction, if there is
  43477. ** one, or the complete transaction if there is no statement transaction.
  43478. */
  43479. if( p->db->mallocFailed ){
  43480. p->rc = SQLITE_NOMEM;
  43481. }
  43482. closeAllCursorsExceptActiveVtabs(p);
  43483. if( p->magic!=VDBE_MAGIC_RUN ){
  43484. return SQLITE_OK;
  43485. }
  43486. checkActiveVdbeCnt(db);
  43487. /* No commit or rollback needed if the program never started */
  43488. if( p->pc>=0 ){
  43489. int mrc; /* Primary error code from p->rc */
  43490. /* Lock all btrees used by the statement */
  43491. sqlite3BtreeMutexArrayEnter(&p->aMutex);
  43492. /* Check for one of the special errors */
  43493. mrc = p->rc & 0xff;
  43494. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  43495. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  43496. if( isSpecialError ){
  43497. /* If the query was read-only, we need do no rollback at all. Otherwise,
  43498. ** proceed with the special handling.
  43499. */
  43500. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  43501. if( p->rc==SQLITE_IOERR_BLOCKED && p->usesStmtJournal ){
  43502. xFunc = sqlite3BtreeRollbackStmt;
  43503. p->rc = SQLITE_BUSY;
  43504. }else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL)
  43505. && p->usesStmtJournal ){
  43506. xFunc = sqlite3BtreeRollbackStmt;
  43507. }else{
  43508. /* We are forced to roll back the active transaction. Before doing
  43509. ** so, abort any other statements this handle currently has active.
  43510. */
  43511. invalidateCursorsOnModifiedBtrees(db);
  43512. sqlite3RollbackAll(db);
  43513. sqlite3CloseSavepoints(db);
  43514. db->autoCommit = 1;
  43515. }
  43516. }
  43517. }
  43518. /* If the auto-commit flag is set and this is the only active vdbe, then
  43519. ** we do either a commit or rollback of the current transaction.
  43520. **
  43521. ** Note: This block also runs if one of the special errors handled
  43522. ** above has occurred.
  43523. */
  43524. if( !sqlite3VtabInSync(db)
  43525. && db->autoCommit
  43526. && db->writeVdbeCnt==(p->readOnly==0)
  43527. && (db->flags & SQLITE_CommitBusy)==0
  43528. ){
  43529. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  43530. /* The auto-commit flag is true, and the vdbe program was
  43531. ** successful or hit an 'OR FAIL' constraint. This means a commit
  43532. ** is required.
  43533. */
  43534. int rc = vdbeCommit(db, p);
  43535. if( rc==SQLITE_BUSY ){
  43536. sqlite3BtreeMutexArrayLeave(&p->aMutex);
  43537. return SQLITE_BUSY;
  43538. }else if( rc!=SQLITE_OK ){
  43539. p->rc = rc;
  43540. sqlite3RollbackAll(db);
  43541. }else{
  43542. sqlite3CommitInternalChanges(db);
  43543. }
  43544. }else{
  43545. sqlite3RollbackAll(db);
  43546. }
  43547. }else if( !xFunc ){
  43548. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  43549. if( p->openedStatement ){
  43550. xFunc = sqlite3BtreeCommitStmt;
  43551. }
  43552. }else if( p->errorAction==OE_Abort ){
  43553. xFunc = sqlite3BtreeRollbackStmt;
  43554. }else{
  43555. invalidateCursorsOnModifiedBtrees(db);
  43556. sqlite3RollbackAll(db);
  43557. sqlite3CloseSavepoints(db);
  43558. db->autoCommit = 1;
  43559. }
  43560. }
  43561. /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
  43562. ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
  43563. ** and the return code is still SQLITE_OK, set the return code to the new
  43564. ** error value.
  43565. */
  43566. assert(!xFunc ||
  43567. xFunc==sqlite3BtreeCommitStmt ||
  43568. xFunc==sqlite3BtreeRollbackStmt
  43569. );
  43570. for(i=0; xFunc && i<db->nDb; i++){
  43571. int rc;
  43572. Btree *pBt = db->aDb[i].pBt;
  43573. if( pBt ){
  43574. rc = xFunc(pBt);
  43575. if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
  43576. p->rc = rc;
  43577. sqlite3DbFree(db, p->zErrMsg);
  43578. p->zErrMsg = 0;
  43579. }
  43580. }
  43581. }
  43582. /* If this was an INSERT, UPDATE or DELETE and the statement was committed,
  43583. ** set the change counter.
  43584. */
  43585. if( p->changeCntOn && p->pc>=0 ){
  43586. if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
  43587. sqlite3VdbeSetChanges(db, p->nChange);
  43588. }else{
  43589. sqlite3VdbeSetChanges(db, 0);
  43590. }
  43591. p->nChange = 0;
  43592. }
  43593. /* Rollback or commit any schema changes that occurred. */
  43594. if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
  43595. sqlite3ResetInternalSchema(db, 0);
  43596. db->flags = (db->flags | SQLITE_InternChanges);
  43597. }
  43598. /* Release the locks */
  43599. sqlite3BtreeMutexArrayLeave(&p->aMutex);
  43600. }
  43601. /* We have successfully halted and closed the VM. Record this fact. */
  43602. if( p->pc>=0 ){
  43603. db->activeVdbeCnt--;
  43604. if( !p->readOnly ){
  43605. db->writeVdbeCnt--;
  43606. }
  43607. assert( db->activeVdbeCnt>=db->writeVdbeCnt );
  43608. }
  43609. p->magic = VDBE_MAGIC_HALT;
  43610. checkActiveVdbeCnt(db);
  43611. if( p->db->mallocFailed ){
  43612. p->rc = SQLITE_NOMEM;
  43613. }
  43614. return SQLITE_OK;
  43615. }
  43616. /*
  43617. ** Each VDBE holds the result of the most recent sqlite3_step() call
  43618. ** in p->rc. This routine sets that result back to SQLITE_OK.
  43619. */
  43620. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  43621. p->rc = SQLITE_OK;
  43622. }
  43623. /*
  43624. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  43625. ** Write any error messages into *pzErrMsg. Return the result code.
  43626. **
  43627. ** After this routine is run, the VDBE should be ready to be executed
  43628. ** again.
  43629. **
  43630. ** To look at it another way, this routine resets the state of the
  43631. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  43632. ** VDBE_MAGIC_INIT.
  43633. */
  43634. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  43635. sqlite3 *db;
  43636. db = p->db;
  43637. /* If the VM did not run to completion or if it encountered an
  43638. ** error, then it might not have been halted properly. So halt
  43639. ** it now.
  43640. */
  43641. (void)sqlite3SafetyOn(db);
  43642. sqlite3VdbeHalt(p);
  43643. (void)sqlite3SafetyOff(db);
  43644. /* If the VDBE has be run even partially, then transfer the error code
  43645. ** and error message from the VDBE into the main database structure. But
  43646. ** if the VDBE has just been set to run but has not actually executed any
  43647. ** instructions yet, leave the main database error information unchanged.
  43648. */
  43649. if( p->pc>=0 ){
  43650. if( p->zErrMsg ){
  43651. sqlite3BeginBenignMalloc();
  43652. sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
  43653. sqlite3EndBenignMalloc();
  43654. db->errCode = p->rc;
  43655. sqlite3DbFree(db, p->zErrMsg);
  43656. p->zErrMsg = 0;
  43657. }else if( p->rc ){
  43658. sqlite3Error(db, p->rc, 0);
  43659. }else{
  43660. sqlite3Error(db, SQLITE_OK, 0);
  43661. }
  43662. }else if( p->rc && p->expired ){
  43663. /* The expired flag was set on the VDBE before the first call
  43664. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  43665. ** called), set the database error in this case as well.
  43666. */
  43667. sqlite3Error(db, p->rc, 0);
  43668. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  43669. sqlite3DbFree(db, p->zErrMsg);
  43670. p->zErrMsg = 0;
  43671. }
  43672. /* Reclaim all memory used by the VDBE
  43673. */
  43674. Cleanup(p);
  43675. /* Save profiling information from this VDBE run.
  43676. */
  43677. #ifdef VDBE_PROFILE
  43678. {
  43679. FILE *out = fopen("vdbe_profile.out", "a");
  43680. if( out ){
  43681. int i;
  43682. fprintf(out, "---- ");
  43683. for(i=0; i<p->nOp; i++){
  43684. fprintf(out, "%02x", p->aOp[i].opcode);
  43685. }
  43686. fprintf(out, "\n");
  43687. for(i=0; i<p->nOp; i++){
  43688. fprintf(out, "%6d %10lld %8lld ",
  43689. p->aOp[i].cnt,
  43690. p->aOp[i].cycles,
  43691. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  43692. );
  43693. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  43694. }
  43695. fclose(out);
  43696. }
  43697. }
  43698. #endif
  43699. p->magic = VDBE_MAGIC_INIT;
  43700. return p->rc & db->errMask;
  43701. }
  43702. /*
  43703. ** Clean up and delete a VDBE after execution. Return an integer which is
  43704. ** the result code. Write any error message text into *pzErrMsg.
  43705. */
  43706. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  43707. int rc = SQLITE_OK;
  43708. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  43709. rc = sqlite3VdbeReset(p);
  43710. assert( (rc & p->db->errMask)==rc );
  43711. }else if( p->magic!=VDBE_MAGIC_INIT ){
  43712. return SQLITE_MISUSE;
  43713. }
  43714. sqlite3VdbeDelete(p);
  43715. return rc;
  43716. }
  43717. /*
  43718. ** Call the destructor for each auxdata entry in pVdbeFunc for which
  43719. ** the corresponding bit in mask is clear. Auxdata entries beyond 31
  43720. ** are always destroyed. To destroy all auxdata entries, call this
  43721. ** routine with mask==0.
  43722. */
  43723. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
  43724. int i;
  43725. for(i=0; i<pVdbeFunc->nAux; i++){
  43726. struct AuxData *pAux = &pVdbeFunc->apAux[i];
  43727. if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
  43728. if( pAux->xDelete ){
  43729. pAux->xDelete(pAux->pAux);
  43730. }
  43731. pAux->pAux = 0;
  43732. }
  43733. }
  43734. }
  43735. /*
  43736. ** Delete an entire VDBE.
  43737. */
  43738. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  43739. int i;
  43740. sqlite3 *db;
  43741. if( p==0 ) return;
  43742. db = p->db;
  43743. if( p->pPrev ){
  43744. p->pPrev->pNext = p->pNext;
  43745. }else{
  43746. assert( db->pVdbe==p );
  43747. db->pVdbe = p->pNext;
  43748. }
  43749. if( p->pNext ){
  43750. p->pNext->pPrev = p->pPrev;
  43751. }
  43752. if( p->aOp ){
  43753. Op *pOp = p->aOp;
  43754. for(i=0; i<p->nOp; i++, pOp++){
  43755. freeP4(db, pOp->p4type, pOp->p4.p);
  43756. #ifdef SQLITE_DEBUG
  43757. sqlite3DbFree(db, pOp->zComment);
  43758. #endif
  43759. }
  43760. sqlite3DbFree(db, p->aOp);
  43761. }
  43762. releaseMemArray(p->aVar, p->nVar);
  43763. sqlite3DbFree(db, p->aLabel);
  43764. if( p->aMem ){
  43765. sqlite3DbFree(db, &p->aMem[1]);
  43766. }
  43767. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  43768. sqlite3DbFree(db, p->aColName);
  43769. sqlite3DbFree(db, p->zSql);
  43770. p->magic = VDBE_MAGIC_DEAD;
  43771. sqlite3DbFree(db, p);
  43772. }
  43773. /*
  43774. ** If a MoveTo operation is pending on the given cursor, then do that
  43775. ** MoveTo now. Return an error code. If no MoveTo is pending, this
  43776. ** routine does nothing and returns SQLITE_OK.
  43777. */
  43778. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  43779. if( p->deferredMoveto ){
  43780. int res, rc;
  43781. #ifdef SQLITE_TEST
  43782. extern int sqlite3_search_count;
  43783. #endif
  43784. assert( p->isTable );
  43785. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  43786. if( rc ) return rc;
  43787. p->lastRowid = keyToInt(p->movetoTarget);
  43788. p->rowidIsValid = res==0 ?1:0;
  43789. if( res<0 ){
  43790. rc = sqlite3BtreeNext(p->pCursor, &res);
  43791. if( rc ) return rc;
  43792. }
  43793. #ifdef SQLITE_TEST
  43794. sqlite3_search_count++;
  43795. #endif
  43796. p->deferredMoveto = 0;
  43797. p->cacheStatus = CACHE_STALE;
  43798. }else if( p->pCursor ){
  43799. int hasMoved;
  43800. int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
  43801. if( rc ) return rc;
  43802. if( hasMoved ){
  43803. p->cacheStatus = CACHE_STALE;
  43804. p->nullRow = 1;
  43805. }
  43806. }
  43807. return SQLITE_OK;
  43808. }
  43809. /*
  43810. ** The following functions:
  43811. **
  43812. ** sqlite3VdbeSerialType()
  43813. ** sqlite3VdbeSerialTypeLen()
  43814. ** sqlite3VdbeSerialLen()
  43815. ** sqlite3VdbeSerialPut()
  43816. ** sqlite3VdbeSerialGet()
  43817. **
  43818. ** encapsulate the code that serializes values for storage in SQLite
  43819. ** data and index records. Each serialized value consists of a
  43820. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  43821. ** integer, stored as a varint.
  43822. **
  43823. ** In an SQLite index record, the serial type is stored directly before
  43824. ** the blob of data that it corresponds to. In a table record, all serial
  43825. ** types are stored at the start of the record, and the blobs of data at
  43826. ** the end. Hence these functions allow the caller to handle the
  43827. ** serial-type and data blob seperately.
  43828. **
  43829. ** The following table describes the various storage classes for data:
  43830. **
  43831. ** serial type bytes of data type
  43832. ** -------------- --------------- ---------------
  43833. ** 0 0 NULL
  43834. ** 1 1 signed integer
  43835. ** 2 2 signed integer
  43836. ** 3 3 signed integer
  43837. ** 4 4 signed integer
  43838. ** 5 6 signed integer
  43839. ** 6 8 signed integer
  43840. ** 7 8 IEEE float
  43841. ** 8 0 Integer constant 0
  43842. ** 9 0 Integer constant 1
  43843. ** 10,11 reserved for expansion
  43844. ** N>=12 and even (N-12)/2 BLOB
  43845. ** N>=13 and odd (N-13)/2 text
  43846. **
  43847. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  43848. ** of SQLite will not understand those serial types.
  43849. */
  43850. /*
  43851. ** Return the serial-type for the value stored in pMem.
  43852. */
  43853. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  43854. int flags = pMem->flags;
  43855. int n;
  43856. if( flags&MEM_Null ){
  43857. return 0;
  43858. }
  43859. if( flags&MEM_Int ){
  43860. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  43861. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  43862. i64 i = pMem->u.i;
  43863. u64 u;
  43864. if( file_format>=4 && (i&1)==i ){
  43865. return 8+(u32)i;
  43866. }
  43867. u = i<0 ? -i : i;
  43868. if( u<=127 ) return 1;
  43869. if( u<=32767 ) return 2;
  43870. if( u<=8388607 ) return 3;
  43871. if( u<=2147483647 ) return 4;
  43872. if( u<=MAX_6BYTE ) return 5;
  43873. return 6;
  43874. }
  43875. if( flags&MEM_Real ){
  43876. return 7;
  43877. }
  43878. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  43879. n = pMem->n;
  43880. if( flags & MEM_Zero ){
  43881. n += pMem->u.nZero;
  43882. }
  43883. assert( n>=0 );
  43884. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  43885. }
  43886. /*
  43887. ** Return the length of the data corresponding to the supplied serial-type.
  43888. */
  43889. SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
  43890. if( serial_type>=12 ){
  43891. return (serial_type-12)/2;
  43892. }else{
  43893. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  43894. return aSize[serial_type];
  43895. }
  43896. }
  43897. /*
  43898. ** If we are on an architecture with mixed-endian floating
  43899. ** points (ex: ARM7) then swap the lower 4 bytes with the
  43900. ** upper 4 bytes. Return the result.
  43901. **
  43902. ** For most architectures, this is a no-op.
  43903. **
  43904. ** (later): It is reported to me that the mixed-endian problem
  43905. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  43906. ** that early versions of GCC stored the two words of a 64-bit
  43907. ** float in the wrong order. And that error has been propagated
  43908. ** ever since. The blame is not necessarily with GCC, though.
  43909. ** GCC might have just copying the problem from a prior compiler.
  43910. ** I am also told that newer versions of GCC that follow a different
  43911. ** ABI get the byte order right.
  43912. **
  43913. ** Developers using SQLite on an ARM7 should compile and run their
  43914. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  43915. ** enabled, some asserts below will ensure that the byte order of
  43916. ** floating point values is correct.
  43917. **
  43918. ** (2007-08-30) Frank van Vugt has studied this problem closely
  43919. ** and has send his findings to the SQLite developers. Frank
  43920. ** writes that some Linux kernels offer floating point hardware
  43921. ** emulation that uses only 32-bit mantissas instead of a full
  43922. ** 48-bits as required by the IEEE standard. (This is the
  43923. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  43924. ** byte swapping becomes very complicated. To avoid problems,
  43925. ** the necessary byte swapping is carried out using a 64-bit integer
  43926. ** rather than a 64-bit float. Frank assures us that the code here
  43927. ** works for him. We, the developers, have no way to independently
  43928. ** verify this, but Frank seems to know what he is talking about
  43929. ** so we trust him.
  43930. */
  43931. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  43932. static u64 floatSwap(u64 in){
  43933. union {
  43934. u64 r;
  43935. u32 i[2];
  43936. } u;
  43937. u32 t;
  43938. u.r = in;
  43939. t = u.i[0];
  43940. u.i[0] = u.i[1];
  43941. u.i[1] = t;
  43942. return u.r;
  43943. }
  43944. # define swapMixedEndianFloat(X) X = floatSwap(X)
  43945. #else
  43946. # define swapMixedEndianFloat(X)
  43947. #endif
  43948. /*
  43949. ** Write the serialized data blob for the value stored in pMem into
  43950. ** buf. It is assumed that the caller has allocated sufficient space.
  43951. ** Return the number of bytes written.
  43952. **
  43953. ** nBuf is the amount of space left in buf[]. nBuf must always be
  43954. ** large enough to hold the entire field. Except, if the field is
  43955. ** a blob with a zero-filled tail, then buf[] might be just the right
  43956. ** size to hold everything except for the zero-filled tail. If buf[]
  43957. ** is only big enough to hold the non-zero prefix, then only write that
  43958. ** prefix into buf[]. But if buf[] is large enough to hold both the
  43959. ** prefix and the tail then write the prefix and set the tail to all
  43960. ** zeros.
  43961. **
  43962. ** Return the number of bytes actually written into buf[]. The number
  43963. ** of bytes in the zero-filled tail is included in the return value only
  43964. ** if those bytes were zeroed in buf[].
  43965. */
  43966. SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  43967. u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  43968. int len;
  43969. /* Integer and Real */
  43970. if( serial_type<=7 && serial_type>0 ){
  43971. u64 v;
  43972. int i;
  43973. if( serial_type==7 ){
  43974. assert( sizeof(v)==sizeof(pMem->r) );
  43975. memcpy(&v, &pMem->r, sizeof(v));
  43976. swapMixedEndianFloat(v);
  43977. }else{
  43978. v = pMem->u.i;
  43979. }
  43980. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  43981. assert( len<=nBuf );
  43982. while( i-- ){
  43983. buf[i] = (u8)(v&0xFF);
  43984. v >>= 8;
  43985. }
  43986. return len;
  43987. }
  43988. /* String or blob */
  43989. if( serial_type>=12 ){
  43990. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  43991. == sqlite3VdbeSerialTypeLen(serial_type) );
  43992. assert( pMem->n<=nBuf );
  43993. len = pMem->n;
  43994. memcpy(buf, pMem->z, len);
  43995. if( pMem->flags & MEM_Zero ){
  43996. len += pMem->u.nZero;
  43997. if( len>nBuf ){
  43998. len = nBuf;
  43999. }
  44000. memset(&buf[pMem->n], 0, len-pMem->n);
  44001. }
  44002. return len;
  44003. }
  44004. /* NULL or constants 0 or 1 */
  44005. return 0;
  44006. }
  44007. /*
  44008. ** Deserialize the data blob pointed to by buf as serial type serial_type
  44009. ** and store the result in pMem. Return the number of bytes read.
  44010. */
  44011. SQLITE_PRIVATE int sqlite3VdbeSerialGet(
  44012. const unsigned char *buf, /* Buffer to deserialize from */
  44013. u32 serial_type, /* Serial type to deserialize */
  44014. Mem *pMem /* Memory cell to write value into */
  44015. ){
  44016. switch( serial_type ){
  44017. case 10: /* Reserved for future use */
  44018. case 11: /* Reserved for future use */
  44019. case 0: { /* NULL */
  44020. pMem->flags = MEM_Null;
  44021. break;
  44022. }
  44023. case 1: { /* 1-byte signed integer */
  44024. pMem->u.i = (signed char)buf[0];
  44025. pMem->flags = MEM_Int;
  44026. return 1;
  44027. }
  44028. case 2: { /* 2-byte signed integer */
  44029. pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  44030. pMem->flags = MEM_Int;
  44031. return 2;
  44032. }
  44033. case 3: { /* 3-byte signed integer */
  44034. pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  44035. pMem->flags = MEM_Int;
  44036. return 3;
  44037. }
  44038. case 4: { /* 4-byte signed integer */
  44039. pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  44040. pMem->flags = MEM_Int;
  44041. return 4;
  44042. }
  44043. case 5: { /* 6-byte signed integer */
  44044. u64 x = (((signed char)buf[0])<<8) | buf[1];
  44045. u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  44046. x = (x<<32) | y;
  44047. pMem->u.i = *(i64*)&x;
  44048. pMem->flags = MEM_Int;
  44049. return 6;
  44050. }
  44051. case 6: /* 8-byte signed integer */
  44052. case 7: { /* IEEE floating point */
  44053. u64 x;
  44054. u32 y;
  44055. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  44056. /* Verify that integers and floating point values use the same
  44057. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  44058. ** defined that 64-bit floating point values really are mixed
  44059. ** endian.
  44060. */
  44061. static const u64 t1 = ((u64)0x3ff00000)<<32;
  44062. static const double r1 = 1.0;
  44063. u64 t2 = t1;
  44064. swapMixedEndianFloat(t2);
  44065. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  44066. #endif
  44067. x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  44068. y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  44069. x = (x<<32) | y;
  44070. if( serial_type==6 ){
  44071. pMem->u.i = *(i64*)&x;
  44072. pMem->flags = MEM_Int;
  44073. }else{
  44074. assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  44075. swapMixedEndianFloat(x);
  44076. memcpy(&pMem->r, &x, sizeof(x));
  44077. pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
  44078. }
  44079. return 8;
  44080. }
  44081. case 8: /* Integer 0 */
  44082. case 9: { /* Integer 1 */
  44083. pMem->u.i = serial_type-8;
  44084. pMem->flags = MEM_Int;
  44085. return 0;
  44086. }
  44087. default: {
  44088. int len = (serial_type-12)/2;
  44089. pMem->z = (char *)buf;
  44090. pMem->n = len;
  44091. pMem->xDel = 0;
  44092. if( serial_type&0x01 ){
  44093. pMem->flags = MEM_Str | MEM_Ephem;
  44094. }else{
  44095. pMem->flags = MEM_Blob | MEM_Ephem;
  44096. }
  44097. return len;
  44098. }
  44099. }
  44100. return 0;
  44101. }
  44102. /*
  44103. ** Given the nKey-byte encoding of a record in pKey[], parse the
  44104. ** record into a UnpackedRecord structure. Return a pointer to
  44105. ** that structure.
  44106. **
  44107. ** The calling function might provide szSpace bytes of memory
  44108. ** space at pSpace. This space can be used to hold the returned
  44109. ** VDbeParsedRecord structure if it is large enough. If it is
  44110. ** not big enough, space is obtained from sqlite3_malloc().
  44111. **
  44112. ** The returned structure should be closed by a call to
  44113. ** sqlite3VdbeDeleteUnpackedRecord().
  44114. */
  44115. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
  44116. KeyInfo *pKeyInfo, /* Information about the record format */
  44117. int nKey, /* Size of the binary record */
  44118. const void *pKey, /* The binary record */
  44119. UnpackedRecord *pSpace,/* Space available to hold resulting object */
  44120. int szSpace /* Size of pSpace[] in bytes */
  44121. ){
  44122. const unsigned char *aKey = (const unsigned char *)pKey;
  44123. UnpackedRecord *p;
  44124. int nByte, d;
  44125. u32 idx;
  44126. u16 u; /* Unsigned loop counter */
  44127. u32 szHdr;
  44128. Mem *pMem;
  44129. assert( sizeof(Mem)>sizeof(*p) );
  44130. nByte = sizeof(Mem)*(pKeyInfo->nField+2);
  44131. if( nByte>szSpace ){
  44132. p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  44133. if( p==0 ) return 0;
  44134. p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
  44135. }else{
  44136. p = pSpace;
  44137. p->flags = UNPACKED_NEED_DESTROY;
  44138. }
  44139. p->pKeyInfo = pKeyInfo;
  44140. p->nField = pKeyInfo->nField + 1;
  44141. p->aMem = pMem = &((Mem*)p)[1];
  44142. idx = getVarint32(aKey, szHdr);
  44143. d = szHdr;
  44144. u = 0;
  44145. while( idx<szHdr && u<p->nField ){
  44146. u32 serial_type;
  44147. idx += getVarint32(&aKey[idx], serial_type);
  44148. if( d>=nKey && sqlite3VdbeSerialTypeLen(serial_type)>0 ) break;
  44149. pMem->enc = pKeyInfo->enc;
  44150. pMem->db = pKeyInfo->db;
  44151. pMem->flags = 0;
  44152. pMem->zMalloc = 0;
  44153. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  44154. pMem++;
  44155. u++;
  44156. }
  44157. assert( u<=pKeyInfo->nField + 1 );
  44158. p->nField = u;
  44159. return (void*)p;
  44160. }
  44161. /*
  44162. ** This routine destroys a UnpackedRecord object
  44163. */
  44164. SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
  44165. if( p ){
  44166. if( p->flags & UNPACKED_NEED_DESTROY ){
  44167. int i;
  44168. Mem *pMem;
  44169. for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
  44170. if( pMem->zMalloc ){
  44171. sqlite3VdbeMemRelease(pMem);
  44172. }
  44173. }
  44174. }
  44175. if( p->flags & UNPACKED_NEED_FREE ){
  44176. sqlite3DbFree(p->pKeyInfo->db, p);
  44177. }
  44178. }
  44179. }
  44180. /*
  44181. ** This function compares the two table rows or index records
  44182. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  44183. ** or positive integer if key1 is less than, equal to or
  44184. ** greater than key2. The {nKey1, pKey1} key must be a blob
  44185. ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
  44186. ** key must be a parsed key such as obtained from
  44187. ** sqlite3VdbeParseRecord.
  44188. **
  44189. ** Key1 and Key2 do not have to contain the same number of fields.
  44190. ** The key with fewer fields is usually compares less than the
  44191. ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
  44192. ** and the common prefixes are equal, then key1 is less than key2.
  44193. ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  44194. ** equal, then the keys are considered to be equal and
  44195. ** the parts beyond the common prefix are ignored.
  44196. **
  44197. ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
  44198. ** the header of pKey1 is ignored. It is assumed that pKey1 is
  44199. ** an index key, and thus ends with a rowid value. The last byte
  44200. ** of the header will therefore be the serial type of the rowid:
  44201. ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
  44202. ** The serial type of the final rowid will always be a single byte.
  44203. ** By ignoring this last byte of the header, we force the comparison
  44204. ** to ignore the rowid at the end of key1.
  44205. */
  44206. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  44207. int nKey1, const void *pKey1, /* Left key */
  44208. UnpackedRecord *pPKey2 /* Right key */
  44209. ){
  44210. int d1; /* Offset into aKey[] of next data element */
  44211. u32 idx1; /* Offset into aKey[] of next header element */
  44212. u32 szHdr1; /* Number of bytes in header */
  44213. int i = 0;
  44214. int nField;
  44215. int rc = 0;
  44216. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  44217. KeyInfo *pKeyInfo;
  44218. Mem mem1;
  44219. pKeyInfo = pPKey2->pKeyInfo;
  44220. mem1.enc = pKeyInfo->enc;
  44221. mem1.db = pKeyInfo->db;
  44222. mem1.flags = 0;
  44223. mem1.zMalloc = 0;
  44224. idx1 = getVarint32(aKey1, szHdr1);
  44225. d1 = szHdr1;
  44226. if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
  44227. szHdr1--;
  44228. }
  44229. nField = pKeyInfo->nField;
  44230. while( idx1<szHdr1 && i<pPKey2->nField ){
  44231. u32 serial_type1;
  44232. /* Read the serial types for the next element in each key. */
  44233. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  44234. if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
  44235. /* Extract the values to be compared.
  44236. */
  44237. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  44238. /* Do the comparison
  44239. */
  44240. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
  44241. i<nField ? pKeyInfo->aColl[i] : 0);
  44242. if( rc!=0 ){
  44243. break;
  44244. }
  44245. i++;
  44246. }
  44247. if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
  44248. if( rc==0 ){
  44249. /* rc==0 here means that one of the keys ran out of fields and
  44250. ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  44251. ** flag is set, then break the tie by treating key2 as larger.
  44252. ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  44253. ** are considered to be equal. Otherwise, the longer key is the
  44254. ** larger. As it happens, the pPKey2 will always be the longer
  44255. ** if there is a difference.
  44256. */
  44257. if( pPKey2->flags & UNPACKED_INCRKEY ){
  44258. rc = -1;
  44259. }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  44260. /* Leave rc==0 */
  44261. }else if( idx1<szHdr1 ){
  44262. rc = 1;
  44263. }
  44264. }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
  44265. && pKeyInfo->aSortOrder[i] ){
  44266. rc = -rc;
  44267. }
  44268. return rc;
  44269. }
  44270. /*
  44271. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  44272. ** Read the rowid (the last field in the record) and store it in *rowid.
  44273. ** Return SQLITE_OK if everything works, or an error code otherwise.
  44274. **
  44275. ** pCur might be pointing to text obtained from a corrupt database file.
  44276. ** So the content cannot be trusted. Do appropriate checks on the content.
  44277. */
  44278. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
  44279. i64 nCellKey = 0;
  44280. int rc;
  44281. u32 szHdr; /* Size of the header */
  44282. u32 typeRowid; /* Serial type of the rowid */
  44283. u32 lenRowid; /* Size of the rowid */
  44284. Mem m, v;
  44285. /* Get the size of the index entry. Only indices entries of less
  44286. ** than 2GiB are support - anything large must be database corruption */
  44287. sqlite3BtreeKeySize(pCur, &nCellKey);
  44288. if( unlikely(nCellKey<=0 || nCellKey>0x7fffffff) ){
  44289. return SQLITE_CORRUPT_BKPT;
  44290. }
  44291. /* Read in the complete content of the index entry */
  44292. m.flags = 0;
  44293. m.db = 0;
  44294. m.zMalloc = 0;
  44295. rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  44296. if( rc ){
  44297. return rc;
  44298. }
  44299. /* The index entry must begin with a header size */
  44300. (void)getVarint32((u8*)m.z, szHdr);
  44301. testcase( szHdr==2 );
  44302. testcase( szHdr==m.n );
  44303. if( unlikely(szHdr<2 || (int)szHdr>m.n) ){
  44304. goto idx_rowid_corruption;
  44305. }
  44306. /* The last field of the index should be an integer - the ROWID.
  44307. ** Verify that the last entry really is an integer. */
  44308. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  44309. testcase( typeRowid==1 );
  44310. testcase( typeRowid==2 );
  44311. testcase( typeRowid==3 );
  44312. testcase( typeRowid==4 );
  44313. testcase( typeRowid==5 );
  44314. testcase( typeRowid==6 );
  44315. testcase( typeRowid==8 );
  44316. testcase( typeRowid==9 );
  44317. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  44318. goto idx_rowid_corruption;
  44319. }
  44320. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  44321. testcase( m.n-lenRowid==szHdr );
  44322. if( unlikely(m.n-lenRowid<szHdr) ){
  44323. goto idx_rowid_corruption;
  44324. }
  44325. /* Fetch the integer off the end of the index record */
  44326. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  44327. *rowid = v.u.i;
  44328. sqlite3VdbeMemRelease(&m);
  44329. return SQLITE_OK;
  44330. /* Jump here if database corruption is detected after m has been
  44331. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  44332. idx_rowid_corruption:
  44333. testcase( m.zMalloc!=0 );
  44334. sqlite3VdbeMemRelease(&m);
  44335. return SQLITE_CORRUPT_BKPT;
  44336. }
  44337. /*
  44338. ** Compare the key of the index entry that cursor pC is point to against
  44339. ** the key string in pKey (of length nKey). Write into *pRes a number
  44340. ** that is negative, zero, or positive if pC is less than, equal to,
  44341. ** or greater than pKey. Return SQLITE_OK on success.
  44342. **
  44343. ** pKey is either created without a rowid or is truncated so that it
  44344. ** omits the rowid at the end. The rowid at the end of the index entry
  44345. ** is ignored as well. Hence, this routine only compares the prefixes
  44346. ** of the keys prior to the final rowid, not the entire key.
  44347. **
  44348. ** pUnpacked may be an unpacked version of pKey,nKey. If pUnpacked is
  44349. ** supplied it is used in place of pKey,nKey.
  44350. */
  44351. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  44352. VdbeCursor *pC, /* The cursor to compare against */
  44353. UnpackedRecord *pUnpacked, /* Unpacked version of pKey and nKey */
  44354. int *res /* Write the comparison result here */
  44355. ){
  44356. i64 nCellKey = 0;
  44357. int rc;
  44358. BtCursor *pCur = pC->pCursor;
  44359. Mem m;
  44360. sqlite3BtreeKeySize(pCur, &nCellKey);
  44361. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  44362. *res = 0;
  44363. return SQLITE_OK;
  44364. }
  44365. m.db = 0;
  44366. m.flags = 0;
  44367. m.zMalloc = 0;
  44368. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  44369. if( rc ){
  44370. return rc;
  44371. }
  44372. assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
  44373. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  44374. sqlite3VdbeMemRelease(&m);
  44375. return SQLITE_OK;
  44376. }
  44377. /*
  44378. ** This routine sets the value to be returned by subsequent calls to
  44379. ** sqlite3_changes() on the database handle 'db'.
  44380. */
  44381. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  44382. assert( sqlite3_mutex_held(db->mutex) );
  44383. db->nChange = nChange;
  44384. db->nTotalChange += nChange;
  44385. }
  44386. /*
  44387. ** Set a flag in the vdbe to update the change counter when it is finalised
  44388. ** or reset.
  44389. */
  44390. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  44391. v->changeCntOn = 1;
  44392. }
  44393. /*
  44394. ** Mark every prepared statement associated with a database connection
  44395. ** as expired.
  44396. **
  44397. ** An expired statement means that recompilation of the statement is
  44398. ** recommend. Statements expire when things happen that make their
  44399. ** programs obsolete. Removing user-defined functions or collating
  44400. ** sequences, or changing an authorization function are the types of
  44401. ** things that make prepared statements obsolete.
  44402. */
  44403. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  44404. Vdbe *p;
  44405. for(p = db->pVdbe; p; p=p->pNext){
  44406. p->expired = 1;
  44407. }
  44408. }
  44409. /*
  44410. ** Return the database associated with the Vdbe.
  44411. */
  44412. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  44413. return v->db;
  44414. }
  44415. /************** End of vdbeaux.c *********************************************/
  44416. /************** Begin file vdbeapi.c *****************************************/
  44417. /*
  44418. ** 2004 May 26
  44419. **
  44420. ** The author disclaims copyright to this source code. In place of
  44421. ** a legal notice, here is a blessing:
  44422. **
  44423. ** May you do good and not evil.
  44424. ** May you find forgiveness for yourself and forgive others.
  44425. ** May you share freely, never taking more than you give.
  44426. **
  44427. *************************************************************************
  44428. **
  44429. ** This file contains code use to implement APIs that are part of the
  44430. ** VDBE.
  44431. **
  44432. ** $Id: vdbeapi.c,v 1.150 2008/12/10 18:03:47 drh Exp $
  44433. */
  44434. #if 0 && defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  44435. /*
  44436. ** The following structure contains pointers to the end points of a
  44437. ** doubly-linked list of all compiled SQL statements that may be holding
  44438. ** buffers eligible for release when the sqlite3_release_memory() interface is
  44439. ** invoked. Access to this list is protected by the SQLITE_MUTEX_STATIC_LRU2
  44440. ** mutex.
  44441. **
  44442. ** Statements are added to the end of this list when sqlite3_reset() is
  44443. ** called. They are removed either when sqlite3_step() or sqlite3_finalize()
  44444. ** is called. When statements are added to this list, the associated
  44445. ** register array (p->aMem[1..p->nMem]) may contain dynamic buffers that
  44446. ** can be freed using sqlite3VdbeReleaseMemory().
  44447. **
  44448. ** When statements are added or removed from this list, the mutex
  44449. ** associated with the Vdbe being added or removed (Vdbe.db->mutex) is
  44450. ** already held. The LRU2 mutex is then obtained, blocking if necessary,
  44451. ** the linked-list pointers manipulated and the LRU2 mutex relinquished.
  44452. */
  44453. struct StatementLruList {
  44454. Vdbe *pFirst;
  44455. Vdbe *pLast;
  44456. };
  44457. static struct StatementLruList sqlite3LruStatements;
  44458. /*
  44459. ** Check that the list looks to be internally consistent. This is used
  44460. ** as part of an assert() statement as follows:
  44461. **
  44462. ** assert( stmtLruCheck() );
  44463. */
  44464. #ifndef NDEBUG
  44465. static int stmtLruCheck(){
  44466. Vdbe *p;
  44467. for(p=sqlite3LruStatements.pFirst; p; p=p->pLruNext){
  44468. assert(p->pLruNext || p==sqlite3LruStatements.pLast);
  44469. assert(!p->pLruNext || p->pLruNext->pLruPrev==p);
  44470. assert(p->pLruPrev || p==sqlite3LruStatements.pFirst);
  44471. assert(!p->pLruPrev || p->pLruPrev->pLruNext==p);
  44472. }
  44473. return 1;
  44474. }
  44475. #endif
  44476. /*
  44477. ** Add vdbe p to the end of the statement lru list. It is assumed that
  44478. ** p is not already part of the list when this is called. The lru list
  44479. ** is protected by the SQLITE_MUTEX_STATIC_LRU mutex.
  44480. */
  44481. static void stmtLruAdd(Vdbe *p){
  44482. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  44483. if( p->pLruPrev || p->pLruNext || sqlite3LruStatements.pFirst==p ){
  44484. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  44485. return;
  44486. }
  44487. assert( stmtLruCheck() );
  44488. if( !sqlite3LruStatements.pFirst ){
  44489. assert( !sqlite3LruStatements.pLast );
  44490. sqlite3LruStatements.pFirst = p;
  44491. sqlite3LruStatements.pLast = p;
  44492. }else{
  44493. assert( !sqlite3LruStatements.pLast->pLruNext );
  44494. p->pLruPrev = sqlite3LruStatements.pLast;
  44495. sqlite3LruStatements.pLast->pLruNext = p;
  44496. sqlite3LruStatements.pLast = p;
  44497. }
  44498. assert( stmtLruCheck() );
  44499. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  44500. }
  44501. /*
  44502. ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is already held, remove
  44503. ** statement p from the least-recently-used statement list. If the
  44504. ** statement is not currently part of the list, this call is a no-op.
  44505. */
  44506. static void stmtLruRemoveNomutex(Vdbe *p){
  44507. if( p->pLruPrev || p->pLruNext || p==sqlite3LruStatements.pFirst ){
  44508. assert( stmtLruCheck() );
  44509. if( p->pLruNext ){
  44510. p->pLruNext->pLruPrev = p->pLruPrev;
  44511. }else{
  44512. sqlite3LruStatements.pLast = p->pLruPrev;
  44513. }
  44514. if( p->pLruPrev ){
  44515. p->pLruPrev->pLruNext = p->pLruNext;
  44516. }else{
  44517. sqlite3LruStatements.pFirst = p->pLruNext;
  44518. }
  44519. p->pLruNext = 0;
  44520. p->pLruPrev = 0;
  44521. assert( stmtLruCheck() );
  44522. }
  44523. }
  44524. /*
  44525. ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is not held, remove
  44526. ** statement p from the least-recently-used statement list. If the
  44527. ** statement is not currently part of the list, this call is a no-op.
  44528. */
  44529. static void stmtLruRemove(Vdbe *p){
  44530. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  44531. stmtLruRemoveNomutex(p);
  44532. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  44533. }
  44534. /*
  44535. ** Try to release n bytes of memory by freeing buffers associated
  44536. ** with the memory registers of currently unused vdbes.
  44537. */
  44538. SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int n){
  44539. Vdbe *p;
  44540. Vdbe *pNext;
  44541. int nFree = 0;
  44542. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  44543. for(p=sqlite3LruStatements.pFirst; p && nFree<n; p=pNext){
  44544. pNext = p->pLruNext;
  44545. /* For each statement handle in the lru list, attempt to obtain the
  44546. ** associated database mutex. If it cannot be obtained, continue
  44547. ** to the next statement handle. It is not possible to block on
  44548. ** the database mutex - that could cause deadlock.
  44549. */
  44550. if( SQLITE_OK==sqlite3_mutex_try(p->db->mutex) ){
  44551. nFree += sqlite3VdbeReleaseBuffers(p);
  44552. stmtLruRemoveNomutex(p);
  44553. sqlite3_mutex_leave(p->db->mutex);
  44554. }
  44555. }
  44556. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  44557. return nFree;
  44558. }
  44559. /*
  44560. ** Call sqlite3Reprepare() on the statement. Remove it from the
  44561. ** lru list before doing so, as Reprepare() will free all the
  44562. ** memory register buffers anyway.
  44563. */
  44564. int vdbeReprepare(Vdbe *p){
  44565. stmtLruRemove(p);
  44566. return sqlite3Reprepare(p);
  44567. }
  44568. #else /* !SQLITE_ENABLE_MEMORY_MANAGEMENT */
  44569. #define stmtLruRemove(x)
  44570. #define stmtLruAdd(x)
  44571. #define vdbeReprepare(x) sqlite3Reprepare(x)
  44572. #endif
  44573. #ifndef SQLITE_OMIT_DEPRECATED
  44574. /*
  44575. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  44576. ** to be recompiled. A statement needs to be recompiled whenever the
  44577. ** execution environment changes in a way that would alter the program
  44578. ** that sqlite3_prepare() generates. For example, if new functions or
  44579. ** collating sequences are registered or if an authorizer function is
  44580. ** added or changed.
  44581. */
  44582. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  44583. Vdbe *p = (Vdbe*)pStmt;
  44584. return p==0 || p->expired;
  44585. }
  44586. #endif
  44587. /*
  44588. ** The following routine destroys a virtual machine that is created by
  44589. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  44590. ** success/failure code that describes the result of executing the virtual
  44591. ** machine.
  44592. **
  44593. ** This routine sets the error code and string returned by
  44594. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  44595. */
  44596. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  44597. int rc;
  44598. if( pStmt==0 ){
  44599. rc = SQLITE_OK;
  44600. }else{
  44601. Vdbe *v = (Vdbe*)pStmt;
  44602. #if SQLITE_THREADSAFE
  44603. sqlite3_mutex *mutex = v->db->mutex;
  44604. #endif
  44605. sqlite3_mutex_enter(mutex);
  44606. stmtLruRemove(v);
  44607. rc = sqlite3VdbeFinalize(v);
  44608. sqlite3_mutex_leave(mutex);
  44609. }
  44610. return rc;
  44611. }
  44612. /*
  44613. ** Terminate the current execution of an SQL statement and reset it
  44614. ** back to its starting state so that it can be reused. A success code from
  44615. ** the prior execution is returned.
  44616. **
  44617. ** This routine sets the error code and string returned by
  44618. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  44619. */
  44620. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  44621. int rc;
  44622. if( pStmt==0 ){
  44623. rc = SQLITE_OK;
  44624. }else{
  44625. Vdbe *v = (Vdbe*)pStmt;
  44626. sqlite3_mutex_enter(v->db->mutex);
  44627. rc = sqlite3VdbeReset(v);
  44628. stmtLruAdd(v);
  44629. sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
  44630. assert( (rc & (v->db->errMask))==rc );
  44631. sqlite3_mutex_leave(v->db->mutex);
  44632. }
  44633. return rc;
  44634. }
  44635. /*
  44636. ** Set all the parameters in the compiled SQL statement to NULL.
  44637. */
  44638. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  44639. int i;
  44640. int rc = SQLITE_OK;
  44641. Vdbe *p = (Vdbe*)pStmt;
  44642. #if SQLITE_THREADSAFE
  44643. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  44644. #endif
  44645. sqlite3_mutex_enter(mutex);
  44646. for(i=0; i<p->nVar; i++){
  44647. sqlite3VdbeMemRelease(&p->aVar[i]);
  44648. p->aVar[i].flags = MEM_Null;
  44649. }
  44650. sqlite3_mutex_leave(mutex);
  44651. return rc;
  44652. }
  44653. /**************************** sqlite3_value_ *******************************
  44654. ** The following routines extract information from a Mem or sqlite3_value
  44655. ** structure.
  44656. */
  44657. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  44658. Mem *p = (Mem*)pVal;
  44659. if( p->flags & (MEM_Blob|MEM_Str) ){
  44660. sqlite3VdbeMemExpandBlob(p);
  44661. p->flags &= ~MEM_Str;
  44662. p->flags |= MEM_Blob;
  44663. return p->z;
  44664. }else{
  44665. return sqlite3_value_text(pVal);
  44666. }
  44667. }
  44668. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  44669. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  44670. }
  44671. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  44672. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  44673. }
  44674. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  44675. return sqlite3VdbeRealValue((Mem*)pVal);
  44676. }
  44677. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  44678. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  44679. }
  44680. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  44681. return sqlite3VdbeIntValue((Mem*)pVal);
  44682. }
  44683. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  44684. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  44685. }
  44686. #ifndef SQLITE_OMIT_UTF16
  44687. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  44688. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  44689. }
  44690. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  44691. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  44692. }
  44693. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  44694. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  44695. }
  44696. #endif /* SQLITE_OMIT_UTF16 */
  44697. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  44698. return pVal->type;
  44699. }
  44700. /**************************** sqlite3_result_ *******************************
  44701. ** The following routines are used by user-defined functions to specify
  44702. ** the function result.
  44703. */
  44704. SQLITE_API void sqlite3_result_blob(
  44705. sqlite3_context *pCtx,
  44706. const void *z,
  44707. int n,
  44708. void (*xDel)(void *)
  44709. ){
  44710. assert( n>=0 );
  44711. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44712. sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
  44713. }
  44714. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  44715. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44716. sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
  44717. }
  44718. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  44719. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44720. pCtx->isError = SQLITE_ERROR;
  44721. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  44722. }
  44723. #ifndef SQLITE_OMIT_UTF16
  44724. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  44725. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44726. pCtx->isError = SQLITE_ERROR;
  44727. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  44728. }
  44729. #endif
  44730. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  44731. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44732. sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
  44733. }
  44734. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  44735. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44736. sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
  44737. }
  44738. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  44739. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44740. sqlite3VdbeMemSetNull(&pCtx->s);
  44741. }
  44742. SQLITE_API void sqlite3_result_text(
  44743. sqlite3_context *pCtx,
  44744. const char *z,
  44745. int n,
  44746. void (*xDel)(void *)
  44747. ){
  44748. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44749. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
  44750. }
  44751. #ifndef SQLITE_OMIT_UTF16
  44752. SQLITE_API void sqlite3_result_text16(
  44753. sqlite3_context *pCtx,
  44754. const void *z,
  44755. int n,
  44756. void (*xDel)(void *)
  44757. ){
  44758. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44759. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
  44760. }
  44761. SQLITE_API void sqlite3_result_text16be(
  44762. sqlite3_context *pCtx,
  44763. const void *z,
  44764. int n,
  44765. void (*xDel)(void *)
  44766. ){
  44767. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44768. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
  44769. }
  44770. SQLITE_API void sqlite3_result_text16le(
  44771. sqlite3_context *pCtx,
  44772. const void *z,
  44773. int n,
  44774. void (*xDel)(void *)
  44775. ){
  44776. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44777. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
  44778. }
  44779. #endif /* SQLITE_OMIT_UTF16 */
  44780. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  44781. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44782. sqlite3VdbeMemCopy(&pCtx->s, pValue);
  44783. }
  44784. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  44785. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44786. sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
  44787. }
  44788. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  44789. pCtx->isError = errCode;
  44790. }
  44791. /* Force an SQLITE_TOOBIG error. */
  44792. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  44793. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44794. pCtx->isError = SQLITE_TOOBIG;
  44795. sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
  44796. SQLITE_UTF8, SQLITE_STATIC);
  44797. }
  44798. /* An SQLITE_NOMEM error. */
  44799. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  44800. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  44801. sqlite3VdbeMemSetNull(&pCtx->s);
  44802. pCtx->isError = SQLITE_NOMEM;
  44803. pCtx->s.db->mallocFailed = 1;
  44804. }
  44805. /*
  44806. ** Execute the statement pStmt, either until a row of data is ready, the
  44807. ** statement is completely executed or an error occurs.
  44808. **
  44809. ** This routine implements the bulk of the logic behind the sqlite_step()
  44810. ** API. The only thing omitted is the automatic recompile if a
  44811. ** schema change has occurred. That detail is handled by the
  44812. ** outer sqlite3_step() wrapper procedure.
  44813. */
  44814. static int sqlite3Step(Vdbe *p){
  44815. sqlite3 *db;
  44816. int rc;
  44817. assert(p);
  44818. if( p->magic!=VDBE_MAGIC_RUN ){
  44819. return SQLITE_MISUSE;
  44820. }
  44821. /* Assert that malloc() has not failed */
  44822. db = p->db;
  44823. if( db->mallocFailed ){
  44824. return SQLITE_NOMEM;
  44825. }
  44826. if( p->pc<=0 && p->expired ){
  44827. if( p->rc==SQLITE_OK ){
  44828. p->rc = SQLITE_SCHEMA;
  44829. }
  44830. rc = SQLITE_ERROR;
  44831. goto end_of_step;
  44832. }
  44833. if( sqlite3SafetyOn(db) ){
  44834. p->rc = SQLITE_MISUSE;
  44835. return SQLITE_MISUSE;
  44836. }
  44837. if( p->pc<0 ){
  44838. /* If there are no other statements currently running, then
  44839. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  44840. ** from interrupting a statement that has not yet started.
  44841. */
  44842. if( db->activeVdbeCnt==0 ){
  44843. db->u1.isInterrupted = 0;
  44844. }
  44845. #ifndef SQLITE_OMIT_TRACE
  44846. if( db->xProfile && !db->init.busy ){
  44847. double rNow;
  44848. sqlite3OsCurrentTime(db->pVfs, &rNow);
  44849. p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
  44850. }
  44851. #endif
  44852. db->activeVdbeCnt++;
  44853. if( p->readOnly==0 ) db->writeVdbeCnt++;
  44854. p->pc = 0;
  44855. stmtLruRemove(p);
  44856. }
  44857. #ifndef SQLITE_OMIT_EXPLAIN
  44858. if( p->explain ){
  44859. rc = sqlite3VdbeList(p);
  44860. }else
  44861. #endif /* SQLITE_OMIT_EXPLAIN */
  44862. {
  44863. rc = sqlite3VdbeExec(p);
  44864. }
  44865. if( sqlite3SafetyOff(db) ){
  44866. rc = SQLITE_MISUSE;
  44867. }
  44868. #ifndef SQLITE_OMIT_TRACE
  44869. /* Invoke the profile callback if there is one
  44870. */
  44871. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->nOp>0
  44872. && p->aOp[0].opcode==OP_Trace && p->aOp[0].p4.z!=0 ){
  44873. double rNow;
  44874. u64 elapseTime;
  44875. sqlite3OsCurrentTime(db->pVfs, &rNow);
  44876. elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
  44877. elapseTime -= p->startTime;
  44878. db->xProfile(db->pProfileArg, p->aOp[0].p4.z, elapseTime);
  44879. }
  44880. #endif
  44881. db->errCode = rc;
  44882. /*sqlite3Error(p->db, rc, 0);*/
  44883. p->rc = sqlite3ApiExit(p->db, p->rc);
  44884. end_of_step:
  44885. assert( (rc&0xff)==rc );
  44886. if( p->zSql && (rc&0xff)<SQLITE_ROW ){
  44887. /* This behavior occurs if sqlite3_prepare_v2() was used to build
  44888. ** the prepared statement. Return error codes directly */
  44889. p->db->errCode = p->rc;
  44890. /* sqlite3Error(p->db, p->rc, 0); */
  44891. return p->rc;
  44892. }else{
  44893. /* This is for legacy sqlite3_prepare() builds and when the code
  44894. ** is SQLITE_ROW or SQLITE_DONE */
  44895. return rc;
  44896. }
  44897. }
  44898. /*
  44899. ** This is the top-level implementation of sqlite3_step(). Call
  44900. ** sqlite3Step() to do most of the work. If a schema error occurs,
  44901. ** call sqlite3Reprepare() and try again.
  44902. */
  44903. #ifdef SQLITE_OMIT_PARSER
  44904. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  44905. int rc = SQLITE_MISUSE;
  44906. if( pStmt ){
  44907. Vdbe *v;
  44908. v = (Vdbe*)pStmt;
  44909. sqlite3_mutex_enter(v->db->mutex);
  44910. rc = sqlite3Step(v);
  44911. sqlite3_mutex_leave(v->db->mutex);
  44912. }
  44913. return rc;
  44914. }
  44915. #else
  44916. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  44917. int rc = SQLITE_MISUSE;
  44918. if( pStmt ){
  44919. int cnt = 0;
  44920. Vdbe *v = (Vdbe*)pStmt;
  44921. sqlite3 *db = v->db;
  44922. sqlite3_mutex_enter(db->mutex);
  44923. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  44924. && cnt++ < 5
  44925. && vdbeReprepare(v) ){
  44926. sqlite3_reset(pStmt);
  44927. v->expired = 0;
  44928. }
  44929. if( rc==SQLITE_SCHEMA && v->zSql && db->pErr ){
  44930. /* This case occurs after failing to recompile an sql statement.
  44931. ** The error message from the SQL compiler has already been loaded
  44932. ** into the database handle. This block copies the error message
  44933. ** from the database handle into the statement and sets the statement
  44934. ** program counter to 0 to ensure that when the statement is
  44935. ** finalized or reset the parser error message is available via
  44936. ** sqlite3_errmsg() and sqlite3_errcode().
  44937. */
  44938. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  44939. sqlite3DbFree(db, v->zErrMsg);
  44940. if( !db->mallocFailed ){
  44941. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  44942. } else {
  44943. v->zErrMsg = 0;
  44944. v->rc = SQLITE_NOMEM;
  44945. }
  44946. }
  44947. rc = sqlite3ApiExit(db, rc);
  44948. sqlite3_mutex_leave(db->mutex);
  44949. }
  44950. return rc;
  44951. }
  44952. #endif
  44953. /*
  44954. ** Extract the user data from a sqlite3_context structure and return a
  44955. ** pointer to it.
  44956. */
  44957. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  44958. assert( p && p->pFunc );
  44959. return p->pFunc->pUserData;
  44960. }
  44961. /*
  44962. ** Extract the user data from a sqlite3_context structure and return a
  44963. ** pointer to it.
  44964. */
  44965. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  44966. assert( p && p->pFunc );
  44967. return p->s.db;
  44968. }
  44969. /*
  44970. ** The following is the implementation of an SQL function that always
  44971. ** fails with an error message stating that the function is used in the
  44972. ** wrong context. The sqlite3_overload_function() API might construct
  44973. ** SQL function that use this routine so that the functions will exist
  44974. ** for name resolution but are actually overloaded by the xFindFunction
  44975. ** method of virtual tables.
  44976. */
  44977. SQLITE_PRIVATE void sqlite3InvalidFunction(
  44978. sqlite3_context *context, /* The function calling context */
  44979. int NotUsed, /* Number of arguments to the function */
  44980. sqlite3_value **NotUsed2 /* Value of each argument */
  44981. ){
  44982. const char *zName = context->pFunc->zName;
  44983. char *zErr;
  44984. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  44985. zErr = sqlite3MPrintf(0,
  44986. "unable to use function %s in the requested context", zName);
  44987. sqlite3_result_error(context, zErr, -1);
  44988. sqlite3_free(zErr);
  44989. }
  44990. /*
  44991. ** Allocate or return the aggregate context for a user function. A new
  44992. ** context is allocated on the first call. Subsequent calls return the
  44993. ** same context that was returned on prior calls.
  44994. */
  44995. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  44996. Mem *pMem;
  44997. assert( p && p->pFunc && p->pFunc->xStep );
  44998. assert( sqlite3_mutex_held(p->s.db->mutex) );
  44999. pMem = p->pMem;
  45000. if( (pMem->flags & MEM_Agg)==0 ){
  45001. if( nByte==0 ){
  45002. sqlite3VdbeMemReleaseExternal(pMem);
  45003. pMem->flags = MEM_Null;
  45004. pMem->z = 0;
  45005. }else{
  45006. sqlite3VdbeMemGrow(pMem, nByte, 0);
  45007. pMem->flags = MEM_Agg;
  45008. pMem->u.pDef = p->pFunc;
  45009. if( pMem->z ){
  45010. memset(pMem->z, 0, nByte);
  45011. }
  45012. }
  45013. }
  45014. return (void*)pMem->z;
  45015. }
  45016. /*
  45017. ** Return the auxilary data pointer, if any, for the iArg'th argument to
  45018. ** the user-function defined by pCtx.
  45019. */
  45020. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  45021. VdbeFunc *pVdbeFunc;
  45022. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45023. pVdbeFunc = pCtx->pVdbeFunc;
  45024. if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
  45025. return 0;
  45026. }
  45027. return pVdbeFunc->apAux[iArg].pAux;
  45028. }
  45029. /*
  45030. ** Set the auxilary data pointer and delete function, for the iArg'th
  45031. ** argument to the user-function defined by pCtx. Any previous value is
  45032. ** deleted by calling the delete function specified when it was set.
  45033. */
  45034. SQLITE_API void sqlite3_set_auxdata(
  45035. sqlite3_context *pCtx,
  45036. int iArg,
  45037. void *pAux,
  45038. void (*xDelete)(void*)
  45039. ){
  45040. struct AuxData *pAuxData;
  45041. VdbeFunc *pVdbeFunc;
  45042. if( iArg<0 ) goto failed;
  45043. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45044. pVdbeFunc = pCtx->pVdbeFunc;
  45045. if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
  45046. int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
  45047. int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
  45048. pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
  45049. if( !pVdbeFunc ){
  45050. goto failed;
  45051. }
  45052. pCtx->pVdbeFunc = pVdbeFunc;
  45053. memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
  45054. pVdbeFunc->nAux = iArg+1;
  45055. pVdbeFunc->pFunc = pCtx->pFunc;
  45056. }
  45057. pAuxData = &pVdbeFunc->apAux[iArg];
  45058. if( pAuxData->pAux && pAuxData->xDelete ){
  45059. pAuxData->xDelete(pAuxData->pAux);
  45060. }
  45061. pAuxData->pAux = pAux;
  45062. pAuxData->xDelete = xDelete;
  45063. return;
  45064. failed:
  45065. if( xDelete ){
  45066. xDelete(pAux);
  45067. }
  45068. }
  45069. #ifndef SQLITE_OMIT_DEPRECATED
  45070. /*
  45071. ** Return the number of times the Step function of a aggregate has been
  45072. ** called.
  45073. **
  45074. ** This function is deprecated. Do not use it for new code. It is
  45075. ** provide only to avoid breaking legacy code. New aggregate function
  45076. ** implementations should keep their own counts within their aggregate
  45077. ** context.
  45078. */
  45079. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  45080. assert( p && p->pFunc && p->pFunc->xStep );
  45081. return p->pMem->n;
  45082. }
  45083. #endif
  45084. /*
  45085. ** Return the number of columns in the result set for the statement pStmt.
  45086. */
  45087. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  45088. Vdbe *pVm = (Vdbe *)pStmt;
  45089. return pVm ? pVm->nResColumn : 0;
  45090. }
  45091. /*
  45092. ** Return the number of values available from the current row of the
  45093. ** currently executing statement pStmt.
  45094. */
  45095. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  45096. Vdbe *pVm = (Vdbe *)pStmt;
  45097. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  45098. return pVm->nResColumn;
  45099. }
  45100. /*
  45101. ** Check to see if column iCol of the given statement is valid. If
  45102. ** it is, return a pointer to the Mem for the value of that column.
  45103. ** If iCol is not valid, return a pointer to a Mem which has a value
  45104. ** of NULL.
  45105. */
  45106. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  45107. Vdbe *pVm;
  45108. int vals;
  45109. Mem *pOut;
  45110. pVm = (Vdbe *)pStmt;
  45111. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  45112. sqlite3_mutex_enter(pVm->db->mutex);
  45113. vals = sqlite3_data_count(pStmt);
  45114. pOut = &pVm->pResultSet[i];
  45115. }else{
  45116. static const Mem nullMem = {{0}, 0.0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
  45117. if( pVm->db ){
  45118. sqlite3_mutex_enter(pVm->db->mutex);
  45119. sqlite3Error(pVm->db, SQLITE_RANGE, 0);
  45120. }
  45121. pOut = (Mem*)&nullMem;
  45122. }
  45123. return pOut;
  45124. }
  45125. /*
  45126. ** This function is called after invoking an sqlite3_value_XXX function on a
  45127. ** column value (i.e. a value returned by evaluating an SQL expression in the
  45128. ** select list of a SELECT statement) that may cause a malloc() failure. If
  45129. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  45130. ** code of statement pStmt set to SQLITE_NOMEM.
  45131. **
  45132. ** Specifically, this is called from within:
  45133. **
  45134. ** sqlite3_column_int()
  45135. ** sqlite3_column_int64()
  45136. ** sqlite3_column_text()
  45137. ** sqlite3_column_text16()
  45138. ** sqlite3_column_real()
  45139. ** sqlite3_column_bytes()
  45140. ** sqlite3_column_bytes16()
  45141. **
  45142. ** But not for sqlite3_column_blob(), which never calls malloc().
  45143. */
  45144. static void columnMallocFailure(sqlite3_stmt *pStmt)
  45145. {
  45146. /* If malloc() failed during an encoding conversion within an
  45147. ** sqlite3_column_XXX API, then set the return code of the statement to
  45148. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  45149. ** and _finalize() will return NOMEM.
  45150. */
  45151. Vdbe *p = (Vdbe *)pStmt;
  45152. if( p ){
  45153. p->rc = sqlite3ApiExit(p->db, p->rc);
  45154. sqlite3_mutex_leave(p->db->mutex);
  45155. }
  45156. }
  45157. /**************************** sqlite3_column_ *******************************
  45158. ** The following routines are used to access elements of the current row
  45159. ** in the result set.
  45160. */
  45161. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  45162. const void *val;
  45163. val = sqlite3_value_blob( columnMem(pStmt,i) );
  45164. /* Even though there is no encoding conversion, value_blob() might
  45165. ** need to call malloc() to expand the result of a zeroblob()
  45166. ** expression.
  45167. */
  45168. columnMallocFailure(pStmt);
  45169. return val;
  45170. }
  45171. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  45172. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  45173. columnMallocFailure(pStmt);
  45174. return val;
  45175. }
  45176. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  45177. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  45178. columnMallocFailure(pStmt);
  45179. return val;
  45180. }
  45181. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  45182. double val = sqlite3_value_double( columnMem(pStmt,i) );
  45183. columnMallocFailure(pStmt);
  45184. return val;
  45185. }
  45186. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  45187. int val = sqlite3_value_int( columnMem(pStmt,i) );
  45188. columnMallocFailure(pStmt);
  45189. return val;
  45190. }
  45191. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  45192. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  45193. columnMallocFailure(pStmt);
  45194. return val;
  45195. }
  45196. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  45197. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  45198. columnMallocFailure(pStmt);
  45199. return val;
  45200. }
  45201. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  45202. Mem *pOut = columnMem(pStmt, i);
  45203. if( pOut->flags&MEM_Static ){
  45204. pOut->flags &= ~MEM_Static;
  45205. pOut->flags |= MEM_Ephem;
  45206. }
  45207. columnMallocFailure(pStmt);
  45208. return (sqlite3_value *)pOut;
  45209. }
  45210. #ifndef SQLITE_OMIT_UTF16
  45211. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  45212. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  45213. columnMallocFailure(pStmt);
  45214. return val;
  45215. }
  45216. #endif /* SQLITE_OMIT_UTF16 */
  45217. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  45218. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  45219. columnMallocFailure(pStmt);
  45220. return iType;
  45221. }
  45222. /* The following function is experimental and subject to change or
  45223. ** removal */
  45224. /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
  45225. ** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
  45226. **}
  45227. */
  45228. /*
  45229. ** Convert the N-th element of pStmt->pColName[] into a string using
  45230. ** xFunc() then return that string. If N is out of range, return 0.
  45231. **
  45232. ** There are up to 5 names for each column. useType determines which
  45233. ** name is returned. Here are the names:
  45234. **
  45235. ** 0 The column name as it should be displayed for output
  45236. ** 1 The datatype name for the column
  45237. ** 2 The name of the database that the column derives from
  45238. ** 3 The name of the table that the column derives from
  45239. ** 4 The name of the table column that the result column derives from
  45240. **
  45241. ** If the result is not a simple column reference (if it is an expression
  45242. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  45243. */
  45244. static const void *columnName(
  45245. sqlite3_stmt *pStmt,
  45246. int N,
  45247. const void *(*xFunc)(Mem*),
  45248. int useType
  45249. ){
  45250. const void *ret = 0;
  45251. Vdbe *p = (Vdbe *)pStmt;
  45252. int n;
  45253. if( p!=0 ){
  45254. n = sqlite3_column_count(pStmt);
  45255. if( N<n && N>=0 ){
  45256. N += useType*n;
  45257. sqlite3_mutex_enter(p->db->mutex);
  45258. ret = xFunc(&p->aColName[N]);
  45259. /* A malloc may have failed inside of the xFunc() call. If this
  45260. ** is the case, clear the mallocFailed flag and return NULL.
  45261. */
  45262. if( p->db && p->db->mallocFailed ){
  45263. p->db->mallocFailed = 0;
  45264. ret = 0;
  45265. }
  45266. sqlite3_mutex_leave(p->db->mutex);
  45267. }
  45268. }
  45269. return ret;
  45270. }
  45271. /*
  45272. ** Return the name of the Nth column of the result set returned by SQL
  45273. ** statement pStmt.
  45274. */
  45275. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  45276. return columnName(
  45277. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  45278. }
  45279. #ifndef SQLITE_OMIT_UTF16
  45280. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  45281. return columnName(
  45282. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  45283. }
  45284. #endif
  45285. /*
  45286. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  45287. ** not define OMIT_DECLTYPE.
  45288. */
  45289. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  45290. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  45291. and SQLITE_ENABLE_COLUMN_METADATA"
  45292. #endif
  45293. #ifndef SQLITE_OMIT_DECLTYPE
  45294. /*
  45295. ** Return the column declaration type (if applicable) of the 'i'th column
  45296. ** of the result set of SQL statement pStmt.
  45297. */
  45298. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  45299. return columnName(
  45300. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  45301. }
  45302. #ifndef SQLITE_OMIT_UTF16
  45303. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  45304. return columnName(
  45305. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  45306. }
  45307. #endif /* SQLITE_OMIT_UTF16 */
  45308. #endif /* SQLITE_OMIT_DECLTYPE */
  45309. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  45310. /*
  45311. ** Return the name of the database from which a result column derives.
  45312. ** NULL is returned if the result column is an expression or constant or
  45313. ** anything else which is not an unabiguous reference to a database column.
  45314. */
  45315. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  45316. return columnName(
  45317. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  45318. }
  45319. #ifndef SQLITE_OMIT_UTF16
  45320. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  45321. return columnName(
  45322. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  45323. }
  45324. #endif /* SQLITE_OMIT_UTF16 */
  45325. /*
  45326. ** Return the name of the table from which a result column derives.
  45327. ** NULL is returned if the result column is an expression or constant or
  45328. ** anything else which is not an unabiguous reference to a database column.
  45329. */
  45330. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  45331. return columnName(
  45332. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  45333. }
  45334. #ifndef SQLITE_OMIT_UTF16
  45335. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  45336. return columnName(
  45337. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  45338. }
  45339. #endif /* SQLITE_OMIT_UTF16 */
  45340. /*
  45341. ** Return the name of the table column from which a result column derives.
  45342. ** NULL is returned if the result column is an expression or constant or
  45343. ** anything else which is not an unabiguous reference to a database column.
  45344. */
  45345. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  45346. return columnName(
  45347. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  45348. }
  45349. #ifndef SQLITE_OMIT_UTF16
  45350. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  45351. return columnName(
  45352. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  45353. }
  45354. #endif /* SQLITE_OMIT_UTF16 */
  45355. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  45356. /******************************* sqlite3_bind_ ***************************
  45357. **
  45358. ** Routines used to attach values to wildcards in a compiled SQL statement.
  45359. */
  45360. /*
  45361. ** Unbind the value bound to variable i in virtual machine p. This is the
  45362. ** the same as binding a NULL value to the column. If the "i" parameter is
  45363. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  45364. **
  45365. ** A successful evaluation of this routine acquires the mutex on p.
  45366. ** the mutex is released if any kind of error occurs.
  45367. **
  45368. ** The error code stored in database p->db is overwritten with the return
  45369. ** value in any case.
  45370. */
  45371. static int vdbeUnbind(Vdbe *p, int i){
  45372. Mem *pVar;
  45373. if( p==0 ) return SQLITE_MISUSE;
  45374. sqlite3_mutex_enter(p->db->mutex);
  45375. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  45376. sqlite3Error(p->db, SQLITE_MISUSE, 0);
  45377. sqlite3_mutex_leave(p->db->mutex);
  45378. return SQLITE_MISUSE;
  45379. }
  45380. if( i<1 || i>p->nVar ){
  45381. sqlite3Error(p->db, SQLITE_RANGE, 0);
  45382. sqlite3_mutex_leave(p->db->mutex);
  45383. return SQLITE_RANGE;
  45384. }
  45385. i--;
  45386. pVar = &p->aVar[i];
  45387. sqlite3VdbeMemRelease(pVar);
  45388. pVar->flags = MEM_Null;
  45389. sqlite3Error(p->db, SQLITE_OK, 0);
  45390. return SQLITE_OK;
  45391. }
  45392. /*
  45393. ** Bind a text or BLOB value.
  45394. */
  45395. static int bindText(
  45396. sqlite3_stmt *pStmt, /* The statement to bind against */
  45397. int i, /* Index of the parameter to bind */
  45398. const void *zData, /* Pointer to the data to be bound */
  45399. int nData, /* Number of bytes of data to be bound */
  45400. void (*xDel)(void*), /* Destructor for the data */
  45401. u8 encoding /* Encoding for the data */
  45402. ){
  45403. Vdbe *p = (Vdbe *)pStmt;
  45404. Mem *pVar;
  45405. int rc;
  45406. rc = vdbeUnbind(p, i);
  45407. if( rc==SQLITE_OK ){
  45408. if( zData!=0 ){
  45409. pVar = &p->aVar[i-1];
  45410. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  45411. if( rc==SQLITE_OK && encoding!=0 ){
  45412. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  45413. }
  45414. sqlite3Error(p->db, rc, 0);
  45415. rc = sqlite3ApiExit(p->db, rc);
  45416. }
  45417. sqlite3_mutex_leave(p->db->mutex);
  45418. }
  45419. return rc;
  45420. }
  45421. /*
  45422. ** Bind a blob value to an SQL statement variable.
  45423. */
  45424. SQLITE_API int sqlite3_bind_blob(
  45425. sqlite3_stmt *pStmt,
  45426. int i,
  45427. const void *zData,
  45428. int nData,
  45429. void (*xDel)(void*)
  45430. ){
  45431. return bindText(pStmt, i, zData, nData, xDel, 0);
  45432. }
  45433. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  45434. int rc;
  45435. Vdbe *p = (Vdbe *)pStmt;
  45436. rc = vdbeUnbind(p, i);
  45437. if( rc==SQLITE_OK ){
  45438. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  45439. sqlite3_mutex_leave(p->db->mutex);
  45440. }
  45441. return rc;
  45442. }
  45443. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  45444. return sqlite3_bind_int64(p, i, (i64)iValue);
  45445. }
  45446. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  45447. int rc;
  45448. Vdbe *p = (Vdbe *)pStmt;
  45449. rc = vdbeUnbind(p, i);
  45450. if( rc==SQLITE_OK ){
  45451. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  45452. sqlite3_mutex_leave(p->db->mutex);
  45453. }
  45454. return rc;
  45455. }
  45456. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  45457. int rc;
  45458. Vdbe *p = (Vdbe*)pStmt;
  45459. rc = vdbeUnbind(p, i);
  45460. if( rc==SQLITE_OK ){
  45461. sqlite3_mutex_leave(p->db->mutex);
  45462. }
  45463. return rc;
  45464. }
  45465. SQLITE_API int sqlite3_bind_text(
  45466. sqlite3_stmt *pStmt,
  45467. int i,
  45468. const char *zData,
  45469. int nData,
  45470. void (*xDel)(void*)
  45471. ){
  45472. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  45473. }
  45474. #ifndef SQLITE_OMIT_UTF16
  45475. SQLITE_API int sqlite3_bind_text16(
  45476. sqlite3_stmt *pStmt,
  45477. int i,
  45478. const void *zData,
  45479. int nData,
  45480. void (*xDel)(void*)
  45481. ){
  45482. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  45483. }
  45484. #endif /* SQLITE_OMIT_UTF16 */
  45485. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  45486. int rc;
  45487. Vdbe *p = (Vdbe *)pStmt;
  45488. rc = vdbeUnbind(p, i);
  45489. if( rc==SQLITE_OK ){
  45490. rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
  45491. if( rc==SQLITE_OK ){
  45492. rc = sqlite3VdbeChangeEncoding(&p->aVar[i-1], ENC(p->db));
  45493. }
  45494. sqlite3_mutex_leave(p->db->mutex);
  45495. }
  45496. rc = sqlite3ApiExit(p->db, rc);
  45497. return rc;
  45498. }
  45499. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  45500. int rc;
  45501. Vdbe *p = (Vdbe *)pStmt;
  45502. rc = vdbeUnbind(p, i);
  45503. if( rc==SQLITE_OK ){
  45504. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  45505. sqlite3_mutex_leave(p->db->mutex);
  45506. }
  45507. return rc;
  45508. }
  45509. /*
  45510. ** Return the number of wildcards that can be potentially bound to.
  45511. ** This routine is added to support DBD::SQLite.
  45512. */
  45513. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  45514. Vdbe *p = (Vdbe*)pStmt;
  45515. return p ? p->nVar : 0;
  45516. }
  45517. /*
  45518. ** Create a mapping from variable numbers to variable names
  45519. ** in the Vdbe.azVar[] array, if such a mapping does not already
  45520. ** exist.
  45521. */
  45522. static void createVarMap(Vdbe *p){
  45523. if( !p->okVar ){
  45524. sqlite3_mutex_enter(p->db->mutex);
  45525. if( !p->okVar ){
  45526. int j;
  45527. Op *pOp;
  45528. for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
  45529. if( pOp->opcode==OP_Variable ){
  45530. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  45531. p->azVar[pOp->p1-1] = pOp->p4.z;
  45532. }
  45533. }
  45534. p->okVar = 1;
  45535. }
  45536. sqlite3_mutex_leave(p->db->mutex);
  45537. }
  45538. }
  45539. /*
  45540. ** Return the name of a wildcard parameter. Return NULL if the index
  45541. ** is out of range or if the wildcard is unnamed.
  45542. **
  45543. ** The result is always UTF-8.
  45544. */
  45545. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  45546. Vdbe *p = (Vdbe*)pStmt;
  45547. if( p==0 || i<1 || i>p->nVar ){
  45548. return 0;
  45549. }
  45550. createVarMap(p);
  45551. return p->azVar[i-1];
  45552. }
  45553. /*
  45554. ** Given a wildcard parameter name, return the index of the variable
  45555. ** with that name. If there is no variable with the given name,
  45556. ** return 0.
  45557. */
  45558. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  45559. Vdbe *p = (Vdbe*)pStmt;
  45560. int i;
  45561. if( p==0 ){
  45562. return 0;
  45563. }
  45564. createVarMap(p);
  45565. if( zName ){
  45566. for(i=0; i<p->nVar; i++){
  45567. const char *z = p->azVar[i];
  45568. if( z && strcmp(z,zName)==0 ){
  45569. return i+1;
  45570. }
  45571. }
  45572. }
  45573. return 0;
  45574. }
  45575. /*
  45576. ** Transfer all bindings from the first statement over to the second.
  45577. ** If the two statements contain a different number of bindings, then
  45578. ** an SQLITE_ERROR is returned.
  45579. */
  45580. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  45581. Vdbe *pFrom = (Vdbe*)pFromStmt;
  45582. Vdbe *pTo = (Vdbe*)pToStmt;
  45583. int i, rc = SQLITE_OK;
  45584. if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
  45585. || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT)
  45586. || pTo->db!=pFrom->db ){
  45587. return SQLITE_MISUSE;
  45588. }
  45589. if( pFrom->nVar!=pTo->nVar ){
  45590. return SQLITE_ERROR;
  45591. }
  45592. sqlite3_mutex_enter(pTo->db->mutex);
  45593. for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
  45594. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  45595. }
  45596. sqlite3_mutex_leave(pTo->db->mutex);
  45597. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  45598. return rc;
  45599. }
  45600. #ifndef SQLITE_OMIT_DEPRECATED
  45601. /*
  45602. ** Deprecated external interface. Internal/core SQLite code
  45603. ** should call sqlite3TransferBindings.
  45604. */
  45605. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  45606. return sqlite3TransferBindings(pFromStmt, pToStmt);
  45607. }
  45608. #endif
  45609. /*
  45610. ** Return the sqlite3* database handle to which the prepared statement given
  45611. ** in the argument belongs. This is the same database handle that was
  45612. ** the first argument to the sqlite3_prepare() that was used to create
  45613. ** the statement in the first place.
  45614. */
  45615. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  45616. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  45617. }
  45618. /*
  45619. ** Return a pointer to the next prepared statement after pStmt associated
  45620. ** with database connection pDb. If pStmt is NULL, return the first
  45621. ** prepared statement for the database connection. Return NULL if there
  45622. ** are no more.
  45623. */
  45624. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  45625. sqlite3_stmt *pNext;
  45626. sqlite3_mutex_enter(pDb->mutex);
  45627. if( pStmt==0 ){
  45628. pNext = (sqlite3_stmt*)pDb->pVdbe;
  45629. }else{
  45630. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  45631. }
  45632. sqlite3_mutex_leave(pDb->mutex);
  45633. return pNext;
  45634. }
  45635. /*
  45636. ** Return the value of a status counter for a prepared statement
  45637. */
  45638. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  45639. Vdbe *pVdbe = (Vdbe*)pStmt;
  45640. int v = pVdbe->aCounter[op-1];
  45641. if( resetFlag ) pVdbe->aCounter[op-1] = 0;
  45642. return v;
  45643. }
  45644. /************** End of vdbeapi.c *********************************************/
  45645. /************** Begin file vdbe.c ********************************************/
  45646. /*
  45647. ** 2001 September 15
  45648. **
  45649. ** The author disclaims copyright to this source code. In place of
  45650. ** a legal notice, here is a blessing:
  45651. **
  45652. ** May you do good and not evil.
  45653. ** May you find forgiveness for yourself and forgive others.
  45654. ** May you share freely, never taking more than you give.
  45655. **
  45656. *************************************************************************
  45657. ** The code in this file implements execution method of the
  45658. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  45659. ** handles housekeeping details such as creating and deleting
  45660. ** VDBE instances. This file is solely interested in executing
  45661. ** the VDBE program.
  45662. **
  45663. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  45664. ** to a VDBE.
  45665. **
  45666. ** The SQL parser generates a program which is then executed by
  45667. ** the VDBE to do the work of the SQL statement. VDBE programs are
  45668. ** similar in form to assembly language. The program consists of
  45669. ** a linear sequence of operations. Each operation has an opcode
  45670. ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
  45671. ** is a null-terminated string. Operand P5 is an unsigned character.
  45672. ** Few opcodes use all 5 operands.
  45673. **
  45674. ** Computation results are stored on a set of registers numbered beginning
  45675. ** with 1 and going up to Vdbe.nMem. Each register can store
  45676. ** either an integer, a null-terminated string, a floating point
  45677. ** number, or the SQL "NULL" value. An implicit conversion from one
  45678. ** type to the other occurs as necessary.
  45679. **
  45680. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  45681. ** function which does the work of interpreting a VDBE program.
  45682. ** But other routines are also provided to help in building up
  45683. ** a program instruction by instruction.
  45684. **
  45685. ** Various scripts scan this source file in order to generate HTML
  45686. ** documentation, headers files, or other derived files. The formatting
  45687. ** of the code in this file is, therefore, important. See other comments
  45688. ** in this file for details. If in doubt, do not deviate from existing
  45689. ** commenting and indentation practices when changing or adding code.
  45690. **
  45691. ** $Id: vdbe.c,v 1.811 2009/01/14 00:55:10 drh Exp $
  45692. */
  45693. /*
  45694. ** The following global variable is incremented every time a cursor
  45695. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  45696. ** procedures use this information to make sure that indices are
  45697. ** working correctly. This variable has no function other than to
  45698. ** help verify the correct operation of the library.
  45699. */
  45700. #ifdef SQLITE_TEST
  45701. SQLITE_API int sqlite3_search_count = 0;
  45702. #endif
  45703. /*
  45704. ** When this global variable is positive, it gets decremented once before
  45705. ** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
  45706. ** field of the sqlite3 structure is set in order to simulate and interrupt.
  45707. **
  45708. ** This facility is used for testing purposes only. It does not function
  45709. ** in an ordinary build.
  45710. */
  45711. #ifdef SQLITE_TEST
  45712. SQLITE_API int sqlite3_interrupt_count = 0;
  45713. #endif
  45714. /*
  45715. ** The next global variable is incremented each type the OP_Sort opcode
  45716. ** is executed. The test procedures use this information to make sure that
  45717. ** sorting is occurring or not occurring at appropriate times. This variable
  45718. ** has no function other than to help verify the correct operation of the
  45719. ** library.
  45720. */
  45721. #ifdef SQLITE_TEST
  45722. SQLITE_API int sqlite3_sort_count = 0;
  45723. #endif
  45724. /*
  45725. ** The next global variable records the size of the largest MEM_Blob
  45726. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  45727. ** use this information to make sure that the zero-blob functionality
  45728. ** is working correctly. This variable has no function other than to
  45729. ** help verify the correct operation of the library.
  45730. */
  45731. #ifdef SQLITE_TEST
  45732. SQLITE_API int sqlite3_max_blobsize = 0;
  45733. static void updateMaxBlobsize(Mem *p){
  45734. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  45735. sqlite3_max_blobsize = p->n;
  45736. }
  45737. }
  45738. #endif
  45739. /*
  45740. ** Test a register to see if it exceeds the current maximum blob size.
  45741. ** If it does, record the new maximum blob size.
  45742. */
  45743. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  45744. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  45745. #else
  45746. # define UPDATE_MAX_BLOBSIZE(P)
  45747. #endif
  45748. /*
  45749. ** Convert the given register into a string if it isn't one
  45750. ** already. Return non-zero if a malloc() fails.
  45751. */
  45752. #define Stringify(P, enc) \
  45753. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  45754. { goto no_mem; }
  45755. /*
  45756. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  45757. ** a pointer to a dynamically allocated string where some other entity
  45758. ** is responsible for deallocating that string. Because the register
  45759. ** does not control the string, it might be deleted without the register
  45760. ** knowing it.
  45761. **
  45762. ** This routine converts an ephemeral string into a dynamically allocated
  45763. ** string that the register itself controls. In other words, it
  45764. ** converts an MEM_Ephem string into an MEM_Dyn string.
  45765. */
  45766. #define Deephemeralize(P) \
  45767. if( ((P)->flags&MEM_Ephem)!=0 \
  45768. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  45769. /*
  45770. ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
  45771. ** P if required.
  45772. */
  45773. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  45774. /*
  45775. ** Argument pMem points at a register that will be passed to a
  45776. ** user-defined function or returned to the user as the result of a query.
  45777. ** The second argument, 'db_enc' is the text encoding used by the vdbe for
  45778. ** register variables. This routine sets the pMem->enc and pMem->type
  45779. ** variables used by the sqlite3_value_*() routines.
  45780. */
  45781. #define storeTypeInfo(A,B) _storeTypeInfo(A)
  45782. static void _storeTypeInfo(Mem *pMem){
  45783. int flags = pMem->flags;
  45784. if( flags & MEM_Null ){
  45785. pMem->type = SQLITE_NULL;
  45786. }
  45787. else if( flags & MEM_Int ){
  45788. pMem->type = SQLITE_INTEGER;
  45789. }
  45790. else if( flags & MEM_Real ){
  45791. pMem->type = SQLITE_FLOAT;
  45792. }
  45793. else if( flags & MEM_Str ){
  45794. pMem->type = SQLITE_TEXT;
  45795. }else{
  45796. pMem->type = SQLITE_BLOB;
  45797. }
  45798. }
  45799. /*
  45800. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  45801. ** created by mkopcodeh.awk during compilation. Data is obtained
  45802. ** from the comments following the "case OP_xxxx:" statements in
  45803. ** this file.
  45804. */
  45805. static const unsigned char opcodeProperty[] = OPFLG_INITIALIZER;
  45806. /*
  45807. ** Return true if an opcode has any of the OPFLG_xxx properties
  45808. ** specified by mask.
  45809. */
  45810. SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
  45811. assert( opcode>0 && opcode<(int)sizeof(opcodeProperty) );
  45812. return (opcodeProperty[opcode]&mask)!=0;
  45813. }
  45814. /*
  45815. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  45816. ** if we run out of memory.
  45817. */
  45818. static VdbeCursor *allocateCursor(
  45819. Vdbe *p, /* The virtual machine */
  45820. int iCur, /* Index of the new VdbeCursor */
  45821. Op *pOp, /* */
  45822. int iDb, /* When database the cursor belongs to, or -1 */
  45823. int isBtreeCursor /* */
  45824. ){
  45825. /* Find the memory cell that will be used to store the blob of memory
  45826. ** required for this VdbeCursor structure. It is convenient to use a
  45827. ** vdbe memory cell to manage the memory allocation required for a
  45828. ** VdbeCursor structure for the following reasons:
  45829. **
  45830. ** * Sometimes cursor numbers are used for a couple of different
  45831. ** purposes in a vdbe program. The different uses might require
  45832. ** different sized allocations. Memory cells provide growable
  45833. ** allocations.
  45834. **
  45835. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  45836. ** be freed lazily via the sqlite3_release_memory() API. This
  45837. ** minimizes the number of malloc calls made by the system.
  45838. **
  45839. ** Memory cells for cursors are allocated at the top of the address
  45840. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  45841. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  45842. */
  45843. Mem *pMem = &p->aMem[p->nMem-iCur];
  45844. int nByte;
  45845. VdbeCursor *pCx = 0;
  45846. /* If the opcode of pOp is OP_SetNumColumns, then pOp->p2 contains
  45847. ** the number of fields in the records contained in the table or
  45848. ** index being opened. Use this to reserve space for the
  45849. ** VdbeCursor.aType[] array.
  45850. */
  45851. int nField = 0;
  45852. if( pOp->opcode==OP_SetNumColumns || pOp->opcode==OP_OpenEphemeral ){
  45853. nField = pOp->p2;
  45854. }
  45855. nByte =
  45856. sizeof(VdbeCursor) +
  45857. (isBtreeCursor?sqlite3BtreeCursorSize():0) +
  45858. 2*nField*sizeof(u32);
  45859. assert( iCur<p->nCursor );
  45860. if( p->apCsr[iCur] ){
  45861. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  45862. p->apCsr[iCur] = 0;
  45863. }
  45864. if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  45865. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  45866. memset(pMem->z, 0, nByte);
  45867. pCx->iDb = iDb;
  45868. pCx->nField = nField;
  45869. if( nField ){
  45870. pCx->aType = (u32 *)&pMem->z[sizeof(VdbeCursor)];
  45871. }
  45872. if( isBtreeCursor ){
  45873. pCx->pCursor = (BtCursor*)
  45874. &pMem->z[sizeof(VdbeCursor)+2*nField*sizeof(u32)];
  45875. }
  45876. }
  45877. return pCx;
  45878. }
  45879. /*
  45880. ** Try to convert a value into a numeric representation if we can
  45881. ** do so without loss of information. In other words, if the string
  45882. ** looks like a number, convert it into a number. If it does not
  45883. ** look like a number, leave it alone.
  45884. */
  45885. static void applyNumericAffinity(Mem *pRec){
  45886. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  45887. int realnum;
  45888. sqlite3VdbeMemNulTerminate(pRec);
  45889. if( (pRec->flags&MEM_Str)
  45890. && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
  45891. i64 value;
  45892. sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
  45893. if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
  45894. pRec->u.i = value;
  45895. MemSetTypeFlag(pRec, MEM_Int);
  45896. }else{
  45897. sqlite3VdbeMemRealify(pRec);
  45898. }
  45899. }
  45900. }
  45901. }
  45902. /*
  45903. ** Processing is determine by the affinity parameter:
  45904. **
  45905. ** SQLITE_AFF_INTEGER:
  45906. ** SQLITE_AFF_REAL:
  45907. ** SQLITE_AFF_NUMERIC:
  45908. ** Try to convert pRec to an integer representation or a
  45909. ** floating-point representation if an integer representation
  45910. ** is not possible. Note that the integer representation is
  45911. ** always preferred, even if the affinity is REAL, because
  45912. ** an integer representation is more space efficient on disk.
  45913. **
  45914. ** SQLITE_AFF_TEXT:
  45915. ** Convert pRec to a text representation.
  45916. **
  45917. ** SQLITE_AFF_NONE:
  45918. ** No-op. pRec is unchanged.
  45919. */
  45920. static void applyAffinity(
  45921. Mem *pRec, /* The value to apply affinity to */
  45922. char affinity, /* The affinity to be applied */
  45923. u8 enc /* Use this text encoding */
  45924. ){
  45925. if( affinity==SQLITE_AFF_TEXT ){
  45926. /* Only attempt the conversion to TEXT if there is an integer or real
  45927. ** representation (blob and NULL do not get converted) but no string
  45928. ** representation.
  45929. */
  45930. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  45931. sqlite3VdbeMemStringify(pRec, enc);
  45932. }
  45933. pRec->flags &= ~(MEM_Real|MEM_Int);
  45934. }else if( affinity!=SQLITE_AFF_NONE ){
  45935. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  45936. || affinity==SQLITE_AFF_NUMERIC );
  45937. applyNumericAffinity(pRec);
  45938. if( pRec->flags & MEM_Real ){
  45939. sqlite3VdbeIntegerAffinity(pRec);
  45940. }
  45941. }
  45942. }
  45943. /*
  45944. ** Try to convert the type of a function argument or a result column
  45945. ** into a numeric representation. Use either INTEGER or REAL whichever
  45946. ** is appropriate. But only do the conversion if it is possible without
  45947. ** loss of information and return the revised type of the argument.
  45948. **
  45949. ** This is an EXPERIMENTAL api and is subject to change or removal.
  45950. */
  45951. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  45952. Mem *pMem = (Mem*)pVal;
  45953. applyNumericAffinity(pMem);
  45954. storeTypeInfo(pMem, 0);
  45955. return pMem->type;
  45956. }
  45957. /*
  45958. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  45959. ** not the internal Mem* type.
  45960. */
  45961. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  45962. sqlite3_value *pVal,
  45963. u8 affinity,
  45964. u8 enc
  45965. ){
  45966. applyAffinity((Mem *)pVal, affinity, enc);
  45967. }
  45968. #ifdef SQLITE_DEBUG
  45969. /*
  45970. ** Write a nice string representation of the contents of cell pMem
  45971. ** into buffer zBuf, length nBuf.
  45972. */
  45973. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  45974. char *zCsr = zBuf;
  45975. int f = pMem->flags;
  45976. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  45977. if( f&MEM_Blob ){
  45978. int i;
  45979. char c;
  45980. if( f & MEM_Dyn ){
  45981. c = 'z';
  45982. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  45983. }else if( f & MEM_Static ){
  45984. c = 't';
  45985. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  45986. }else if( f & MEM_Ephem ){
  45987. c = 'e';
  45988. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  45989. }else{
  45990. c = 's';
  45991. }
  45992. sqlite3_snprintf(100, zCsr, "%c", c);
  45993. zCsr += sqlite3Strlen30(zCsr);
  45994. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  45995. zCsr += sqlite3Strlen30(zCsr);
  45996. for(i=0; i<16 && i<pMem->n; i++){
  45997. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  45998. zCsr += sqlite3Strlen30(zCsr);
  45999. }
  46000. for(i=0; i<16 && i<pMem->n; i++){
  46001. char z = pMem->z[i];
  46002. if( z<32 || z>126 ) *zCsr++ = '.';
  46003. else *zCsr++ = z;
  46004. }
  46005. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  46006. zCsr += sqlite3Strlen30(zCsr);
  46007. if( f & MEM_Zero ){
  46008. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  46009. zCsr += sqlite3Strlen30(zCsr);
  46010. }
  46011. *zCsr = '\0';
  46012. }else if( f & MEM_Str ){
  46013. int j, k;
  46014. zBuf[0] = ' ';
  46015. if( f & MEM_Dyn ){
  46016. zBuf[1] = 'z';
  46017. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  46018. }else if( f & MEM_Static ){
  46019. zBuf[1] = 't';
  46020. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  46021. }else if( f & MEM_Ephem ){
  46022. zBuf[1] = 'e';
  46023. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  46024. }else{
  46025. zBuf[1] = 's';
  46026. }
  46027. k = 2;
  46028. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  46029. k += sqlite3Strlen30(&zBuf[k]);
  46030. zBuf[k++] = '[';
  46031. for(j=0; j<15 && j<pMem->n; j++){
  46032. u8 c = pMem->z[j];
  46033. if( c>=0x20 && c<0x7f ){
  46034. zBuf[k++] = c;
  46035. }else{
  46036. zBuf[k++] = '.';
  46037. }
  46038. }
  46039. zBuf[k++] = ']';
  46040. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  46041. k += sqlite3Strlen30(&zBuf[k]);
  46042. zBuf[k++] = 0;
  46043. }
  46044. }
  46045. #endif
  46046. #ifdef SQLITE_DEBUG
  46047. /*
  46048. ** Print the value of a register for tracing purposes:
  46049. */
  46050. static void memTracePrint(FILE *out, Mem *p){
  46051. if( p->flags & MEM_Null ){
  46052. fprintf(out, " NULL");
  46053. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  46054. fprintf(out, " si:%lld", p->u.i);
  46055. }else if( p->flags & MEM_Int ){
  46056. fprintf(out, " i:%lld", p->u.i);
  46057. }else if( p->flags & MEM_Real ){
  46058. fprintf(out, " r:%g", p->r);
  46059. }else{
  46060. char zBuf[200];
  46061. sqlite3VdbeMemPrettyPrint(p, zBuf);
  46062. fprintf(out, " ");
  46063. fprintf(out, "%s", zBuf);
  46064. }
  46065. }
  46066. static void registerTrace(FILE *out, int iReg, Mem *p){
  46067. fprintf(out, "REG[%d] = ", iReg);
  46068. memTracePrint(out, p);
  46069. fprintf(out, "\n");
  46070. }
  46071. #endif
  46072. #ifdef SQLITE_DEBUG
  46073. # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
  46074. #else
  46075. # define REGISTER_TRACE(R,M)
  46076. #endif
  46077. #ifdef VDBE_PROFILE
  46078. /*
  46079. ** hwtime.h contains inline assembler code for implementing
  46080. ** high-performance timing routines.
  46081. */
  46082. /************** Include hwtime.h in the middle of vdbe.c *********************/
  46083. /************** Begin file hwtime.h ******************************************/
  46084. /*
  46085. ** 2008 May 27
  46086. **
  46087. ** The author disclaims copyright to this source code. In place of
  46088. ** a legal notice, here is a blessing:
  46089. **
  46090. ** May you do good and not evil.
  46091. ** May you find forgiveness for yourself and forgive others.
  46092. ** May you share freely, never taking more than you give.
  46093. **
  46094. ******************************************************************************
  46095. **
  46096. ** This file contains inline asm code for retrieving "high-performance"
  46097. ** counters for x86 class CPUs.
  46098. **
  46099. ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
  46100. */
  46101. #ifndef _HWTIME_H_
  46102. #define _HWTIME_H_
  46103. /*
  46104. ** The following routine only works on pentium-class (or newer) processors.
  46105. ** It uses the RDTSC opcode to read the cycle count value out of the
  46106. ** processor and returns that value. This can be used for high-res
  46107. ** profiling.
  46108. */
  46109. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  46110. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  46111. #if defined(__GNUC__)
  46112. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  46113. unsigned int lo, hi;
  46114. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  46115. return (sqlite_uint64)hi << 32 | lo;
  46116. }
  46117. #elif defined(_MSC_VER)
  46118. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  46119. __asm {
  46120. rdtsc
  46121. ret ; return value at EDX:EAX
  46122. }
  46123. }
  46124. #endif
  46125. #elif (defined(__GNUC__) && defined(__x86_64__))
  46126. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  46127. unsigned long val;
  46128. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  46129. return val;
  46130. }
  46131. #elif (defined(__GNUC__) && defined(__ppc__))
  46132. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  46133. unsigned long long retval;
  46134. unsigned long junk;
  46135. __asm__ __volatile__ ("\n\
  46136. 1: mftbu %1\n\
  46137. mftb %L0\n\
  46138. mftbu %0\n\
  46139. cmpw %0,%1\n\
  46140. bne 1b"
  46141. : "=r" (retval), "=r" (junk));
  46142. return retval;
  46143. }
  46144. #else
  46145. #error Need implementation of sqlite3Hwtime() for your platform.
  46146. /*
  46147. ** To compile without implementing sqlite3Hwtime() for your platform,
  46148. ** you can remove the above #error and use the following
  46149. ** stub function. You will lose timing support for many
  46150. ** of the debugging and testing utilities, but it should at
  46151. ** least compile and run.
  46152. */
  46153. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  46154. #endif
  46155. #endif /* !defined(_HWTIME_H_) */
  46156. /************** End of hwtime.h **********************************************/
  46157. /************** Continuing where we left off in vdbe.c ***********************/
  46158. #endif
  46159. /*
  46160. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  46161. ** sqlite3_interrupt() routine has been called. If it has been, then
  46162. ** processing of the VDBE program is interrupted.
  46163. **
  46164. ** This macro added to every instruction that does a jump in order to
  46165. ** implement a loop. This test used to be on every single instruction,
  46166. ** but that meant we more testing that we needed. By only testing the
  46167. ** flag on jump instructions, we get a (small) speed improvement.
  46168. */
  46169. #define CHECK_FOR_INTERRUPT \
  46170. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  46171. #ifdef SQLITE_DEBUG
  46172. static int fileExists(sqlite3 *db, const char *zFile){
  46173. int res = 0;
  46174. int rc = SQLITE_OK;
  46175. #ifdef SQLITE_TEST
  46176. /* If we are currently testing IO errors, then do not call OsAccess() to
  46177. ** test for the presence of zFile. This is because any IO error that
  46178. ** occurs here will not be reported, causing the test to fail.
  46179. */
  46180. extern int sqlite3_io_error_pending;
  46181. if( sqlite3_io_error_pending<=0 )
  46182. #endif
  46183. rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
  46184. return (res && rc==SQLITE_OK);
  46185. }
  46186. #endif
  46187. #ifndef NDEBUG
  46188. /*
  46189. ** This function is only called from within an assert() expression. It
  46190. ** checks that the sqlite3.nTransaction variable is correctly set to
  46191. ** the number of non-transaction savepoints currently in the
  46192. ** linked list starting at sqlite3.pSavepoint.
  46193. **
  46194. ** Usage:
  46195. **
  46196. ** assert( checkSavepointCount(db) );
  46197. */
  46198. static int checkSavepointCount(sqlite3 *db){
  46199. int n = 0;
  46200. Savepoint *p;
  46201. for(p=db->pSavepoint; p; p=p->pNext) n++;
  46202. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  46203. return 1;
  46204. }
  46205. #endif
  46206. /*
  46207. ** Execute as much of a VDBE program as we can then return.
  46208. **
  46209. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  46210. ** close the program with a final OP_Halt and to set up the callbacks
  46211. ** and the error message pointer.
  46212. **
  46213. ** Whenever a row or result data is available, this routine will either
  46214. ** invoke the result callback (if there is one) or return with
  46215. ** SQLITE_ROW.
  46216. **
  46217. ** If an attempt is made to open a locked database, then this routine
  46218. ** will either invoke the busy callback (if there is one) or it will
  46219. ** return SQLITE_BUSY.
  46220. **
  46221. ** If an error occurs, an error message is written to memory obtained
  46222. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  46223. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  46224. **
  46225. ** If the callback ever returns non-zero, then the program exits
  46226. ** immediately. There will be no error message but the p->rc field is
  46227. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  46228. **
  46229. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  46230. ** routine to return SQLITE_ERROR.
  46231. **
  46232. ** Other fatal errors return SQLITE_ERROR.
  46233. **
  46234. ** After this routine has finished, sqlite3VdbeFinalize() should be
  46235. ** used to clean up the mess that was left behind.
  46236. */
  46237. SQLITE_PRIVATE int sqlite3VdbeExec(
  46238. Vdbe *p /* The VDBE */
  46239. ){
  46240. int pc; /* The program counter */
  46241. Op *pOp; /* Current operation */
  46242. int rc = SQLITE_OK; /* Value to return */
  46243. sqlite3 *db = p->db; /* The database */
  46244. u8 encoding = ENC(db); /* The database encoding */
  46245. Mem *pIn1 = 0; /* 1st input operand */
  46246. Mem *pIn2 = 0; /* 2nd input operand */
  46247. Mem *pIn3 = 0; /* 3rd input operand */
  46248. Mem *pOut = 0; /* Output operand */
  46249. u8 opProperty;
  46250. int iCompare = 0; /* Result of last OP_Compare operation */
  46251. int *aPermute = 0; /* Permuation of columns for OP_Compare */
  46252. #ifdef VDBE_PROFILE
  46253. u64 start; /* CPU clock count at start of opcode */
  46254. int origPc; /* Program counter at start of opcode */
  46255. #endif
  46256. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  46257. int nProgressOps = 0; /* Opcodes executed since progress callback. */
  46258. #endif
  46259. UnpackedRecord aTempRec[16]; /* Space to hold a transient UnpackedRecord */
  46260. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  46261. assert( db->magic==SQLITE_MAGIC_BUSY );
  46262. sqlite3BtreeMutexArrayEnter(&p->aMutex);
  46263. if( p->rc==SQLITE_NOMEM ){
  46264. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  46265. ** sqlite3_column_text16() failed. */
  46266. goto no_mem;
  46267. }
  46268. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  46269. p->rc = SQLITE_OK;
  46270. assert( p->explain==0 );
  46271. p->pResultSet = 0;
  46272. db->busyHandler.nBusy = 0;
  46273. CHECK_FOR_INTERRUPT;
  46274. sqlite3VdbeIOTraceSql(p);
  46275. #ifdef SQLITE_DEBUG
  46276. sqlite3BeginBenignMalloc();
  46277. if( p->pc==0
  46278. && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
  46279. ){
  46280. int i;
  46281. printf("VDBE Program Listing:\n");
  46282. sqlite3VdbePrintSql(p);
  46283. for(i=0; i<p->nOp; i++){
  46284. sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
  46285. }
  46286. }
  46287. if( fileExists(db, "vdbe_trace") ){
  46288. p->trace = stdout;
  46289. }
  46290. sqlite3EndBenignMalloc();
  46291. #endif
  46292. for(pc=p->pc; rc==SQLITE_OK; pc++){
  46293. assert( pc>=0 && pc<p->nOp );
  46294. if( db->mallocFailed ) goto no_mem;
  46295. #ifdef VDBE_PROFILE
  46296. origPc = pc;
  46297. start = sqlite3Hwtime();
  46298. #endif
  46299. pOp = &p->aOp[pc];
  46300. /* Only allow tracing if SQLITE_DEBUG is defined.
  46301. */
  46302. #ifdef SQLITE_DEBUG
  46303. if( p->trace ){
  46304. if( pc==0 ){
  46305. printf("VDBE Execution Trace:\n");
  46306. sqlite3VdbePrintSql(p);
  46307. }
  46308. sqlite3VdbePrintOp(p->trace, pc, pOp);
  46309. }
  46310. if( p->trace==0 && pc==0 ){
  46311. sqlite3BeginBenignMalloc();
  46312. if( fileExists(db, "vdbe_sqltrace") ){
  46313. sqlite3VdbePrintSql(p);
  46314. }
  46315. sqlite3EndBenignMalloc();
  46316. }
  46317. #endif
  46318. /* Check to see if we need to simulate an interrupt. This only happens
  46319. ** if we have a special test build.
  46320. */
  46321. #ifdef SQLITE_TEST
  46322. if( sqlite3_interrupt_count>0 ){
  46323. sqlite3_interrupt_count--;
  46324. if( sqlite3_interrupt_count==0 ){
  46325. sqlite3_interrupt(db);
  46326. }
  46327. }
  46328. #endif
  46329. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  46330. /* Call the progress callback if it is configured and the required number
  46331. ** of VDBE ops have been executed (either since this invocation of
  46332. ** sqlite3VdbeExec() or since last time the progress callback was called).
  46333. ** If the progress callback returns non-zero, exit the virtual machine with
  46334. ** a return code SQLITE_ABORT.
  46335. */
  46336. if( db->xProgress ){
  46337. if( db->nProgressOps==nProgressOps ){
  46338. int prc;
  46339. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  46340. prc =db->xProgress(db->pProgressArg);
  46341. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  46342. if( prc!=0 ){
  46343. rc = SQLITE_INTERRUPT;
  46344. goto vdbe_error_halt;
  46345. }
  46346. nProgressOps = 0;
  46347. }
  46348. nProgressOps++;
  46349. }
  46350. #endif
  46351. /* Do common setup processing for any opcode that is marked
  46352. ** with the "out2-prerelease" tag. Such opcodes have a single
  46353. ** output which is specified by the P2 parameter. The P2 register
  46354. ** is initialized to a NULL.
  46355. */
  46356. opProperty = opcodeProperty[pOp->opcode];
  46357. if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
  46358. assert( pOp->p2>0 );
  46359. assert( pOp->p2<=p->nMem );
  46360. pOut = &p->aMem[pOp->p2];
  46361. sqlite3VdbeMemReleaseExternal(pOut);
  46362. pOut->flags = MEM_Null;
  46363. }else
  46364. /* Do common setup for opcodes marked with one of the following
  46365. ** combinations of properties.
  46366. **
  46367. ** in1
  46368. ** in1 in2
  46369. ** in1 in2 out3
  46370. ** in1 in3
  46371. **
  46372. ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
  46373. ** registers for inputs. Variable pOut points to the output register.
  46374. */
  46375. if( (opProperty & OPFLG_IN1)!=0 ){
  46376. assert( pOp->p1>0 );
  46377. assert( pOp->p1<=p->nMem );
  46378. pIn1 = &p->aMem[pOp->p1];
  46379. REGISTER_TRACE(pOp->p1, pIn1);
  46380. if( (opProperty & OPFLG_IN2)!=0 ){
  46381. assert( pOp->p2>0 );
  46382. assert( pOp->p2<=p->nMem );
  46383. pIn2 = &p->aMem[pOp->p2];
  46384. REGISTER_TRACE(pOp->p2, pIn2);
  46385. if( (opProperty & OPFLG_OUT3)!=0 ){
  46386. assert( pOp->p3>0 );
  46387. assert( pOp->p3<=p->nMem );
  46388. pOut = &p->aMem[pOp->p3];
  46389. }
  46390. }else if( (opProperty & OPFLG_IN3)!=0 ){
  46391. assert( pOp->p3>0 );
  46392. assert( pOp->p3<=p->nMem );
  46393. pIn3 = &p->aMem[pOp->p3];
  46394. REGISTER_TRACE(pOp->p3, pIn3);
  46395. }
  46396. }else if( (opProperty & OPFLG_IN2)!=0 ){
  46397. assert( pOp->p2>0 );
  46398. assert( pOp->p2<=p->nMem );
  46399. pIn2 = &p->aMem[pOp->p2];
  46400. REGISTER_TRACE(pOp->p2, pIn2);
  46401. }else if( (opProperty & OPFLG_IN3)!=0 ){
  46402. assert( pOp->p3>0 );
  46403. assert( pOp->p3<=p->nMem );
  46404. pIn3 = &p->aMem[pOp->p3];
  46405. REGISTER_TRACE(pOp->p3, pIn3);
  46406. }
  46407. switch( pOp->opcode ){
  46408. /*****************************************************************************
  46409. ** What follows is a massive switch statement where each case implements a
  46410. ** separate instruction in the virtual machine. If we follow the usual
  46411. ** indentation conventions, each case should be indented by 6 spaces. But
  46412. ** that is a lot of wasted space on the left margin. So the code within
  46413. ** the switch statement will break with convention and be flush-left. Another
  46414. ** big comment (similar to this one) will mark the point in the code where
  46415. ** we transition back to normal indentation.
  46416. **
  46417. ** The formatting of each case is important. The makefile for SQLite
  46418. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  46419. ** file looking for lines that begin with "case OP_". The opcodes.h files
  46420. ** will be filled with #defines that give unique integer values to each
  46421. ** opcode and the opcodes.c file is filled with an array of strings where
  46422. ** each string is the symbolic name for the corresponding opcode. If the
  46423. ** case statement is followed by a comment of the form "/# same as ... #/"
  46424. ** that comment is used to determine the particular value of the opcode.
  46425. **
  46426. ** Other keywords in the comment that follows each case are used to
  46427. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  46428. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  46429. ** the mkopcodeh.awk script for additional information.
  46430. **
  46431. ** Documentation about VDBE opcodes is generated by scanning this file
  46432. ** for lines of that contain "Opcode:". That line and all subsequent
  46433. ** comment lines are used in the generation of the opcode.html documentation
  46434. ** file.
  46435. **
  46436. ** SUMMARY:
  46437. **
  46438. ** Formatting is important to scripts that scan this file.
  46439. ** Do not deviate from the formatting style currently in use.
  46440. **
  46441. *****************************************************************************/
  46442. /* Opcode: Goto * P2 * * *
  46443. **
  46444. ** An unconditional jump to address P2.
  46445. ** The next instruction executed will be
  46446. ** the one at index P2 from the beginning of
  46447. ** the program.
  46448. */
  46449. case OP_Goto: { /* jump */
  46450. CHECK_FOR_INTERRUPT;
  46451. pc = pOp->p2 - 1;
  46452. break;
  46453. }
  46454. /* Opcode: Gosub P1 P2 * * *
  46455. **
  46456. ** Write the current address onto register P1
  46457. ** and then jump to address P2.
  46458. */
  46459. case OP_Gosub: { /* jump */
  46460. assert( pOp->p1>0 );
  46461. assert( pOp->p1<=p->nMem );
  46462. pIn1 = &p->aMem[pOp->p1];
  46463. assert( (pIn1->flags & MEM_Dyn)==0 );
  46464. pIn1->flags = MEM_Int;
  46465. pIn1->u.i = pc;
  46466. REGISTER_TRACE(pOp->p1, pIn1);
  46467. pc = pOp->p2 - 1;
  46468. break;
  46469. }
  46470. /* Opcode: Return P1 * * * *
  46471. **
  46472. ** Jump to the next instruction after the address in register P1.
  46473. */
  46474. case OP_Return: { /* in1 */
  46475. assert( pIn1->flags & MEM_Int );
  46476. pc = (int)pIn1->u.i;
  46477. break;
  46478. }
  46479. /* Opcode: Yield P1 * * * *
  46480. **
  46481. ** Swap the program counter with the value in register P1.
  46482. */
  46483. case OP_Yield: { /* in1 */
  46484. int pcDest;
  46485. assert( (pIn1->flags & MEM_Dyn)==0 );
  46486. pIn1->flags = MEM_Int;
  46487. pcDest = (int)pIn1->u.i;
  46488. pIn1->u.i = pc;
  46489. REGISTER_TRACE(pOp->p1, pIn1);
  46490. pc = pcDest;
  46491. break;
  46492. }
  46493. /* Opcode: Halt P1 P2 * P4 *
  46494. **
  46495. ** Exit immediately. All open cursors, etc are closed
  46496. ** automatically.
  46497. **
  46498. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  46499. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  46500. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  46501. ** whether or not to rollback the current transaction. Do not rollback
  46502. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  46503. ** then back out all changes that have occurred during this execution of the
  46504. ** VDBE, but do not rollback the transaction.
  46505. **
  46506. ** If P4 is not null then it is an error message string.
  46507. **
  46508. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  46509. ** every program. So a jump past the last instruction of the program
  46510. ** is the same as executing Halt.
  46511. */
  46512. case OP_Halt: {
  46513. p->rc = pOp->p1;
  46514. p->pc = pc;
  46515. p->errorAction = pOp->p2;
  46516. if( pOp->p4.z ){
  46517. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  46518. }
  46519. rc = sqlite3VdbeHalt(p);
  46520. assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
  46521. if( rc==SQLITE_BUSY ){
  46522. p->rc = rc = SQLITE_BUSY;
  46523. }else{
  46524. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  46525. }
  46526. goto vdbe_return;
  46527. }
  46528. /* Opcode: Integer P1 P2 * * *
  46529. **
  46530. ** The 32-bit integer value P1 is written into register P2.
  46531. */
  46532. case OP_Integer: { /* out2-prerelease */
  46533. pOut->flags = MEM_Int;
  46534. pOut->u.i = pOp->p1;
  46535. break;
  46536. }
  46537. /* Opcode: Int64 * P2 * P4 *
  46538. **
  46539. ** P4 is a pointer to a 64-bit integer value.
  46540. ** Write that value into register P2.
  46541. */
  46542. case OP_Int64: { /* out2-prerelease */
  46543. assert( pOp->p4.pI64!=0 );
  46544. pOut->flags = MEM_Int;
  46545. pOut->u.i = *pOp->p4.pI64;
  46546. break;
  46547. }
  46548. /* Opcode: Real * P2 * P4 *
  46549. **
  46550. ** P4 is a pointer to a 64-bit floating point value.
  46551. ** Write that value into register P2.
  46552. */
  46553. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  46554. pOut->flags = MEM_Real;
  46555. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  46556. pOut->r = *pOp->p4.pReal;
  46557. break;
  46558. }
  46559. /* Opcode: String8 * P2 * P4 *
  46560. **
  46561. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  46562. ** into an OP_String before it is executed for the first time.
  46563. */
  46564. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  46565. assert( pOp->p4.z!=0 );
  46566. pOp->opcode = OP_String;
  46567. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  46568. #ifndef SQLITE_OMIT_UTF16
  46569. if( encoding!=SQLITE_UTF8 ){
  46570. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  46571. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  46572. if( SQLITE_OK!=sqlite3VdbeMemMakeWriteable(pOut) ) goto no_mem;
  46573. pOut->zMalloc = 0;
  46574. pOut->flags |= MEM_Static;
  46575. pOut->flags &= ~MEM_Dyn;
  46576. if( pOp->p4type==P4_DYNAMIC ){
  46577. sqlite3DbFree(db, pOp->p4.z);
  46578. }
  46579. pOp->p4type = P4_DYNAMIC;
  46580. pOp->p4.z = pOut->z;
  46581. pOp->p1 = pOut->n;
  46582. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  46583. goto too_big;
  46584. }
  46585. UPDATE_MAX_BLOBSIZE(pOut);
  46586. break;
  46587. }
  46588. #endif
  46589. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  46590. goto too_big;
  46591. }
  46592. /* Fall through to the next case, OP_String */
  46593. }
  46594. /* Opcode: String P1 P2 * P4 *
  46595. **
  46596. ** The string value P4 of length P1 (bytes) is stored in register P2.
  46597. */
  46598. case OP_String: { /* out2-prerelease */
  46599. assert( pOp->p4.z!=0 );
  46600. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  46601. pOut->z = pOp->p4.z;
  46602. pOut->n = pOp->p1;
  46603. pOut->enc = encoding;
  46604. UPDATE_MAX_BLOBSIZE(pOut);
  46605. break;
  46606. }
  46607. /* Opcode: Null * P2 * * *
  46608. **
  46609. ** Write a NULL into register P2.
  46610. */
  46611. case OP_Null: { /* out2-prerelease */
  46612. break;
  46613. }
  46614. /* Opcode: Blob P1 P2 * P4
  46615. **
  46616. ** P4 points to a blob of data P1 bytes long. Store this
  46617. ** blob in register P2. This instruction is not coded directly
  46618. ** by the compiler. Instead, the compiler layer specifies
  46619. ** an OP_HexBlob opcode, with the hex string representation of
  46620. ** the blob as P4. This opcode is transformed to an OP_Blob
  46621. ** the first time it is executed.
  46622. */
  46623. case OP_Blob: { /* out2-prerelease */
  46624. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  46625. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  46626. pOut->enc = encoding;
  46627. UPDATE_MAX_BLOBSIZE(pOut);
  46628. break;
  46629. }
  46630. /* Opcode: Variable P1 P2 * * *
  46631. **
  46632. ** The value of variable P1 is written into register P2. A variable is
  46633. ** an unknown in the original SQL string as handed to sqlite3_compile().
  46634. ** Any occurrence of the '?' character in the original SQL is considered
  46635. ** a variable. Variables in the SQL string are number from left to
  46636. ** right beginning with 1. The values of variables are set using the
  46637. ** sqlite3_bind() API.
  46638. */
  46639. case OP_Variable: { /* out2-prerelease */
  46640. int j = pOp->p1 - 1;
  46641. Mem *pVar;
  46642. assert( j>=0 && j<p->nVar );
  46643. pVar = &p->aVar[j];
  46644. if( sqlite3VdbeMemTooBig(pVar) ){
  46645. goto too_big;
  46646. }
  46647. sqlite3VdbeMemShallowCopy(pOut, &p->aVar[j], MEM_Static);
  46648. UPDATE_MAX_BLOBSIZE(pOut);
  46649. break;
  46650. }
  46651. /* Opcode: Move P1 P2 P3 * *
  46652. **
  46653. ** Move the values in register P1..P1+P3-1 over into
  46654. ** registers P2..P2+P3-1. Registers P1..P1+P1-1 are
  46655. ** left holding a NULL. It is an error for register ranges
  46656. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
  46657. */
  46658. case OP_Move: {
  46659. char *zMalloc;
  46660. int n = pOp->p3;
  46661. int p1 = pOp->p1;
  46662. int p2 = pOp->p2;
  46663. assert( n>0 );
  46664. assert( p1>0 );
  46665. assert( p1+n<p->nMem );
  46666. pIn1 = &p->aMem[p1];
  46667. assert( p2>0 );
  46668. assert( p2+n<p->nMem );
  46669. pOut = &p->aMem[p2];
  46670. assert( p1+n<=p2 || p2+n<=p1 );
  46671. while( n-- ){
  46672. zMalloc = pOut->zMalloc;
  46673. pOut->zMalloc = 0;
  46674. sqlite3VdbeMemMove(pOut, pIn1);
  46675. pIn1->zMalloc = zMalloc;
  46676. REGISTER_TRACE(p2++, pOut);
  46677. pIn1++;
  46678. pOut++;
  46679. }
  46680. break;
  46681. }
  46682. /* Opcode: Copy P1 P2 * * *
  46683. **
  46684. ** Make a copy of register P1 into register P2.
  46685. **
  46686. ** This instruction makes a deep copy of the value. A duplicate
  46687. ** is made of any string or blob constant. See also OP_SCopy.
  46688. */
  46689. case OP_Copy: { /* in1 */
  46690. assert( pOp->p2>0 );
  46691. assert( pOp->p2<=p->nMem );
  46692. pOut = &p->aMem[pOp->p2];
  46693. assert( pOut!=pIn1 );
  46694. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  46695. Deephemeralize(pOut);
  46696. REGISTER_TRACE(pOp->p2, pOut);
  46697. break;
  46698. }
  46699. /* Opcode: SCopy P1 P2 * * *
  46700. **
  46701. ** Make a shallow copy of register P1 into register P2.
  46702. **
  46703. ** This instruction makes a shallow copy of the value. If the value
  46704. ** is a string or blob, then the copy is only a pointer to the
  46705. ** original and hence if the original changes so will the copy.
  46706. ** Worse, if the original is deallocated, the copy becomes invalid.
  46707. ** Thus the program must guarantee that the original will not change
  46708. ** during the lifetime of the copy. Use OP_Copy to make a complete
  46709. ** copy.
  46710. */
  46711. case OP_SCopy: { /* in1 */
  46712. REGISTER_TRACE(pOp->p1, pIn1);
  46713. assert( pOp->p2>0 );
  46714. assert( pOp->p2<=p->nMem );
  46715. pOut = &p->aMem[pOp->p2];
  46716. assert( pOut!=pIn1 );
  46717. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  46718. REGISTER_TRACE(pOp->p2, pOut);
  46719. break;
  46720. }
  46721. /* Opcode: ResultRow P1 P2 * * *
  46722. **
  46723. ** The registers P1 through P1+P2-1 contain a single row of
  46724. ** results. This opcode causes the sqlite3_step() call to terminate
  46725. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  46726. ** structure to provide access to the top P1 values as the result
  46727. ** row.
  46728. */
  46729. case OP_ResultRow: {
  46730. Mem *pMem;
  46731. int i;
  46732. assert( p->nResColumn==pOp->p2 );
  46733. assert( pOp->p1>0 );
  46734. assert( pOp->p1+pOp->p2<=p->nMem );
  46735. /* Invalidate all ephemeral cursor row caches */
  46736. p->cacheCtr = (p->cacheCtr + 2)|1;
  46737. /* Make sure the results of the current row are \000 terminated
  46738. ** and have an assigned type. The results are de-ephemeralized as
  46739. ** as side effect.
  46740. */
  46741. pMem = p->pResultSet = &p->aMem[pOp->p1];
  46742. for(i=0; i<pOp->p2; i++){
  46743. sqlite3VdbeMemNulTerminate(&pMem[i]);
  46744. storeTypeInfo(&pMem[i], encoding);
  46745. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  46746. }
  46747. if( db->mallocFailed ) goto no_mem;
  46748. /* Return SQLITE_ROW
  46749. */
  46750. p->nCallback++;
  46751. p->pc = pc + 1;
  46752. rc = SQLITE_ROW;
  46753. goto vdbe_return;
  46754. }
  46755. /* Opcode: Concat P1 P2 P3 * *
  46756. **
  46757. ** Add the text in register P1 onto the end of the text in
  46758. ** register P2 and store the result in register P3.
  46759. ** If either the P1 or P2 text are NULL then store NULL in P3.
  46760. **
  46761. ** P3 = P2 || P1
  46762. **
  46763. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  46764. ** if P3 is the same register as P2, the implementation is able
  46765. ** to avoid a memcpy().
  46766. */
  46767. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  46768. i64 nByte;
  46769. assert( pIn1!=pOut );
  46770. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  46771. sqlite3VdbeMemSetNull(pOut);
  46772. break;
  46773. }
  46774. ExpandBlob(pIn1);
  46775. Stringify(pIn1, encoding);
  46776. ExpandBlob(pIn2);
  46777. Stringify(pIn2, encoding);
  46778. nByte = pIn1->n + pIn2->n;
  46779. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  46780. goto too_big;
  46781. }
  46782. MemSetTypeFlag(pOut, MEM_Str);
  46783. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  46784. goto no_mem;
  46785. }
  46786. if( pOut!=pIn2 ){
  46787. memcpy(pOut->z, pIn2->z, pIn2->n);
  46788. }
  46789. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  46790. pOut->z[nByte] = 0;
  46791. pOut->z[nByte+1] = 0;
  46792. pOut->flags |= MEM_Term;
  46793. pOut->n = (int)nByte;
  46794. pOut->enc = encoding;
  46795. UPDATE_MAX_BLOBSIZE(pOut);
  46796. break;
  46797. }
  46798. /* Opcode: Add P1 P2 P3 * *
  46799. **
  46800. ** Add the value in register P1 to the value in register P2
  46801. ** and store the result in register P3.
  46802. ** If either input is NULL, the result is NULL.
  46803. */
  46804. /* Opcode: Multiply P1 P2 P3 * *
  46805. **
  46806. **
  46807. ** Multiply the value in register P1 by the value in register P2
  46808. ** and store the result in register P3.
  46809. ** If either input is NULL, the result is NULL.
  46810. */
  46811. /* Opcode: Subtract P1 P2 P3 * *
  46812. **
  46813. ** Subtract the value in register P1 from the value in register P2
  46814. ** and store the result in register P3.
  46815. ** If either input is NULL, the result is NULL.
  46816. */
  46817. /* Opcode: Divide P1 P2 P3 * *
  46818. **
  46819. ** Divide the value in register P1 by the value in register P2
  46820. ** and store the result in register P3. If the value in register P2
  46821. ** is zero, then the result is NULL.
  46822. ** If either input is NULL, the result is NULL.
  46823. */
  46824. /* Opcode: Remainder P1 P2 P3 * *
  46825. **
  46826. ** Compute the remainder after integer division of the value in
  46827. ** register P1 by the value in register P2 and store the result in P3.
  46828. ** If the value in register P2 is zero the result is NULL.
  46829. ** If either operand is NULL, the result is NULL.
  46830. */
  46831. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  46832. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  46833. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  46834. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  46835. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  46836. int flags;
  46837. applyNumericAffinity(pIn1);
  46838. applyNumericAffinity(pIn2);
  46839. flags = pIn1->flags | pIn2->flags;
  46840. if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  46841. if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
  46842. i64 a, b;
  46843. a = pIn1->u.i;
  46844. b = pIn2->u.i;
  46845. switch( pOp->opcode ){
  46846. case OP_Add: b += a; break;
  46847. case OP_Subtract: b -= a; break;
  46848. case OP_Multiply: b *= a; break;
  46849. case OP_Divide: {
  46850. if( a==0 ) goto arithmetic_result_is_null;
  46851. /* Dividing the largest possible negative 64-bit integer (1<<63) by
  46852. ** -1 returns an integer too large to store in a 64-bit data-type. On
  46853. ** some architectures, the value overflows to (1<<63). On others,
  46854. ** a SIGFPE is issued. The following statement normalizes this
  46855. ** behavior so that all architectures behave as if integer
  46856. ** overflow occurred.
  46857. */
  46858. if( a==-1 && b==SMALLEST_INT64 ) a = 1;
  46859. b /= a;
  46860. break;
  46861. }
  46862. default: {
  46863. if( a==0 ) goto arithmetic_result_is_null;
  46864. if( a==-1 ) a = 1;
  46865. b %= a;
  46866. break;
  46867. }
  46868. }
  46869. pOut->u.i = b;
  46870. MemSetTypeFlag(pOut, MEM_Int);
  46871. }else{
  46872. double a, b;
  46873. a = sqlite3VdbeRealValue(pIn1);
  46874. b = sqlite3VdbeRealValue(pIn2);
  46875. switch( pOp->opcode ){
  46876. case OP_Add: b += a; break;
  46877. case OP_Subtract: b -= a; break;
  46878. case OP_Multiply: b *= a; break;
  46879. case OP_Divide: {
  46880. if( a==0.0 ) goto arithmetic_result_is_null;
  46881. b /= a;
  46882. break;
  46883. }
  46884. default: {
  46885. i64 ia = (i64)a;
  46886. i64 ib = (i64)b;
  46887. if( ia==0 ) goto arithmetic_result_is_null;
  46888. if( ia==-1 ) ia = 1;
  46889. b = (double)(ib % ia);
  46890. break;
  46891. }
  46892. }
  46893. if( sqlite3IsNaN(b) ){
  46894. goto arithmetic_result_is_null;
  46895. }
  46896. pOut->r = b;
  46897. MemSetTypeFlag(pOut, MEM_Real);
  46898. if( (flags & MEM_Real)==0 ){
  46899. sqlite3VdbeIntegerAffinity(pOut);
  46900. }
  46901. }
  46902. break;
  46903. arithmetic_result_is_null:
  46904. sqlite3VdbeMemSetNull(pOut);
  46905. break;
  46906. }
  46907. /* Opcode: CollSeq * * P4
  46908. **
  46909. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  46910. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  46911. ** be returned. This is used by the built-in min(), max() and nullif()
  46912. ** functions.
  46913. **
  46914. ** The interface used by the implementation of the aforementioned functions
  46915. ** to retrieve the collation sequence set by this opcode is not available
  46916. ** publicly, only to user functions defined in func.c.
  46917. */
  46918. case OP_CollSeq: {
  46919. assert( pOp->p4type==P4_COLLSEQ );
  46920. break;
  46921. }
  46922. /* Opcode: Function P1 P2 P3 P4 P5
  46923. **
  46924. ** Invoke a user function (P4 is a pointer to a Function structure that
  46925. ** defines the function) with P5 arguments taken from register P2 and
  46926. ** successors. The result of the function is stored in register P3.
  46927. ** Register P3 must not be one of the function inputs.
  46928. **
  46929. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  46930. ** function was determined to be constant at compile time. If the first
  46931. ** argument was constant then bit 0 of P1 is set. This is used to determine
  46932. ** whether meta data associated with a user function argument using the
  46933. ** sqlite3_set_auxdata() API may be safely retained until the next
  46934. ** invocation of this opcode.
  46935. **
  46936. ** See also: AggStep and AggFinal
  46937. */
  46938. case OP_Function: {
  46939. int i;
  46940. Mem *pArg;
  46941. sqlite3_context ctx;
  46942. sqlite3_value **apVal;
  46943. int n = pOp->p5;
  46944. apVal = p->apArg;
  46945. assert( apVal || n==0 );
  46946. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem) );
  46947. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  46948. pArg = &p->aMem[pOp->p2];
  46949. for(i=0; i<n; i++, pArg++){
  46950. apVal[i] = pArg;
  46951. storeTypeInfo(pArg, encoding);
  46952. REGISTER_TRACE(pOp->p2, pArg);
  46953. }
  46954. assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
  46955. if( pOp->p4type==P4_FUNCDEF ){
  46956. ctx.pFunc = pOp->p4.pFunc;
  46957. ctx.pVdbeFunc = 0;
  46958. }else{
  46959. ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
  46960. ctx.pFunc = ctx.pVdbeFunc->pFunc;
  46961. }
  46962. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  46963. pOut = &p->aMem[pOp->p3];
  46964. ctx.s.flags = MEM_Null;
  46965. ctx.s.db = db;
  46966. ctx.s.xDel = 0;
  46967. ctx.s.zMalloc = 0;
  46968. /* The output cell may already have a buffer allocated. Move
  46969. ** the pointer to ctx.s so in case the user-function can use
  46970. ** the already allocated buffer instead of allocating a new one.
  46971. */
  46972. sqlite3VdbeMemMove(&ctx.s, pOut);
  46973. MemSetTypeFlag(&ctx.s, MEM_Null);
  46974. ctx.isError = 0;
  46975. if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  46976. assert( pOp>p->aOp );
  46977. assert( pOp[-1].p4type==P4_COLLSEQ );
  46978. assert( pOp[-1].opcode==OP_CollSeq );
  46979. ctx.pColl = pOp[-1].p4.pColl;
  46980. }
  46981. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  46982. (*ctx.pFunc->xFunc)(&ctx, n, apVal);
  46983. if( sqlite3SafetyOn(db) ){
  46984. sqlite3VdbeMemRelease(&ctx.s);
  46985. goto abort_due_to_misuse;
  46986. }
  46987. if( db->mallocFailed ){
  46988. /* Even though a malloc() has failed, the implementation of the
  46989. ** user function may have called an sqlite3_result_XXX() function
  46990. ** to return a value. The following call releases any resources
  46991. ** associated with such a value.
  46992. **
  46993. ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
  46994. ** fails also (the if(...) statement above). But if people are
  46995. ** misusing sqlite, they have bigger problems than a leaked value.
  46996. */
  46997. sqlite3VdbeMemRelease(&ctx.s);
  46998. goto no_mem;
  46999. }
  47000. /* If any auxiliary data functions have been called by this user function,
  47001. ** immediately call the destructor for any non-static values.
  47002. */
  47003. if( ctx.pVdbeFunc ){
  47004. sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
  47005. pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
  47006. pOp->p4type = P4_VDBEFUNC;
  47007. }
  47008. /* If the function returned an error, throw an exception */
  47009. if( ctx.isError ){
  47010. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
  47011. rc = ctx.isError;
  47012. }
  47013. /* Copy the result of the function into register P3 */
  47014. sqlite3VdbeChangeEncoding(&ctx.s, encoding);
  47015. sqlite3VdbeMemMove(pOut, &ctx.s);
  47016. if( sqlite3VdbeMemTooBig(pOut) ){
  47017. goto too_big;
  47018. }
  47019. REGISTER_TRACE(pOp->p3, pOut);
  47020. UPDATE_MAX_BLOBSIZE(pOut);
  47021. break;
  47022. }
  47023. /* Opcode: BitAnd P1 P2 P3 * *
  47024. **
  47025. ** Take the bit-wise AND of the values in register P1 and P2 and
  47026. ** store the result in register P3.
  47027. ** If either input is NULL, the result is NULL.
  47028. */
  47029. /* Opcode: BitOr P1 P2 P3 * *
  47030. **
  47031. ** Take the bit-wise OR of the values in register P1 and P2 and
  47032. ** store the result in register P3.
  47033. ** If either input is NULL, the result is NULL.
  47034. */
  47035. /* Opcode: ShiftLeft P1 P2 P3 * *
  47036. **
  47037. ** Shift the integer value in register P2 to the left by the
  47038. ** number of bits specified by the integer in regiser P1.
  47039. ** Store the result in register P3.
  47040. ** If either input is NULL, the result is NULL.
  47041. */
  47042. /* Opcode: ShiftRight P1 P2 P3 * *
  47043. **
  47044. ** Shift the integer value in register P2 to the right by the
  47045. ** number of bits specified by the integer in register P1.
  47046. ** Store the result in register P3.
  47047. ** If either input is NULL, the result is NULL.
  47048. */
  47049. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  47050. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  47051. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  47052. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  47053. i64 a, b;
  47054. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  47055. sqlite3VdbeMemSetNull(pOut);
  47056. break;
  47057. }
  47058. a = sqlite3VdbeIntValue(pIn2);
  47059. b = sqlite3VdbeIntValue(pIn1);
  47060. switch( pOp->opcode ){
  47061. case OP_BitAnd: a &= b; break;
  47062. case OP_BitOr: a |= b; break;
  47063. case OP_ShiftLeft: a <<= b; break;
  47064. default: assert( pOp->opcode==OP_ShiftRight );
  47065. a >>= b; break;
  47066. }
  47067. pOut->u.i = a;
  47068. MemSetTypeFlag(pOut, MEM_Int);
  47069. break;
  47070. }
  47071. /* Opcode: AddImm P1 P2 * * *
  47072. **
  47073. ** Add the constant P2 to the value in register P1.
  47074. ** The result is always an integer.
  47075. **
  47076. ** To force any register to be an integer, just add 0.
  47077. */
  47078. case OP_AddImm: { /* in1 */
  47079. sqlite3VdbeMemIntegerify(pIn1);
  47080. pIn1->u.i += pOp->p2;
  47081. break;
  47082. }
  47083. /* Opcode: MustBeInt P1 P2 * * *
  47084. **
  47085. ** Force the value in register P1 to be an integer. If the value
  47086. ** in P1 is not an integer and cannot be converted into an integer
  47087. ** without data loss, then jump immediately to P2, or if P2==0
  47088. ** raise an SQLITE_MISMATCH exception.
  47089. */
  47090. case OP_MustBeInt: { /* jump, in1 */
  47091. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  47092. if( (pIn1->flags & MEM_Int)==0 ){
  47093. if( pOp->p2==0 ){
  47094. rc = SQLITE_MISMATCH;
  47095. goto abort_due_to_error;
  47096. }else{
  47097. pc = pOp->p2 - 1;
  47098. }
  47099. }else{
  47100. MemSetTypeFlag(pIn1, MEM_Int);
  47101. }
  47102. break;
  47103. }
  47104. /* Opcode: RealAffinity P1 * * * *
  47105. **
  47106. ** If register P1 holds an integer convert it to a real value.
  47107. **
  47108. ** This opcode is used when extracting information from a column that
  47109. ** has REAL affinity. Such column values may still be stored as
  47110. ** integers, for space efficiency, but after extraction we want them
  47111. ** to have only a real value.
  47112. */
  47113. case OP_RealAffinity: { /* in1 */
  47114. if( pIn1->flags & MEM_Int ){
  47115. sqlite3VdbeMemRealify(pIn1);
  47116. }
  47117. break;
  47118. }
  47119. #ifndef SQLITE_OMIT_CAST
  47120. /* Opcode: ToText P1 * * * *
  47121. **
  47122. ** Force the value in register P1 to be text.
  47123. ** If the value is numeric, convert it to a string using the
  47124. ** equivalent of printf(). Blob values are unchanged and
  47125. ** are afterwards simply interpreted as text.
  47126. **
  47127. ** A NULL value is not changed by this routine. It remains NULL.
  47128. */
  47129. case OP_ToText: { /* same as TK_TO_TEXT, in1 */
  47130. if( pIn1->flags & MEM_Null ) break;
  47131. assert( MEM_Str==(MEM_Blob>>3) );
  47132. pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  47133. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  47134. rc = ExpandBlob(pIn1);
  47135. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  47136. pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  47137. UPDATE_MAX_BLOBSIZE(pIn1);
  47138. break;
  47139. }
  47140. /* Opcode: ToBlob P1 * * * *
  47141. **
  47142. ** Force the value in register P1 to be a BLOB.
  47143. ** If the value is numeric, convert it to a string first.
  47144. ** Strings are simply reinterpreted as blobs with no change
  47145. ** to the underlying data.
  47146. **
  47147. ** A NULL value is not changed by this routine. It remains NULL.
  47148. */
  47149. case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
  47150. if( pIn1->flags & MEM_Null ) break;
  47151. if( (pIn1->flags & MEM_Blob)==0 ){
  47152. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  47153. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  47154. MemSetTypeFlag(pIn1, MEM_Blob);
  47155. }else{
  47156. pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  47157. }
  47158. UPDATE_MAX_BLOBSIZE(pIn1);
  47159. break;
  47160. }
  47161. /* Opcode: ToNumeric P1 * * * *
  47162. **
  47163. ** Force the value in register P1 to be numeric (either an
  47164. ** integer or a floating-point number.)
  47165. ** If the value is text or blob, try to convert it to an using the
  47166. ** equivalent of atoi() or atof() and store 0 if no such conversion
  47167. ** is possible.
  47168. **
  47169. ** A NULL value is not changed by this routine. It remains NULL.
  47170. */
  47171. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
  47172. if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
  47173. sqlite3VdbeMemNumerify(pIn1);
  47174. }
  47175. break;
  47176. }
  47177. #endif /* SQLITE_OMIT_CAST */
  47178. /* Opcode: ToInt P1 * * * *
  47179. **
  47180. ** Force the value in register P1 be an integer. If
  47181. ** The value is currently a real number, drop its fractional part.
  47182. ** If the value is text or blob, try to convert it to an integer using the
  47183. ** equivalent of atoi() and store 0 if no such conversion is possible.
  47184. **
  47185. ** A NULL value is not changed by this routine. It remains NULL.
  47186. */
  47187. case OP_ToInt: { /* same as TK_TO_INT, in1 */
  47188. if( (pIn1->flags & MEM_Null)==0 ){
  47189. sqlite3VdbeMemIntegerify(pIn1);
  47190. }
  47191. break;
  47192. }
  47193. #ifndef SQLITE_OMIT_CAST
  47194. /* Opcode: ToReal P1 * * * *
  47195. **
  47196. ** Force the value in register P1 to be a floating point number.
  47197. ** If The value is currently an integer, convert it.
  47198. ** If the value is text or blob, try to convert it to an integer using the
  47199. ** equivalent of atoi() and store 0.0 if no such conversion is possible.
  47200. **
  47201. ** A NULL value is not changed by this routine. It remains NULL.
  47202. */
  47203. case OP_ToReal: { /* same as TK_TO_REAL, in1 */
  47204. if( (pIn1->flags & MEM_Null)==0 ){
  47205. sqlite3VdbeMemRealify(pIn1);
  47206. }
  47207. break;
  47208. }
  47209. #endif /* SQLITE_OMIT_CAST */
  47210. /* Opcode: Lt P1 P2 P3 P4 P5
  47211. **
  47212. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  47213. ** jump to address P2.
  47214. **
  47215. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  47216. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  47217. ** bit is clear then fall thru if either operand is NULL.
  47218. **
  47219. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  47220. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  47221. ** to coerce both inputs according to this affinity before the
  47222. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  47223. ** affinity is used. Note that the affinity conversions are stored
  47224. ** back into the input registers P1 and P3. So this opcode can cause
  47225. ** persistent changes to registers P1 and P3.
  47226. **
  47227. ** Once any conversions have taken place, and neither value is NULL,
  47228. ** the values are compared. If both values are blobs then memcmp() is
  47229. ** used to determine the results of the comparison. If both values
  47230. ** are text, then the appropriate collating function specified in
  47231. ** P4 is used to do the comparison. If P4 is not specified then
  47232. ** memcmp() is used to compare text string. If both values are
  47233. ** numeric, then a numeric comparison is used. If the two values
  47234. ** are of different types, then numbers are considered less than
  47235. ** strings and strings are considered less than blobs.
  47236. **
  47237. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  47238. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  47239. */
  47240. /* Opcode: Ne P1 P2 P3 P4 P5
  47241. **
  47242. ** This works just like the Lt opcode except that the jump is taken if
  47243. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  47244. ** additional information.
  47245. */
  47246. /* Opcode: Eq P1 P2 P3 P4 P5
  47247. **
  47248. ** This works just like the Lt opcode except that the jump is taken if
  47249. ** the operands in registers P1 and P3 are equal.
  47250. ** See the Lt opcode for additional information.
  47251. */
  47252. /* Opcode: Le P1 P2 P3 P4 P5
  47253. **
  47254. ** This works just like the Lt opcode except that the jump is taken if
  47255. ** the content of register P3 is less than or equal to the content of
  47256. ** register P1. See the Lt opcode for additional information.
  47257. */
  47258. /* Opcode: Gt P1 P2 P3 P4 P5
  47259. **
  47260. ** This works just like the Lt opcode except that the jump is taken if
  47261. ** the content of register P3 is greater than the content of
  47262. ** register P1. See the Lt opcode for additional information.
  47263. */
  47264. /* Opcode: Ge P1 P2 P3 P4 P5
  47265. **
  47266. ** This works just like the Lt opcode except that the jump is taken if
  47267. ** the content of register P3 is greater than or equal to the content of
  47268. ** register P1. See the Lt opcode for additional information.
  47269. */
  47270. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  47271. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  47272. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  47273. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  47274. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  47275. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  47276. int flags;
  47277. int res;
  47278. char affinity;
  47279. flags = pIn1->flags|pIn3->flags;
  47280. if( flags&MEM_Null ){
  47281. /* If either operand is NULL then the result is always NULL.
  47282. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  47283. */
  47284. if( pOp->p5 & SQLITE_STOREP2 ){
  47285. pOut = &p->aMem[pOp->p2];
  47286. MemSetTypeFlag(pOut, MEM_Null);
  47287. REGISTER_TRACE(pOp->p2, pOut);
  47288. }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
  47289. pc = pOp->p2-1;
  47290. }
  47291. break;
  47292. }
  47293. affinity = pOp->p5 & SQLITE_AFF_MASK;
  47294. if( affinity ){
  47295. applyAffinity(pIn1, affinity, encoding);
  47296. applyAffinity(pIn3, affinity, encoding);
  47297. if( db->mallocFailed ) goto no_mem;
  47298. }
  47299. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  47300. ExpandBlob(pIn1);
  47301. ExpandBlob(pIn3);
  47302. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  47303. switch( pOp->opcode ){
  47304. case OP_Eq: res = res==0; break;
  47305. case OP_Ne: res = res!=0; break;
  47306. case OP_Lt: res = res<0; break;
  47307. case OP_Le: res = res<=0; break;
  47308. case OP_Gt: res = res>0; break;
  47309. default: res = res>=0; break;
  47310. }
  47311. if( pOp->p5 & SQLITE_STOREP2 ){
  47312. pOut = &p->aMem[pOp->p2];
  47313. MemSetTypeFlag(pOut, MEM_Int);
  47314. pOut->u.i = res;
  47315. REGISTER_TRACE(pOp->p2, pOut);
  47316. }else if( res ){
  47317. pc = pOp->p2-1;
  47318. }
  47319. break;
  47320. }
  47321. /* Opcode: Permutation * * * P4 *
  47322. **
  47323. ** Set the permuation used by the OP_Compare operator to be the array
  47324. ** of integers in P4.
  47325. **
  47326. ** The permutation is only valid until the next OP_Permutation, OP_Compare,
  47327. ** OP_Halt, or OP_ResultRow. Typically the OP_Permutation should occur
  47328. ** immediately prior to the OP_Compare.
  47329. */
  47330. case OP_Permutation: {
  47331. assert( pOp->p4type==P4_INTARRAY );
  47332. assert( pOp->p4.ai );
  47333. aPermute = pOp->p4.ai;
  47334. break;
  47335. }
  47336. /* Opcode: Compare P1 P2 P3 P4 *
  47337. **
  47338. ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
  47339. ** one "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  47340. ** the comparison for use by the next OP_Jump instruct.
  47341. **
  47342. ** P4 is a KeyInfo structure that defines collating sequences and sort
  47343. ** orders for the comparison. The permutation applies to registers
  47344. ** only. The KeyInfo elements are used sequentially.
  47345. **
  47346. ** The comparison is a sort comparison, so NULLs compare equal,
  47347. ** NULLs are less than numbers, numbers are less than strings,
  47348. ** and strings are less than blobs.
  47349. */
  47350. case OP_Compare: {
  47351. int n = pOp->p3;
  47352. int i, p1, p2;
  47353. const KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  47354. assert( n>0 );
  47355. assert( pKeyInfo!=0 );
  47356. p1 = pOp->p1;
  47357. assert( p1>0 && p1+n-1<p->nMem );
  47358. p2 = pOp->p2;
  47359. assert( p2>0 && p2+n-1<p->nMem );
  47360. for(i=0; i<n; i++){
  47361. int idx = aPermute ? aPermute[i] : i;
  47362. CollSeq *pColl; /* Collating sequence to use on this term */
  47363. int bRev; /* True for DESCENDING sort order */
  47364. REGISTER_TRACE(p1+idx, &p->aMem[p1+idx]);
  47365. REGISTER_TRACE(p2+idx, &p->aMem[p2+idx]);
  47366. assert( i<pKeyInfo->nField );
  47367. pColl = pKeyInfo->aColl[i];
  47368. bRev = pKeyInfo->aSortOrder[i];
  47369. iCompare = sqlite3MemCompare(&p->aMem[p1+idx], &p->aMem[p2+idx], pColl);
  47370. if( iCompare ){
  47371. if( bRev ) iCompare = -iCompare;
  47372. break;
  47373. }
  47374. }
  47375. aPermute = 0;
  47376. break;
  47377. }
  47378. /* Opcode: Jump P1 P2 P3 * *
  47379. **
  47380. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  47381. ** in the most recent OP_Compare instruction the P1 vector was less than
  47382. ** equal to, or greater than the P2 vector, respectively.
  47383. */
  47384. case OP_Jump: { /* jump */
  47385. if( iCompare<0 ){
  47386. pc = pOp->p1 - 1;
  47387. }else if( iCompare==0 ){
  47388. pc = pOp->p2 - 1;
  47389. }else{
  47390. pc = pOp->p3 - 1;
  47391. }
  47392. break;
  47393. }
  47394. /* Opcode: And P1 P2 P3 * *
  47395. **
  47396. ** Take the logical AND of the values in registers P1 and P2 and
  47397. ** write the result into register P3.
  47398. **
  47399. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  47400. ** the other input is NULL. A NULL and true or two NULLs give
  47401. ** a NULL output.
  47402. */
  47403. /* Opcode: Or P1 P2 P3 * *
  47404. **
  47405. ** Take the logical OR of the values in register P1 and P2 and
  47406. ** store the answer in register P3.
  47407. **
  47408. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  47409. ** even if the other input is NULL. A NULL and false or two NULLs
  47410. ** give a NULL output.
  47411. */
  47412. case OP_And: /* same as TK_AND, in1, in2, out3 */
  47413. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  47414. int v1, v2; /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  47415. if( pIn1->flags & MEM_Null ){
  47416. v1 = 2;
  47417. }else{
  47418. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  47419. }
  47420. if( pIn2->flags & MEM_Null ){
  47421. v2 = 2;
  47422. }else{
  47423. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  47424. }
  47425. if( pOp->opcode==OP_And ){
  47426. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  47427. v1 = and_logic[v1*3+v2];
  47428. }else{
  47429. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  47430. v1 = or_logic[v1*3+v2];
  47431. }
  47432. if( v1==2 ){
  47433. MemSetTypeFlag(pOut, MEM_Null);
  47434. }else{
  47435. pOut->u.i = v1;
  47436. MemSetTypeFlag(pOut, MEM_Int);
  47437. }
  47438. break;
  47439. }
  47440. /* Opcode: Not P1 P2 * * *
  47441. **
  47442. ** Interpret the value in register P1 as a boolean value. Store the
  47443. ** boolean complement in register P2. If the value in register P1 is
  47444. ** NULL, then a NULL is stored in P2.
  47445. */
  47446. case OP_Not: { /* same as TK_NOT, in1 */
  47447. pOut = &p->aMem[pOp->p2];
  47448. if( pIn1->flags & MEM_Null ){
  47449. sqlite3VdbeMemSetNull(pOut);
  47450. }else{
  47451. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  47452. }
  47453. break;
  47454. }
  47455. /* Opcode: BitNot P1 P2 * * *
  47456. **
  47457. ** Interpret the content of register P1 as an integer. Store the
  47458. ** ones-complement of the P1 value into register P2. If P1 holds
  47459. ** a NULL then store a NULL in P2.
  47460. */
  47461. case OP_BitNot: { /* same as TK_BITNOT, in1 */
  47462. pOut = &p->aMem[pOp->p2];
  47463. if( pIn1->flags & MEM_Null ){
  47464. sqlite3VdbeMemSetNull(pOut);
  47465. }else{
  47466. sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  47467. }
  47468. break;
  47469. }
  47470. /* Opcode: If P1 P2 P3 * *
  47471. **
  47472. ** Jump to P2 if the value in register P1 is true. The value is
  47473. ** is considered true if it is numeric and non-zero. If the value
  47474. ** in P1 is NULL then take the jump if P3 is true.
  47475. */
  47476. /* Opcode: IfNot P1 P2 P3 * *
  47477. **
  47478. ** Jump to P2 if the value in register P1 is False. The value is
  47479. ** is considered true if it has a numeric value of zero. If the value
  47480. ** in P1 is NULL then take the jump if P3 is true.
  47481. */
  47482. case OP_If: /* jump, in1 */
  47483. case OP_IfNot: { /* jump, in1 */
  47484. int c;
  47485. if( pIn1->flags & MEM_Null ){
  47486. c = pOp->p3;
  47487. }else{
  47488. #ifdef SQLITE_OMIT_FLOATING_POINT
  47489. c = sqlite3VdbeIntValue(pIn1);
  47490. #else
  47491. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  47492. #endif
  47493. if( pOp->opcode==OP_IfNot ) c = !c;
  47494. }
  47495. if( c ){
  47496. pc = pOp->p2-1;
  47497. }
  47498. break;
  47499. }
  47500. /* Opcode: IsNull P1 P2 P3 * *
  47501. **
  47502. ** Jump to P2 if the value in register P1 is NULL. If P3 is greater
  47503. ** than zero, then check all values reg(P1), reg(P1+1),
  47504. ** reg(P1+2), ..., reg(P1+P3-1).
  47505. */
  47506. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  47507. int n = pOp->p3;
  47508. assert( pOp->p3==0 || pOp->p1>0 );
  47509. do{
  47510. if( (pIn1->flags & MEM_Null)!=0 ){
  47511. pc = pOp->p2 - 1;
  47512. break;
  47513. }
  47514. pIn1++;
  47515. }while( --n > 0 );
  47516. break;
  47517. }
  47518. /* Opcode: NotNull P1 P2 * * *
  47519. **
  47520. ** Jump to P2 if the value in register P1 is not NULL.
  47521. */
  47522. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  47523. if( (pIn1->flags & MEM_Null)==0 ){
  47524. pc = pOp->p2 - 1;
  47525. }
  47526. break;
  47527. }
  47528. /* Opcode: SetNumColumns * P2 * * *
  47529. **
  47530. ** This opcode sets the number of columns for the cursor opened by the
  47531. ** following instruction to P2.
  47532. **
  47533. ** An OP_SetNumColumns is only useful if it occurs immediately before
  47534. ** one of the following opcodes:
  47535. **
  47536. ** OpenRead
  47537. ** OpenWrite
  47538. ** OpenPseudo
  47539. **
  47540. ** If the OP_Column opcode is to be executed on a cursor, then
  47541. ** this opcode must be present immediately before the opcode that
  47542. ** opens the cursor.
  47543. */
  47544. case OP_SetNumColumns: {
  47545. break;
  47546. }
  47547. /* Opcode: Column P1 P2 P3 P4 *
  47548. **
  47549. ** Interpret the data that cursor P1 points to as a structure built using
  47550. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  47551. ** information about the format of the data.) Extract the P2-th column
  47552. ** from this record. If there are less that (P2+1)
  47553. ** values in the record, extract a NULL.
  47554. **
  47555. ** The value extracted is stored in register P3.
  47556. **
  47557. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  47558. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  47559. ** the result.
  47560. */
  47561. case OP_Column: {
  47562. int payloadSize; /* Number of bytes in the record */
  47563. int p1 = pOp->p1; /* P1 value of the opcode */
  47564. int p2 = pOp->p2; /* column number to retrieve */
  47565. VdbeCursor *pC = 0;/* The VDBE cursor */
  47566. char *zRec; /* Pointer to complete record-data */
  47567. BtCursor *pCrsr; /* The BTree cursor */
  47568. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  47569. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  47570. int nField; /* number of fields in the record */
  47571. int len; /* The length of the serialized data for the column */
  47572. int i; /* Loop counter */
  47573. char *zData; /* Part of the record being decoded */
  47574. Mem *pDest; /* Where to write the extracted value */
  47575. Mem sMem; /* For storing the record being decoded */
  47576. memset(&sMem, 0, sizeof(sMem));
  47577. assert( p1<p->nCursor );
  47578. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  47579. pDest = &p->aMem[pOp->p3];
  47580. MemSetTypeFlag(pDest, MEM_Null);
  47581. /* This block sets the variable payloadSize to be the total number of
  47582. ** bytes in the record.
  47583. **
  47584. ** zRec is set to be the complete text of the record if it is available.
  47585. ** The complete record text is always available for pseudo-tables
  47586. ** If the record is stored in a cursor, the complete record text
  47587. ** might be available in the pC->aRow cache. Or it might not be.
  47588. ** If the data is unavailable, zRec is set to NULL.
  47589. **
  47590. ** We also compute the number of columns in the record. For cursors,
  47591. ** the number of columns is stored in the VdbeCursor.nField element.
  47592. */
  47593. pC = p->apCsr[p1];
  47594. assert( pC!=0 );
  47595. #ifndef SQLITE_OMIT_VIRTUALTABLE
  47596. assert( pC->pVtabCursor==0 );
  47597. #endif
  47598. if( pC->pCursor!=0 ){
  47599. /* The record is stored in a B-Tree */
  47600. rc = sqlite3VdbeCursorMoveto(pC);
  47601. if( rc ) goto abort_due_to_error;
  47602. zRec = 0;
  47603. pCrsr = pC->pCursor;
  47604. if( pC->nullRow ){
  47605. payloadSize = 0;
  47606. }else if( pC->cacheStatus==p->cacheCtr ){
  47607. payloadSize = pC->payloadSize;
  47608. zRec = (char*)pC->aRow;
  47609. }else if( pC->isIndex ){
  47610. i64 payloadSize64;
  47611. sqlite3BtreeKeySize(pCrsr, &payloadSize64);
  47612. payloadSize = (int)payloadSize64;
  47613. }else{
  47614. sqlite3BtreeDataSize(pCrsr, (u32 *)&payloadSize);
  47615. }
  47616. nField = pC->nField;
  47617. }else{
  47618. assert( pC->pseudoTable );
  47619. /* The record is the sole entry of a pseudo-table */
  47620. payloadSize = pC->nData;
  47621. zRec = pC->pData;
  47622. pC->cacheStatus = CACHE_STALE;
  47623. assert( payloadSize==0 || zRec!=0 );
  47624. nField = pC->nField;
  47625. pCrsr = 0;
  47626. }
  47627. /* If payloadSize is 0, then just store a NULL */
  47628. if( payloadSize==0 ){
  47629. assert( pDest->flags&MEM_Null );
  47630. goto op_column_out;
  47631. }
  47632. if( payloadSize>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  47633. goto too_big;
  47634. }
  47635. assert( p2<nField );
  47636. /* Read and parse the table header. Store the results of the parse
  47637. ** into the record header cache fields of the cursor.
  47638. */
  47639. aType = pC->aType;
  47640. if( pC->cacheStatus==p->cacheCtr ){
  47641. aOffset = pC->aOffset;
  47642. }else{
  47643. u8 *zIdx; /* Index into header */
  47644. u8 *zEndHdr; /* Pointer to first byte after the header */
  47645. int offset; /* Offset into the data */
  47646. int szHdrSz; /* Size of the header size field at start of record */
  47647. int avail = 0; /* Number of bytes of available data */
  47648. assert(aType);
  47649. pC->aOffset = aOffset = &aType[nField];
  47650. pC->payloadSize = payloadSize;
  47651. pC->cacheStatus = p->cacheCtr;
  47652. /* Figure out how many bytes are in the header */
  47653. if( zRec ){
  47654. zData = zRec;
  47655. }else{
  47656. if( pC->isIndex ){
  47657. zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
  47658. }else{
  47659. zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
  47660. }
  47661. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  47662. ** save the payload in the pC->aRow cache. That will save us from
  47663. ** having to make additional calls to fetch the content portion of
  47664. ** the record.
  47665. */
  47666. if( avail>=payloadSize ){
  47667. zRec = zData;
  47668. pC->aRow = (u8*)zData;
  47669. }else{
  47670. pC->aRow = 0;
  47671. }
  47672. }
  47673. /* The following assert is true in all cases accept when
  47674. ** the database file has been corrupted externally.
  47675. ** assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
  47676. szHdrSz = getVarint32((u8*)zData, offset);
  47677. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  47678. ** record header in most cases. But they will fail to get the complete
  47679. ** record header if the record header does not fit on a single page
  47680. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  47681. ** acquire the complete header text.
  47682. */
  47683. if( !zRec && avail<offset ){
  47684. sMem.flags = 0;
  47685. sMem.db = 0;
  47686. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
  47687. if( rc!=SQLITE_OK ){
  47688. goto op_column_out;
  47689. }
  47690. zData = sMem.z;
  47691. }
  47692. zEndHdr = (u8 *)&zData[offset];
  47693. zIdx = (u8 *)&zData[szHdrSz];
  47694. /* Scan the header and use it to fill in the aType[] and aOffset[]
  47695. ** arrays. aType[i] will contain the type integer for the i-th
  47696. ** column and aOffset[i] will contain the offset from the beginning
  47697. ** of the record to the start of the data for the i-th column
  47698. */
  47699. for(i=0; i<nField; i++){
  47700. if( zIdx<zEndHdr ){
  47701. aOffset[i] = offset;
  47702. zIdx += getVarint32(zIdx, aType[i]);
  47703. offset += sqlite3VdbeSerialTypeLen(aType[i]);
  47704. }else{
  47705. /* If i is less that nField, then there are less fields in this
  47706. ** record than SetNumColumns indicated there are columns in the
  47707. ** table. Set the offset for any extra columns not present in
  47708. ** the record to 0. This tells code below to store a NULL
  47709. ** instead of deserializing a value from the record.
  47710. */
  47711. aOffset[i] = 0;
  47712. }
  47713. }
  47714. sqlite3VdbeMemRelease(&sMem);
  47715. sMem.flags = MEM_Null;
  47716. /* If we have read more header data than was contained in the header,
  47717. ** or if the end of the last field appears to be past the end of the
  47718. ** record, or if the end of the last field appears to be before the end
  47719. ** of the record (when all fields present), then we must be dealing
  47720. ** with a corrupt database.
  47721. */
  47722. if( zIdx>zEndHdr || offset>payloadSize
  47723. || (zIdx==zEndHdr && offset!=payloadSize) ){
  47724. rc = SQLITE_CORRUPT_BKPT;
  47725. goto op_column_out;
  47726. }
  47727. }
  47728. /* Get the column information. If aOffset[p2] is non-zero, then
  47729. ** deserialize the value from the record. If aOffset[p2] is zero,
  47730. ** then there are not enough fields in the record to satisfy the
  47731. ** request. In this case, set the value NULL or to P4 if P4 is
  47732. ** a pointer to a Mem object.
  47733. */
  47734. if( aOffset[p2] ){
  47735. assert( rc==SQLITE_OK );
  47736. if( zRec ){
  47737. sqlite3VdbeMemReleaseExternal(pDest);
  47738. sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
  47739. }else{
  47740. len = sqlite3VdbeSerialTypeLen(aType[p2]);
  47741. sqlite3VdbeMemMove(&sMem, pDest);
  47742. rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
  47743. if( rc!=SQLITE_OK ){
  47744. goto op_column_out;
  47745. }
  47746. zData = sMem.z;
  47747. sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
  47748. }
  47749. pDest->enc = encoding;
  47750. }else{
  47751. if( pOp->p4type==P4_MEM ){
  47752. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  47753. }else{
  47754. assert( pDest->flags&MEM_Null );
  47755. }
  47756. }
  47757. /* If we dynamically allocated space to hold the data (in the
  47758. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  47759. ** dynamically allocated space over to the pDest structure.
  47760. ** This prevents a memory copy.
  47761. */
  47762. if( sMem.zMalloc ){
  47763. assert( sMem.z==sMem.zMalloc );
  47764. assert( !(pDest->flags & MEM_Dyn) );
  47765. assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
  47766. pDest->flags &= ~(MEM_Ephem|MEM_Static);
  47767. pDest->flags |= MEM_Term;
  47768. pDest->z = sMem.z;
  47769. pDest->zMalloc = sMem.zMalloc;
  47770. }
  47771. rc = sqlite3VdbeMemMakeWriteable(pDest);
  47772. op_column_out:
  47773. UPDATE_MAX_BLOBSIZE(pDest);
  47774. REGISTER_TRACE(pOp->p3, pDest);
  47775. break;
  47776. }
  47777. /* Opcode: Affinity P1 P2 * P4 *
  47778. **
  47779. ** Apply affinities to a range of P2 registers starting with P1.
  47780. **
  47781. ** P4 is a string that is P2 characters long. The nth character of the
  47782. ** string indicates the column affinity that should be used for the nth
  47783. ** memory cell in the range.
  47784. */
  47785. case OP_Affinity: {
  47786. char *zAffinity = pOp->p4.z;
  47787. Mem *pData0 = &p->aMem[pOp->p1];
  47788. Mem *pLast = &pData0[pOp->p2-1];
  47789. Mem *pRec;
  47790. for(pRec=pData0; pRec<=pLast; pRec++){
  47791. ExpandBlob(pRec);
  47792. applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
  47793. }
  47794. break;
  47795. }
  47796. /* Opcode: MakeRecord P1 P2 P3 P4 *
  47797. **
  47798. ** Convert P2 registers beginning with P1 into a single entry
  47799. ** suitable for use as a data record in a database table or as a key
  47800. ** in an index. The details of the format are irrelevant as long as
  47801. ** the OP_Column opcode can decode the record later.
  47802. ** Refer to source code comments for the details of the record
  47803. ** format.
  47804. **
  47805. ** P4 may be a string that is P2 characters long. The nth character of the
  47806. ** string indicates the column affinity that should be used for the nth
  47807. ** field of the index key.
  47808. **
  47809. ** The mapping from character to affinity is given by the SQLITE_AFF_
  47810. ** macros defined in sqliteInt.h.
  47811. **
  47812. ** If P4 is NULL then all index fields have the affinity NONE.
  47813. */
  47814. case OP_MakeRecord: {
  47815. /* Assuming the record contains N fields, the record format looks
  47816. ** like this:
  47817. **
  47818. ** ------------------------------------------------------------------------
  47819. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  47820. ** ------------------------------------------------------------------------
  47821. **
  47822. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  47823. ** and so froth.
  47824. **
  47825. ** Each type field is a varint representing the serial type of the
  47826. ** corresponding data element (see sqlite3VdbeSerialType()). The
  47827. ** hdr-size field is also a varint which is the offset from the beginning
  47828. ** of the record to data0.
  47829. */
  47830. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  47831. Mem *pRec; /* The new record */
  47832. u64 nData = 0; /* Number of bytes of data space */
  47833. int nHdr = 0; /* Number of bytes of header space */
  47834. i64 nByte = 0; /* Data space required for this record */
  47835. int nZero = 0; /* Number of zero bytes at the end of the record */
  47836. int nVarint; /* Number of bytes in a varint */
  47837. u32 serial_type; /* Type field */
  47838. Mem *pData0; /* First field to be combined into the record */
  47839. Mem *pLast; /* Last field of the record */
  47840. int nField; /* Number of fields in the record */
  47841. char *zAffinity; /* The affinity string for the record */
  47842. int file_format; /* File format to use for encoding */
  47843. int i; /* Space used in zNewRecord[] */
  47844. nField = pOp->p1;
  47845. zAffinity = pOp->p4.z;
  47846. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem );
  47847. pData0 = &p->aMem[nField];
  47848. nField = pOp->p2;
  47849. pLast = &pData0[nField-1];
  47850. file_format = p->minWriteFileFormat;
  47851. /* Loop through the elements that will make up the record to figure
  47852. ** out how much space is required for the new record.
  47853. */
  47854. for(pRec=pData0; pRec<=pLast; pRec++){
  47855. int len;
  47856. if( zAffinity ){
  47857. applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
  47858. }
  47859. if( pRec->flags&MEM_Zero && pRec->n>0 ){
  47860. sqlite3VdbeMemExpandBlob(pRec);
  47861. }
  47862. serial_type = sqlite3VdbeSerialType(pRec, file_format);
  47863. len = sqlite3VdbeSerialTypeLen(serial_type);
  47864. nData += len;
  47865. nHdr += sqlite3VarintLen(serial_type);
  47866. if( pRec->flags & MEM_Zero ){
  47867. /* Only pure zero-filled BLOBs can be input to this Opcode.
  47868. ** We do not allow blobs with a prefix and a zero-filled tail. */
  47869. nZero += pRec->u.nZero;
  47870. }else if( len ){
  47871. nZero = 0;
  47872. }
  47873. }
  47874. /* Add the initial header varint and total the size */
  47875. nHdr += nVarint = sqlite3VarintLen(nHdr);
  47876. if( nVarint<sqlite3VarintLen(nHdr) ){
  47877. nHdr++;
  47878. }
  47879. nByte = nHdr+nData-nZero;
  47880. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  47881. goto too_big;
  47882. }
  47883. /* Make sure the output register has a buffer large enough to store
  47884. ** the new record. The output register (pOp->p3) is not allowed to
  47885. ** be one of the input registers (because the following call to
  47886. ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  47887. */
  47888. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  47889. pOut = &p->aMem[pOp->p3];
  47890. if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){
  47891. goto no_mem;
  47892. }
  47893. zNewRecord = (u8 *)pOut->z;
  47894. /* Write the record */
  47895. i = putVarint32(zNewRecord, nHdr);
  47896. for(pRec=pData0; pRec<=pLast; pRec++){
  47897. serial_type = sqlite3VdbeSerialType(pRec, file_format);
  47898. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  47899. }
  47900. for(pRec=pData0; pRec<=pLast; pRec++){ /* serial data */
  47901. i += sqlite3VdbeSerialPut(&zNewRecord[i], (int)(nByte-i), pRec,file_format);
  47902. }
  47903. assert( i==nByte );
  47904. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  47905. pOut->n = (int)nByte;
  47906. pOut->flags = MEM_Blob | MEM_Dyn;
  47907. pOut->xDel = 0;
  47908. if( nZero ){
  47909. pOut->u.nZero = nZero;
  47910. pOut->flags |= MEM_Zero;
  47911. }
  47912. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  47913. REGISTER_TRACE(pOp->p3, pOut);
  47914. UPDATE_MAX_BLOBSIZE(pOut);
  47915. break;
  47916. }
  47917. /* Opcode: Statement P1 * * * *
  47918. **
  47919. ** Begin an individual statement transaction which is part of a larger
  47920. ** transaction. This is needed so that the statement
  47921. ** can be rolled back after an error without having to roll back the
  47922. ** entire transaction. The statement transaction will automatically
  47923. ** commit when the VDBE halts.
  47924. **
  47925. ** If the database connection is currently in autocommit mode (that
  47926. ** is to say, if it is in between BEGIN and COMMIT)
  47927. ** and if there are no other active statements on the same database
  47928. ** connection, then this operation is a no-op. No statement transaction
  47929. ** is needed since any error can use the normal ROLLBACK process to
  47930. ** undo changes.
  47931. **
  47932. ** If a statement transaction is started, then a statement journal file
  47933. ** will be allocated and initialized.
  47934. **
  47935. ** The statement is begun on the database file with index P1. The main
  47936. ** database file has an index of 0 and the file used for temporary tables
  47937. ** has an index of 1.
  47938. */
  47939. case OP_Statement: {
  47940. if( db->autoCommit==0 || db->activeVdbeCnt>1 ){
  47941. int i = pOp->p1;
  47942. Btree *pBt;
  47943. assert( i>=0 && i<db->nDb );
  47944. assert( db->aDb[i].pBt!=0 );
  47945. pBt = db->aDb[i].pBt;
  47946. assert( sqlite3BtreeIsInTrans(pBt) );
  47947. assert( (p->btreeMask & (1<<i))!=0 );
  47948. if( !sqlite3BtreeIsInStmt(pBt) ){
  47949. rc = sqlite3BtreeBeginStmt(pBt);
  47950. p->openedStatement = 1;
  47951. }
  47952. }
  47953. break;
  47954. }
  47955. /* Opcode: Savepoint P1 * * P4 *
  47956. **
  47957. ** Open, release or rollback the savepoint named by parameter P4, depending
  47958. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  47959. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  47960. */
  47961. case OP_Savepoint: {
  47962. int p1 = pOp->p1;
  47963. char *zName = pOp->p4.z; /* Name of savepoint */
  47964. /* Assert that the p1 parameter is valid. Also that if there is no open
  47965. ** transaction, then there cannot be any savepoints.
  47966. */
  47967. assert( db->pSavepoint==0 || db->autoCommit==0 );
  47968. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  47969. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  47970. assert( checkSavepointCount(db) );
  47971. if( p1==SAVEPOINT_BEGIN ){
  47972. if( db->writeVdbeCnt>0 ){
  47973. /* A new savepoint cannot be created if there are active write
  47974. ** statements (i.e. open read/write incremental blob handles).
  47975. */
  47976. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  47977. "SQL statements in progress");
  47978. rc = SQLITE_BUSY;
  47979. }else{
  47980. int nName = sqlite3Strlen30(zName);
  47981. Savepoint *pNew;
  47982. /* Create a new savepoint structure. */
  47983. pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
  47984. if( pNew ){
  47985. pNew->zName = (char *)&pNew[1];
  47986. memcpy(pNew->zName, zName, nName+1);
  47987. /* If there is no open transaction, then mark this as a special
  47988. ** "transaction savepoint". */
  47989. if( db->autoCommit ){
  47990. db->autoCommit = 0;
  47991. db->isTransactionSavepoint = 1;
  47992. }else{
  47993. db->nSavepoint++;
  47994. }
  47995. /* Link the new savepoint into the database handle's list. */
  47996. pNew->pNext = db->pSavepoint;
  47997. db->pSavepoint = pNew;
  47998. }
  47999. }
  48000. }else{
  48001. Savepoint *pSavepoint;
  48002. int iSavepoint = 0;
  48003. /* Find the named savepoint. If there is no such savepoint, then an
  48004. ** an error is returned to the user. */
  48005. for(
  48006. pSavepoint=db->pSavepoint;
  48007. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  48008. pSavepoint=pSavepoint->pNext
  48009. ){
  48010. iSavepoint++;
  48011. }
  48012. if( !pSavepoint ){
  48013. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
  48014. rc = SQLITE_ERROR;
  48015. }else if(
  48016. db->writeVdbeCnt>0 || (p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
  48017. ){
  48018. /* It is not possible to release (commit) a savepoint if there are
  48019. ** active write statements. It is not possible to rollback a savepoint
  48020. ** if there are any active statements at all.
  48021. */
  48022. sqlite3SetString(&p->zErrMsg, db,
  48023. "cannot %s savepoint - SQL statements in progress",
  48024. (p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
  48025. );
  48026. rc = SQLITE_BUSY;
  48027. }else{
  48028. /* Determine whether or not this is a transaction savepoint. If so,
  48029. ** and this is a RELEASE command, then the current transaction
  48030. ** is committed.
  48031. */
  48032. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  48033. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  48034. db->autoCommit = 1;
  48035. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  48036. p->pc = pc;
  48037. db->autoCommit = 0;
  48038. p->rc = rc = SQLITE_BUSY;
  48039. goto vdbe_return;
  48040. }
  48041. db->isTransactionSavepoint = 0;
  48042. rc = p->rc;
  48043. }else{
  48044. int ii;
  48045. iSavepoint = db->nSavepoint - iSavepoint - 1;
  48046. for(ii=0; ii<db->nDb; ii++){
  48047. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  48048. if( rc!=SQLITE_OK ){
  48049. goto abort_due_to_error;
  48050. }
  48051. }
  48052. if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  48053. sqlite3ExpirePreparedStatements(db);
  48054. sqlite3ResetInternalSchema(db, 0);
  48055. }
  48056. }
  48057. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  48058. ** savepoints nested inside of the savepoint being operated on. */
  48059. while( db->pSavepoint!=pSavepoint ){
  48060. Savepoint *pTmp = db->pSavepoint;
  48061. db->pSavepoint = pTmp->pNext;
  48062. sqlite3DbFree(db, pTmp);
  48063. db->nSavepoint--;
  48064. }
  48065. /* If it is a RELEASE, then destroy the savepoint being operated on too */
  48066. if( p1==SAVEPOINT_RELEASE ){
  48067. assert( pSavepoint==db->pSavepoint );
  48068. db->pSavepoint = pSavepoint->pNext;
  48069. sqlite3DbFree(db, pSavepoint);
  48070. if( !isTransaction ){
  48071. db->nSavepoint--;
  48072. }
  48073. }
  48074. }
  48075. }
  48076. break;
  48077. }
  48078. /* Opcode: AutoCommit P1 P2 * * *
  48079. **
  48080. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  48081. ** back any currently active btree transactions. If there are any active
  48082. ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
  48083. **
  48084. ** This instruction causes the VM to halt.
  48085. */
  48086. case OP_AutoCommit: {
  48087. int desiredAutoCommit = pOp->p1;
  48088. int rollback = pOp->p2;
  48089. int turnOnAC = desiredAutoCommit && !db->autoCommit;
  48090. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  48091. assert( desiredAutoCommit==1 || rollback==0 );
  48092. assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
  48093. if( turnOnAC && rollback && db->activeVdbeCnt>1 ){
  48094. /* If this instruction implements a ROLLBACK and other VMs are
  48095. ** still running, and a transaction is active, return an error indicating
  48096. ** that the other VMs must complete first.
  48097. */
  48098. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  48099. "SQL statements in progress");
  48100. rc = SQLITE_BUSY;
  48101. }else if( turnOnAC && !rollback && db->writeVdbeCnt>1 ){
  48102. /* If this instruction implements a COMMIT and other VMs are writing
  48103. ** return an error indicating that the other VMs must complete first.
  48104. */
  48105. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  48106. "SQL statements in progress");
  48107. rc = SQLITE_BUSY;
  48108. }else if( desiredAutoCommit!=db->autoCommit ){
  48109. if( rollback ){
  48110. assert( desiredAutoCommit==1 );
  48111. sqlite3RollbackAll(db);
  48112. db->autoCommit = 1;
  48113. }else{
  48114. db->autoCommit = (u8)desiredAutoCommit;
  48115. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  48116. p->pc = pc;
  48117. db->autoCommit = (u8)(1-desiredAutoCommit);
  48118. p->rc = rc = SQLITE_BUSY;
  48119. goto vdbe_return;
  48120. }
  48121. }
  48122. sqlite3CloseSavepoints(db);
  48123. if( p->rc==SQLITE_OK ){
  48124. rc = SQLITE_DONE;
  48125. }else{
  48126. rc = SQLITE_ERROR;
  48127. }
  48128. goto vdbe_return;
  48129. }else{
  48130. sqlite3SetString(&p->zErrMsg, db,
  48131. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  48132. (rollback)?"cannot rollback - no transaction is active":
  48133. "cannot commit - no transaction is active"));
  48134. rc = SQLITE_ERROR;
  48135. }
  48136. break;
  48137. }
  48138. /* Opcode: Transaction P1 P2 * * *
  48139. **
  48140. ** Begin a transaction. The transaction ends when a Commit or Rollback
  48141. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  48142. ** transaction might also be rolled back if an error is encountered.
  48143. **
  48144. ** P1 is the index of the database file on which the transaction is
  48145. ** started. Index 0 is the main database file and index 1 is the
  48146. ** file used for temporary tables. Indices of 2 or more are used for
  48147. ** attached databases.
  48148. **
  48149. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  48150. ** obtained on the database file when a write-transaction is started. No
  48151. ** other process can start another write transaction while this transaction is
  48152. ** underway. Starting a write transaction also creates a rollback journal. A
  48153. ** write transaction must be started before any changes can be made to the
  48154. ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
  48155. ** on the file.
  48156. **
  48157. ** If P2 is zero, then a read-lock is obtained on the database file.
  48158. */
  48159. case OP_Transaction: {
  48160. int i = pOp->p1;
  48161. Btree *pBt;
  48162. assert( i>=0 && i<db->nDb );
  48163. assert( (p->btreeMask & (1<<i))!=0 );
  48164. pBt = db->aDb[i].pBt;
  48165. if( pBt ){
  48166. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  48167. if( rc==SQLITE_BUSY ){
  48168. p->pc = pc;
  48169. p->rc = rc = SQLITE_BUSY;
  48170. goto vdbe_return;
  48171. }
  48172. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
  48173. goto abort_due_to_error;
  48174. }
  48175. }
  48176. break;
  48177. }
  48178. /* Opcode: ReadCookie P1 P2 P3 * *
  48179. **
  48180. ** Read cookie number P3 from database P1 and write it into register P2.
  48181. ** P3==0 is the schema version. P3==1 is the database format.
  48182. ** P3==2 is the recommended pager cache size, and so forth. P1==0 is
  48183. ** the main database file and P1==1 is the database file used to store
  48184. ** temporary tables.
  48185. **
  48186. ** If P1 is negative, then this is a request to read the size of a
  48187. ** databases free-list. P3 must be set to 1 in this case. The actual
  48188. ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
  48189. ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
  48190. **
  48191. ** There must be a read-lock on the database (either a transaction
  48192. ** must be started or there must be an open cursor) before
  48193. ** executing this instruction.
  48194. */
  48195. case OP_ReadCookie: { /* out2-prerelease */
  48196. int iMeta;
  48197. int iDb = pOp->p1;
  48198. int iCookie = pOp->p3;
  48199. assert( pOp->p3<SQLITE_N_BTREE_META );
  48200. if( iDb<0 ){
  48201. iDb = (-1*(iDb+1));
  48202. iCookie *= -1;
  48203. }
  48204. assert( iDb>=0 && iDb<db->nDb );
  48205. assert( db->aDb[iDb].pBt!=0 );
  48206. assert( (p->btreeMask & (1<<iDb))!=0 );
  48207. /* The indexing of meta values at the schema layer is off by one from
  48208. ** the indexing in the btree layer. The btree considers meta[0] to
  48209. ** be the number of free pages in the database (a read-only value)
  48210. ** and meta[1] to be the schema cookie. The schema layer considers
  48211. ** meta[1] to be the schema cookie. So we have to shift the index
  48212. ** by one in the following statement.
  48213. */
  48214. rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
  48215. pOut->u.i = iMeta;
  48216. MemSetTypeFlag(pOut, MEM_Int);
  48217. break;
  48218. }
  48219. /* Opcode: SetCookie P1 P2 P3 * *
  48220. **
  48221. ** Write the content of register P3 (interpreted as an integer)
  48222. ** into cookie number P2 of database P1.
  48223. ** P2==0 is the schema version. P2==1 is the database format.
  48224. ** P2==2 is the recommended pager cache size, and so forth. P1==0 is
  48225. ** the main database file and P1==1 is the database file used to store
  48226. ** temporary tables.
  48227. **
  48228. ** A transaction must be started before executing this opcode.
  48229. */
  48230. case OP_SetCookie: { /* in3 */
  48231. Db *pDb;
  48232. assert( pOp->p2<SQLITE_N_BTREE_META );
  48233. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  48234. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  48235. pDb = &db->aDb[pOp->p1];
  48236. assert( pDb->pBt!=0 );
  48237. sqlite3VdbeMemIntegerify(pIn3);
  48238. /* See note about index shifting on OP_ReadCookie */
  48239. rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i);
  48240. if( pOp->p2==0 ){
  48241. /* When the schema cookie changes, record the new cookie internally */
  48242. pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  48243. db->flags |= SQLITE_InternChanges;
  48244. }else if( pOp->p2==1 ){
  48245. /* Record changes in the file format */
  48246. pDb->pSchema->file_format = (u8)pIn3->u.i;
  48247. }
  48248. if( pOp->p1==1 ){
  48249. /* Invalidate all prepared statements whenever the TEMP database
  48250. ** schema is changed. Ticket #1644 */
  48251. sqlite3ExpirePreparedStatements(db);
  48252. }
  48253. break;
  48254. }
  48255. /* Opcode: VerifyCookie P1 P2 *
  48256. **
  48257. ** Check the value of global database parameter number 0 (the
  48258. ** schema version) and make sure it is equal to P2.
  48259. ** P1 is the database number which is 0 for the main database file
  48260. ** and 1 for the file holding temporary tables and some higher number
  48261. ** for auxiliary databases.
  48262. **
  48263. ** The cookie changes its value whenever the database schema changes.
  48264. ** This operation is used to detect when that the cookie has changed
  48265. ** and that the current process needs to reread the schema.
  48266. **
  48267. ** Either a transaction needs to have been started or an OP_Open needs
  48268. ** to be executed (to establish a read lock) before this opcode is
  48269. ** invoked.
  48270. */
  48271. case OP_VerifyCookie: {
  48272. int iMeta;
  48273. Btree *pBt;
  48274. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  48275. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  48276. pBt = db->aDb[pOp->p1].pBt;
  48277. if( pBt ){
  48278. rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
  48279. }else{
  48280. rc = SQLITE_OK;
  48281. iMeta = 0;
  48282. }
  48283. if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
  48284. sqlite3DbFree(db, p->zErrMsg);
  48285. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  48286. /* If the schema-cookie from the database file matches the cookie
  48287. ** stored with the in-memory representation of the schema, do
  48288. ** not reload the schema from the database file.
  48289. **
  48290. ** If virtual-tables are in use, this is not just an optimization.
  48291. ** Often, v-tables store their data in other SQLite tables, which
  48292. ** are queried from within xNext() and other v-table methods using
  48293. ** prepared queries. If such a query is out-of-date, we do not want to
  48294. ** discard the database schema, as the user code implementing the
  48295. ** v-table would have to be ready for the sqlite3_vtab structure itself
  48296. ** to be invalidated whenever sqlite3_step() is called from within
  48297. ** a v-table method.
  48298. */
  48299. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  48300. sqlite3ResetInternalSchema(db, pOp->p1);
  48301. }
  48302. sqlite3ExpirePreparedStatements(db);
  48303. rc = SQLITE_SCHEMA;
  48304. }
  48305. break;
  48306. }
  48307. /* Opcode: OpenRead P1 P2 P3 P4 P5
  48308. **
  48309. ** Open a read-only cursor for the database table whose root page is
  48310. ** P2 in a database file. The database file is determined by P3.
  48311. ** P3==0 means the main database, P3==1 means the database used for
  48312. ** temporary tables, and P3>1 means used the corresponding attached
  48313. ** database. Give the new cursor an identifier of P1. The P1
  48314. ** values need not be contiguous but all P1 values should be small integers.
  48315. ** It is an error for P1 to be negative.
  48316. **
  48317. ** If P5!=0 then use the content of register P2 as the root page, not
  48318. ** the value of P2 itself.
  48319. **
  48320. ** There will be a read lock on the database whenever there is an
  48321. ** open cursor. If the database was unlocked prior to this instruction
  48322. ** then a read lock is acquired as part of this instruction. A read
  48323. ** lock allows other processes to read the database but prohibits
  48324. ** any other process from modifying the database. The read lock is
  48325. ** released when all cursors are closed. If this instruction attempts
  48326. ** to get a read lock but fails, the script terminates with an
  48327. ** SQLITE_BUSY error code.
  48328. **
  48329. ** The P4 value is a pointer to a KeyInfo structure that defines the
  48330. ** content and collating sequence of indices. P4 is NULL for cursors
  48331. ** that are not pointing to indices.
  48332. **
  48333. ** See also OpenWrite.
  48334. */
  48335. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  48336. **
  48337. ** Open a read/write cursor named P1 on the table or index whose root
  48338. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  48339. ** root page.
  48340. **
  48341. ** The P4 value is a pointer to a KeyInfo structure that defines the
  48342. ** content and collating sequence of indices. P4 is NULL for cursors
  48343. ** that are not pointing to indices.
  48344. **
  48345. ** This instruction works just like OpenRead except that it opens the cursor
  48346. ** in read/write mode. For a given table, there can be one or more read-only
  48347. ** cursors or a single read/write cursor but not both.
  48348. **
  48349. ** See also OpenRead.
  48350. */
  48351. case OP_OpenRead:
  48352. case OP_OpenWrite: {
  48353. int i = pOp->p1;
  48354. int p2 = pOp->p2;
  48355. int iDb = pOp->p3;
  48356. int wrFlag;
  48357. Btree *pX;
  48358. VdbeCursor *pCur;
  48359. Db *pDb;
  48360. assert( iDb>=0 && iDb<db->nDb );
  48361. assert( (p->btreeMask & (1<<iDb))!=0 );
  48362. pDb = &db->aDb[iDb];
  48363. pX = pDb->pBt;
  48364. assert( pX!=0 );
  48365. if( pOp->opcode==OP_OpenWrite ){
  48366. wrFlag = 1;
  48367. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  48368. p->minWriteFileFormat = pDb->pSchema->file_format;
  48369. }
  48370. }else{
  48371. wrFlag = 0;
  48372. }
  48373. if( pOp->p5 ){
  48374. assert( p2>0 );
  48375. assert( p2<=p->nMem );
  48376. pIn2 = &p->aMem[p2];
  48377. sqlite3VdbeMemIntegerify(pIn2);
  48378. p2 = (int)pIn2->u.i;
  48379. if( p2<2 ) {
  48380. rc = SQLITE_CORRUPT_BKPT;
  48381. goto abort_due_to_error;
  48382. }
  48383. }
  48384. assert( i>=0 );
  48385. pCur = allocateCursor(p, i, &pOp[-1], iDb, 1);
  48386. if( pCur==0 ) goto no_mem;
  48387. pCur->nullRow = 1;
  48388. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pOp->p4.p, pCur->pCursor);
  48389. if( pOp->p4type==P4_KEYINFO ){
  48390. pCur->pKeyInfo = pOp->p4.pKeyInfo;
  48391. pCur->pKeyInfo->enc = ENC(p->db);
  48392. }else{
  48393. pCur->pKeyInfo = 0;
  48394. }
  48395. switch( rc ){
  48396. case SQLITE_BUSY: {
  48397. p->pc = pc;
  48398. p->rc = rc = SQLITE_BUSY;
  48399. goto vdbe_return;
  48400. }
  48401. case SQLITE_OK: {
  48402. int flags = sqlite3BtreeFlags(pCur->pCursor);
  48403. /* Sanity checking. Only the lower four bits of the flags byte should
  48404. ** be used. Bit 3 (mask 0x08) is unpredictable. The lower 3 bits
  48405. ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
  48406. ** 2 (zerodata for indices). If these conditions are not met it can
  48407. ** only mean that we are dealing with a corrupt database file
  48408. */
  48409. if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
  48410. rc = SQLITE_CORRUPT_BKPT;
  48411. goto abort_due_to_error;
  48412. }
  48413. pCur->isTable = (flags & BTREE_INTKEY)!=0 ?1:0;
  48414. pCur->isIndex = (flags & BTREE_ZERODATA)!=0 ?1:0;
  48415. /* If P4==0 it means we are expected to open a table. If P4!=0 then
  48416. ** we expect to be opening an index. If this is not what happened,
  48417. ** then the database is corrupt
  48418. */
  48419. if( (pCur->isTable && pOp->p4type==P4_KEYINFO)
  48420. || (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){
  48421. rc = SQLITE_CORRUPT_BKPT;
  48422. goto abort_due_to_error;
  48423. }
  48424. break;
  48425. }
  48426. case SQLITE_EMPTY: {
  48427. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  48428. pCur->isIndex = !pCur->isTable;
  48429. pCur->pCursor = 0;
  48430. rc = SQLITE_OK;
  48431. break;
  48432. }
  48433. default: {
  48434. goto abort_due_to_error;
  48435. }
  48436. }
  48437. break;
  48438. }
  48439. /* Opcode: OpenEphemeral P1 P2 * P4 *
  48440. **
  48441. ** Open a new cursor P1 to a transient table.
  48442. ** The cursor is always opened read/write even if
  48443. ** the main database is read-only. The transient or virtual
  48444. ** table is deleted automatically when the cursor is closed.
  48445. **
  48446. ** P2 is the number of columns in the virtual table.
  48447. ** The cursor points to a BTree table if P4==0 and to a BTree index
  48448. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  48449. ** that defines the format of keys in the index.
  48450. **
  48451. ** This opcode was once called OpenTemp. But that created
  48452. ** confusion because the term "temp table", might refer either
  48453. ** to a TEMP table at the SQL level, or to a table opened by
  48454. ** this opcode. Then this opcode was call OpenVirtual. But
  48455. ** that created confusion with the whole virtual-table idea.
  48456. */
  48457. case OP_OpenEphemeral: {
  48458. int i = pOp->p1;
  48459. VdbeCursor *pCx;
  48460. static const int openFlags =
  48461. SQLITE_OPEN_READWRITE |
  48462. SQLITE_OPEN_CREATE |
  48463. SQLITE_OPEN_EXCLUSIVE |
  48464. SQLITE_OPEN_DELETEONCLOSE |
  48465. SQLITE_OPEN_TRANSIENT_DB;
  48466. assert( i>=0 );
  48467. pCx = allocateCursor(p, i, pOp, -1, 1);
  48468. if( pCx==0 ) goto no_mem;
  48469. pCx->nullRow = 1;
  48470. rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
  48471. &pCx->pBt);
  48472. if( rc==SQLITE_OK ){
  48473. rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  48474. }
  48475. if( rc==SQLITE_OK ){
  48476. /* If a transient index is required, create it by calling
  48477. ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
  48478. ** opening it. If a transient table is required, just use the
  48479. ** automatically created table with root-page 1 (an INTKEY table).
  48480. */
  48481. if( pOp->p4.pKeyInfo ){
  48482. int pgno;
  48483. assert( pOp->p4type==P4_KEYINFO );
  48484. rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
  48485. if( rc==SQLITE_OK ){
  48486. assert( pgno==MASTER_ROOT+1 );
  48487. rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1,
  48488. (KeyInfo*)pOp->p4.z, pCx->pCursor);
  48489. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  48490. pCx->pKeyInfo->enc = ENC(p->db);
  48491. }
  48492. pCx->isTable = 0;
  48493. }else{
  48494. rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
  48495. pCx->isTable = 1;
  48496. }
  48497. }
  48498. pCx->isIndex = !pCx->isTable;
  48499. break;
  48500. }
  48501. /* Opcode: OpenPseudo P1 P2 * * *
  48502. **
  48503. ** Open a new cursor that points to a fake table that contains a single
  48504. ** row of data. Any attempt to write a second row of data causes the
  48505. ** first row to be deleted. All data is deleted when the cursor is
  48506. ** closed.
  48507. **
  48508. ** A pseudo-table created by this opcode is useful for holding the
  48509. ** NEW or OLD tables in a trigger. Also used to hold the a single
  48510. ** row output from the sorter so that the row can be decomposed into
  48511. ** individual columns using the OP_Column opcode.
  48512. **
  48513. ** When OP_Insert is executed to insert a row in to the pseudo table,
  48514. ** the pseudo-table cursor may or may not make it's own copy of the
  48515. ** original row data. If P2 is 0, then the pseudo-table will copy the
  48516. ** original row data. Otherwise, a pointer to the original memory cell
  48517. ** is stored. In this case, the vdbe program must ensure that the
  48518. ** memory cell containing the row data is not overwritten until the
  48519. ** pseudo table is closed (or a new row is inserted into it).
  48520. */
  48521. case OP_OpenPseudo: {
  48522. int i = pOp->p1;
  48523. VdbeCursor *pCx;
  48524. assert( i>=0 );
  48525. pCx = allocateCursor(p, i, &pOp[-1], -1, 0);
  48526. if( pCx==0 ) goto no_mem;
  48527. pCx->nullRow = 1;
  48528. pCx->pseudoTable = 1;
  48529. pCx->ephemPseudoTable = (u8)pOp->p2;
  48530. pCx->isTable = 1;
  48531. pCx->isIndex = 0;
  48532. break;
  48533. }
  48534. /* Opcode: Close P1 * * * *
  48535. **
  48536. ** Close a cursor previously opened as P1. If P1 is not
  48537. ** currently open, this instruction is a no-op.
  48538. */
  48539. case OP_Close: {
  48540. int i = pOp->p1;
  48541. assert( i>=0 && i<p->nCursor );
  48542. sqlite3VdbeFreeCursor(p, p->apCsr[i]);
  48543. p->apCsr[i] = 0;
  48544. break;
  48545. }
  48546. /* Opcode: SeekGe P1 P2 P3 P4 *
  48547. **
  48548. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  48549. ** use the value in register P3 as the key. If cursor P1 refers
  48550. ** to an SQL index, then P3 is the first in an array of P4 registers
  48551. ** that are used as an unpacked index key.
  48552. **
  48553. ** Reposition cursor P1 so that it points to the smallest entry that
  48554. ** is greater than or equal to the key value. If there are no records
  48555. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  48556. **
  48557. ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
  48558. */
  48559. /* Opcode: SeekGt P1 P2 P3 P4 *
  48560. **
  48561. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  48562. ** use the value in register P3 as a key. If cursor P1 refers
  48563. ** to an SQL index, then P3 is the first in an array of P4 registers
  48564. ** that are used as an unpacked index key.
  48565. **
  48566. ** Reposition cursor P1 so that it points to the smallest entry that
  48567. ** is greater than the key value. If there are no records greater than
  48568. ** the key and P2 is not zero, then jump to P2.
  48569. **
  48570. ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
  48571. */
  48572. /* Opcode: SeekLt P1 P2 P3 P4 *
  48573. **
  48574. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  48575. ** use the value in register P3 as a key. If cursor P1 refers
  48576. ** to an SQL index, then P3 is the first in an array of P4 registers
  48577. ** that are used as an unpacked index key.
  48578. **
  48579. ** Reposition cursor P1 so that it points to the largest entry that
  48580. ** is less than the key value. If there are no records less than
  48581. ** the key and P2 is not zero, then jump to P2.
  48582. **
  48583. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
  48584. */
  48585. /* Opcode: SeekLe P1 P2 P3 P4 *
  48586. **
  48587. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  48588. ** use the value in register P3 as a key. If cursor P1 refers
  48589. ** to an SQL index, then P3 is the first in an array of P4 registers
  48590. ** that are used as an unpacked index key.
  48591. **
  48592. ** Reposition cursor P1 so that it points to the largest entry that
  48593. ** is less than or equal to the key value. If there are no records
  48594. ** less than or equal to the key and P2 is not zero, then jump to P2.
  48595. **
  48596. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  48597. */
  48598. case OP_SeekLt: /* jump, in3 */
  48599. case OP_SeekLe: /* jump, in3 */
  48600. case OP_SeekGe: /* jump, in3 */
  48601. case OP_SeekGt: { /* jump, in3 */
  48602. int i = pOp->p1;
  48603. VdbeCursor *pC;
  48604. assert( i>=0 && i<p->nCursor );
  48605. assert( pOp->p2!=0 );
  48606. pC = p->apCsr[i];
  48607. assert( pC!=0 );
  48608. if( pC->pCursor!=0 ){
  48609. int res, oc;
  48610. oc = pOp->opcode;
  48611. pC->nullRow = 0;
  48612. if( pC->isTable ){
  48613. i64 iKey; /* The rowid we are to seek to */
  48614. /* The input value in P3 might be of any type: integer, real, string,
  48615. ** blob, or NULL. But it needs to be an integer before we can do
  48616. ** the seek, so covert it. */
  48617. applyNumericAffinity(pIn3);
  48618. iKey = sqlite3VdbeIntValue(pIn3);
  48619. pC->rowidIsValid = 0;
  48620. /* If the P3 value could not be converted into an integer without
  48621. ** loss of information, then special processing is required... */
  48622. if( (pIn3->flags & MEM_Int)==0 ){
  48623. if( (pIn3->flags & MEM_Real)==0 ){
  48624. /* If the P3 value cannot be converted into any kind of a number,
  48625. ** then the seek is not possible, so jump to P2 */
  48626. pc = pOp->p2 - 1;
  48627. break;
  48628. }
  48629. /* If we reach this point, then the P3 value must be a floating
  48630. ** point number. */
  48631. assert( (pIn3->flags & MEM_Real)!=0 );
  48632. if( iKey==SMALLEST_INT64 && (pIn3->r<(double)iKey || pIn3->r>0) ){
  48633. /* The P3 value is to large in magnitude to be expressed as an
  48634. ** integer. */
  48635. res = 1;
  48636. if( pIn3->r<0 ){
  48637. if( oc==OP_SeekGt || oc==OP_SeekGe ){
  48638. rc = sqlite3BtreeFirst(pC->pCursor, &res);
  48639. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  48640. }
  48641. }else{
  48642. if( oc==OP_SeekLt || oc==OP_SeekLe ){
  48643. rc = sqlite3BtreeLast(pC->pCursor, &res);
  48644. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  48645. }
  48646. }
  48647. if( res ){
  48648. pc = pOp->p2 - 1;
  48649. }
  48650. break;
  48651. }else if( oc==OP_SeekLt || oc==OP_SeekGe ){
  48652. /* Use the ceiling() function to convert real->int */
  48653. if( pIn3->r > (double)iKey ) iKey++;
  48654. }else{
  48655. /* Use the floor() function to convert real->int */
  48656. assert( oc==OP_SeekLe || oc==OP_SeekGt );
  48657. if( pIn3->r < (double)iKey ) iKey--;
  48658. }
  48659. }
  48660. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
  48661. if( rc!=SQLITE_OK ){
  48662. goto abort_due_to_error;
  48663. }
  48664. if( res==0 ){
  48665. pC->rowidIsValid = 1;
  48666. pC->lastRowid = iKey;
  48667. }
  48668. }else{
  48669. UnpackedRecord r;
  48670. int nField = pOp->p4.i;
  48671. assert( pOp->p4type==P4_INT32 );
  48672. assert( nField>0 );
  48673. r.pKeyInfo = pC->pKeyInfo;
  48674. r.nField = (u16)nField;
  48675. if( oc==OP_SeekGt || oc==OP_SeekLe ){
  48676. r.flags = UNPACKED_INCRKEY;
  48677. }else{
  48678. r.flags = 0;
  48679. }
  48680. r.aMem = &p->aMem[pOp->p3];
  48681. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
  48682. if( rc!=SQLITE_OK ){
  48683. goto abort_due_to_error;
  48684. }
  48685. pC->rowidIsValid = 0;
  48686. }
  48687. pC->deferredMoveto = 0;
  48688. pC->cacheStatus = CACHE_STALE;
  48689. #ifdef SQLITE_TEST
  48690. sqlite3_search_count++;
  48691. #endif
  48692. if( oc==OP_SeekGe || oc==OP_SeekGt ){
  48693. if( res<0 || (res==0 && oc==OP_SeekGt) ){
  48694. rc = sqlite3BtreeNext(pC->pCursor, &res);
  48695. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  48696. pC->rowidIsValid = 0;
  48697. }else{
  48698. res = 0;
  48699. }
  48700. }else{
  48701. assert( oc==OP_SeekLt || oc==OP_SeekLe );
  48702. if( res>0 || (res==0 && oc==OP_SeekLt) ){
  48703. rc = sqlite3BtreePrevious(pC->pCursor, &res);
  48704. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  48705. pC->rowidIsValid = 0;
  48706. }else{
  48707. /* res might be negative because the table is empty. Check to
  48708. ** see if this is the case.
  48709. */
  48710. res = sqlite3BtreeEof(pC->pCursor);
  48711. }
  48712. }
  48713. assert( pOp->p2>0 );
  48714. if( res ){
  48715. pc = pOp->p2 - 1;
  48716. }
  48717. }else if( !pC->pseudoTable ){
  48718. /* This happens when attempting to open the sqlite3_master table
  48719. ** for read access returns SQLITE_EMPTY. In this case always
  48720. ** take the jump (since there are no records in the table).
  48721. */
  48722. pc = pOp->p2 - 1;
  48723. }
  48724. break;
  48725. }
  48726. /* Opcode: Seek P1 P2 * * *
  48727. **
  48728. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  48729. ** for P1 to move so that it points to the rowid given by P2.
  48730. **
  48731. ** This is actually a deferred seek. Nothing actually happens until
  48732. ** the cursor is used to read a record. That way, if no reads
  48733. ** occur, no unnecessary I/O happens.
  48734. */
  48735. case OP_Seek: { /* in2 */
  48736. int i = pOp->p1;
  48737. VdbeCursor *pC;
  48738. assert( i>=0 && i<p->nCursor );
  48739. pC = p->apCsr[i];
  48740. assert( pC!=0 );
  48741. if( pC->pCursor!=0 ){
  48742. assert( pC->isTable );
  48743. pC->nullRow = 0;
  48744. pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  48745. pC->rowidIsValid = 0;
  48746. pC->deferredMoveto = 1;
  48747. }
  48748. break;
  48749. }
  48750. /* Opcode: Found P1 P2 P3 * *
  48751. **
  48752. ** Register P3 holds a blob constructed by MakeRecord. P1 is an index.
  48753. ** If an entry that matches the value in register p3 exists in P1 then
  48754. ** jump to P2. If the P3 value does not match any entry in P1
  48755. ** then fall thru. The P1 cursor is left pointing at the matching entry
  48756. ** if it exists.
  48757. **
  48758. ** This instruction is used to implement the IN operator where the
  48759. ** left-hand side is a SELECT statement. P1 may be a true index, or it
  48760. ** may be a temporary index that holds the results of the SELECT
  48761. ** statement. This instruction is also used to implement the
  48762. ** DISTINCT keyword in SELECT statements.
  48763. **
  48764. ** This instruction checks if index P1 contains a record for which
  48765. ** the first N serialized values exactly match the N serialized values
  48766. ** in the record in register P3, where N is the total number of values in
  48767. ** the P3 record (the P3 record is a prefix of the P1 record).
  48768. **
  48769. ** See also: NotFound, IsUnique, NotExists
  48770. */
  48771. /* Opcode: NotFound P1 P2 P3 * *
  48772. **
  48773. ** Register P3 holds a blob constructed by MakeRecord. P1 is
  48774. ** an index. If no entry exists in P1 that matches the blob then jump
  48775. ** to P2. If an entry does existing, fall through. The cursor is left
  48776. ** pointing to the entry that matches.
  48777. **
  48778. ** See also: Found, NotExists, IsUnique
  48779. */
  48780. case OP_NotFound: /* jump, in3 */
  48781. case OP_Found: { /* jump, in3 */
  48782. int i = pOp->p1;
  48783. int alreadyExists = 0;
  48784. VdbeCursor *pC;
  48785. assert( i>=0 && i<p->nCursor );
  48786. assert( p->apCsr[i]!=0 );
  48787. if( (pC = p->apCsr[i])->pCursor!=0 ){
  48788. int res;
  48789. UnpackedRecord *pIdxKey;
  48790. assert( pC->isTable==0 );
  48791. assert( pIn3->flags & MEM_Blob );
  48792. pIdxKey = sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z,
  48793. aTempRec, sizeof(aTempRec));
  48794. if( pIdxKey==0 ){
  48795. goto no_mem;
  48796. }
  48797. if( pOp->opcode==OP_Found ){
  48798. pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  48799. }
  48800. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
  48801. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  48802. if( rc!=SQLITE_OK ){
  48803. break;
  48804. }
  48805. alreadyExists = (res==0);
  48806. pC->deferredMoveto = 0;
  48807. pC->cacheStatus = CACHE_STALE;
  48808. }
  48809. if( pOp->opcode==OP_Found ){
  48810. if( alreadyExists ) pc = pOp->p2 - 1;
  48811. }else{
  48812. if( !alreadyExists ) pc = pOp->p2 - 1;
  48813. }
  48814. break;
  48815. }
  48816. /* Opcode: IsUnique P1 P2 P3 P4 *
  48817. **
  48818. ** The P3 register contains an integer record number. Call this
  48819. ** record number R. The P4 register contains an index key created
  48820. ** using MakeRecord. Call it K.
  48821. **
  48822. ** P1 is an index. So it has no data and its key consists of a
  48823. ** record generated by OP_MakeRecord where the last field is the
  48824. ** rowid of the entry that the index refers to.
  48825. **
  48826. ** This instruction asks if there is an entry in P1 where the
  48827. ** fields matches K but the rowid is different from R.
  48828. ** If there is no such entry, then there is an immediate
  48829. ** jump to P2. If any entry does exist where the index string
  48830. ** matches K but the record number is not R, then the record
  48831. ** number for that entry is written into P3 and control
  48832. ** falls through to the next instruction.
  48833. **
  48834. ** See also: NotFound, NotExists, Found
  48835. */
  48836. case OP_IsUnique: { /* jump, in3 */
  48837. int i = pOp->p1;
  48838. VdbeCursor *pCx;
  48839. BtCursor *pCrsr;
  48840. Mem *pK;
  48841. i64 R;
  48842. /* Pop the value R off the top of the stack
  48843. */
  48844. assert( pOp->p4type==P4_INT32 );
  48845. assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
  48846. pK = &p->aMem[pOp->p4.i];
  48847. sqlite3VdbeMemIntegerify(pIn3);
  48848. R = pIn3->u.i;
  48849. assert( i>=0 && i<p->nCursor );
  48850. pCx = p->apCsr[i];
  48851. assert( pCx!=0 );
  48852. pCrsr = pCx->pCursor;
  48853. if( pCrsr!=0 ){
  48854. int res;
  48855. i64 v; /* The record number that matches K */
  48856. UnpackedRecord *pIdxKey; /* Unpacked version of P4 */
  48857. /* Make sure K is a string and make zKey point to K
  48858. */
  48859. assert( pK->flags & MEM_Blob );
  48860. pIdxKey = sqlite3VdbeRecordUnpack(pCx->pKeyInfo, pK->n, pK->z,
  48861. aTempRec, sizeof(aTempRec));
  48862. if( pIdxKey==0 ){
  48863. goto no_mem;
  48864. }
  48865. pIdxKey->flags |= UNPACKED_IGNORE_ROWID;
  48866. /* Search for an entry in P1 where all but the last rowid match K
  48867. ** If there is no such entry, jump immediately to P2.
  48868. */
  48869. assert( pCx->deferredMoveto==0 );
  48870. pCx->cacheStatus = CACHE_STALE;
  48871. rc = sqlite3BtreeMovetoUnpacked(pCrsr, pIdxKey, 0, 0, &res);
  48872. if( rc!=SQLITE_OK ){
  48873. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  48874. goto abort_due_to_error;
  48875. }
  48876. if( res<0 ){
  48877. rc = sqlite3BtreeNext(pCrsr, &res);
  48878. if( res ){
  48879. pc = pOp->p2 - 1;
  48880. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  48881. break;
  48882. }
  48883. }
  48884. rc = sqlite3VdbeIdxKeyCompare(pCx, pIdxKey, &res);
  48885. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  48886. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  48887. if( res>0 ){
  48888. pc = pOp->p2 - 1;
  48889. break;
  48890. }
  48891. /* At this point, pCrsr is pointing to an entry in P1 where all but
  48892. ** the final entry (the rowid) matches K. Check to see if the
  48893. ** final rowid column is different from R. If it equals R then jump
  48894. ** immediately to P2.
  48895. */
  48896. rc = sqlite3VdbeIdxRowid(pCrsr, &v);
  48897. if( rc!=SQLITE_OK ){
  48898. goto abort_due_to_error;
  48899. }
  48900. if( v==R ){
  48901. pc = pOp->p2 - 1;
  48902. break;
  48903. }
  48904. /* The final varint of the key is different from R. Store it back
  48905. ** into register R3. (The record number of an entry that violates
  48906. ** a UNIQUE constraint.)
  48907. */
  48908. pIn3->u.i = v;
  48909. assert( pIn3->flags&MEM_Int );
  48910. }
  48911. break;
  48912. }
  48913. /* Opcode: NotExists P1 P2 P3 * *
  48914. **
  48915. ** Use the content of register P3 as a integer key. If a record
  48916. ** with that key does not exist in table of P1, then jump to P2.
  48917. ** If the record does exist, then fall thru. The cursor is left
  48918. ** pointing to the record if it exists.
  48919. **
  48920. ** The difference between this operation and NotFound is that this
  48921. ** operation assumes the key is an integer and that P1 is a table whereas
  48922. ** NotFound assumes key is a blob constructed from MakeRecord and
  48923. ** P1 is an index.
  48924. **
  48925. ** See also: Found, NotFound, IsUnique
  48926. */
  48927. case OP_NotExists: { /* jump, in3 */
  48928. int i = pOp->p1;
  48929. VdbeCursor *pC;
  48930. BtCursor *pCrsr;
  48931. assert( i>=0 && i<p->nCursor );
  48932. assert( p->apCsr[i]!=0 );
  48933. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  48934. int res = 0;
  48935. u64 iKey;
  48936. assert( pIn3->flags & MEM_Int );
  48937. assert( p->apCsr[i]->isTable );
  48938. iKey = intToKey(pIn3->u.i);
  48939. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0,&res);
  48940. pC->lastRowid = pIn3->u.i;
  48941. pC->rowidIsValid = res==0 ?1:0;
  48942. pC->nullRow = 0;
  48943. pC->cacheStatus = CACHE_STALE;
  48944. if( res!=0 ){
  48945. pc = pOp->p2 - 1;
  48946. assert( pC->rowidIsValid==0 );
  48947. }
  48948. }else if( !pC->pseudoTable ){
  48949. /* This happens when an attempt to open a read cursor on the
  48950. ** sqlite_master table returns SQLITE_EMPTY.
  48951. */
  48952. assert( pC->isTable );
  48953. pc = pOp->p2 - 1;
  48954. assert( pC->rowidIsValid==0 );
  48955. }
  48956. break;
  48957. }
  48958. /* Opcode: Sequence P1 P2 * * *
  48959. **
  48960. ** Find the next available sequence number for cursor P1.
  48961. ** Write the sequence number into register P2.
  48962. ** The sequence number on the cursor is incremented after this
  48963. ** instruction.
  48964. */
  48965. case OP_Sequence: { /* out2-prerelease */
  48966. int i = pOp->p1;
  48967. assert( i>=0 && i<p->nCursor );
  48968. assert( p->apCsr[i]!=0 );
  48969. pOut->u.i = p->apCsr[i]->seqCount++;
  48970. MemSetTypeFlag(pOut, MEM_Int);
  48971. break;
  48972. }
  48973. /* Opcode: NewRowid P1 P2 P3 * *
  48974. **
  48975. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  48976. ** The record number is not previously used as a key in the database
  48977. ** table that cursor P1 points to. The new record number is written
  48978. ** written to register P2.
  48979. **
  48980. ** If P3>0 then P3 is a register that holds the largest previously
  48981. ** generated record number. No new record numbers are allowed to be less
  48982. ** than this value. When this value reaches its maximum, a SQLITE_FULL
  48983. ** error is generated. The P3 register is updated with the generated
  48984. ** record number. This P3 mechanism is used to help implement the
  48985. ** AUTOINCREMENT feature.
  48986. */
  48987. case OP_NewRowid: { /* out2-prerelease */
  48988. int i = pOp->p1;
  48989. i64 v = 0;
  48990. VdbeCursor *pC;
  48991. assert( i>=0 && i<p->nCursor );
  48992. assert( p->apCsr[i]!=0 );
  48993. if( (pC = p->apCsr[i])->pCursor==0 ){
  48994. /* The zero initialization above is all that is needed */
  48995. }else{
  48996. /* The next rowid or record number (different terms for the same
  48997. ** thing) is obtained in a two-step algorithm.
  48998. **
  48999. ** First we attempt to find the largest existing rowid and add one
  49000. ** to that. But if the largest existing rowid is already the maximum
  49001. ** positive integer, we have to fall through to the second
  49002. ** probabilistic algorithm
  49003. **
  49004. ** The second algorithm is to select a rowid at random and see if
  49005. ** it already exists in the table. If it does not exist, we have
  49006. ** succeeded. If the random rowid does exist, we select a new one
  49007. ** and try again, up to 1000 times.
  49008. **
  49009. ** For a table with less than 2 billion entries, the probability
  49010. ** of not finding a unused rowid is about 1.0e-300. This is a
  49011. ** non-zero probability, but it is still vanishingly small and should
  49012. ** never cause a problem. You are much, much more likely to have a
  49013. ** hardware failure than for this algorithm to fail.
  49014. **
  49015. ** The analysis in the previous paragraph assumes that you have a good
  49016. ** source of random numbers. Is a library function like lrand48()
  49017. ** good enough? Maybe. Maybe not. It's hard to know whether there
  49018. ** might be subtle bugs is some implementations of lrand48() that
  49019. ** could cause problems. To avoid uncertainty, SQLite uses its own
  49020. ** random number generator based on the RC4 algorithm.
  49021. **
  49022. ** To promote locality of reference for repetitive inserts, the
  49023. ** first few attempts at choosing a random rowid pick values just a little
  49024. ** larger than the previous rowid. This has been shown experimentally
  49025. ** to double the speed of the COPY operation.
  49026. */
  49027. int res, rx=SQLITE_OK, cnt;
  49028. i64 x;
  49029. cnt = 0;
  49030. if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
  49031. BTREE_INTKEY ){
  49032. rc = SQLITE_CORRUPT_BKPT;
  49033. goto abort_due_to_error;
  49034. }
  49035. assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
  49036. assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
  49037. #ifdef SQLITE_32BIT_ROWID
  49038. # define MAX_ROWID 0x7fffffff
  49039. #else
  49040. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  49041. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  49042. ** to provide the constant while making all compilers happy.
  49043. */
  49044. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  49045. #endif
  49046. if( !pC->useRandomRowid ){
  49047. if( pC->nextRowidValid ){
  49048. v = pC->nextRowid;
  49049. }else{
  49050. rc = sqlite3BtreeLast(pC->pCursor, &res);
  49051. if( rc!=SQLITE_OK ){
  49052. goto abort_due_to_error;
  49053. }
  49054. if( res ){
  49055. v = 1;
  49056. }else{
  49057. sqlite3BtreeKeySize(pC->pCursor, &v);
  49058. v = keyToInt(v);
  49059. if( v==MAX_ROWID ){
  49060. pC->useRandomRowid = 1;
  49061. }else{
  49062. v++;
  49063. }
  49064. }
  49065. }
  49066. #ifndef SQLITE_OMIT_AUTOINCREMENT
  49067. if( pOp->p3 ){
  49068. Mem *pMem;
  49069. assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
  49070. pMem = &p->aMem[pOp->p3];
  49071. REGISTER_TRACE(pOp->p3, pMem);
  49072. sqlite3VdbeMemIntegerify(pMem);
  49073. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  49074. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  49075. rc = SQLITE_FULL;
  49076. goto abort_due_to_error;
  49077. }
  49078. if( v<pMem->u.i+1 ){
  49079. v = pMem->u.i + 1;
  49080. }
  49081. pMem->u.i = v;
  49082. }
  49083. #endif
  49084. if( v<MAX_ROWID ){
  49085. pC->nextRowidValid = 1;
  49086. pC->nextRowid = v+1;
  49087. }else{
  49088. pC->nextRowidValid = 0;
  49089. }
  49090. }
  49091. if( pC->useRandomRowid ){
  49092. assert( pOp->p3==0 ); /* SQLITE_FULL must have occurred prior to this */
  49093. v = db->priorNewRowid;
  49094. cnt = 0;
  49095. do{
  49096. if( cnt==0 && (v&0xffffff)==v ){
  49097. v++;
  49098. }else{
  49099. sqlite3_randomness(sizeof(v), &v);
  49100. if( cnt<5 ) v &= 0xffffff;
  49101. }
  49102. if( v==0 ) continue;
  49103. x = intToKey(v);
  49104. rx = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)x, 0, &res);
  49105. cnt++;
  49106. }while( cnt<100 && rx==SQLITE_OK && res==0 );
  49107. db->priorNewRowid = v;
  49108. if( rx==SQLITE_OK && res==0 ){
  49109. rc = SQLITE_FULL;
  49110. goto abort_due_to_error;
  49111. }
  49112. }
  49113. pC->rowidIsValid = 0;
  49114. pC->deferredMoveto = 0;
  49115. pC->cacheStatus = CACHE_STALE;
  49116. }
  49117. MemSetTypeFlag(pOut, MEM_Int);
  49118. pOut->u.i = v;
  49119. break;
  49120. }
  49121. /* Opcode: Insert P1 P2 P3 P4 P5
  49122. **
  49123. ** Write an entry into the table of cursor P1. A new entry is
  49124. ** created if it doesn't already exist or the data for an existing
  49125. ** entry is overwritten. The data is the value stored register
  49126. ** number P2. The key is stored in register P3. The key must
  49127. ** be an integer.
  49128. **
  49129. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  49130. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  49131. ** then rowid is stored for subsequent return by the
  49132. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  49133. **
  49134. ** Parameter P4 may point to a string containing the table-name, or
  49135. ** may be NULL. If it is not NULL, then the update-hook
  49136. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  49137. **
  49138. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  49139. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  49140. ** and register P2 becomes ephemeral. If the cursor is changed, the
  49141. ** value of register P2 will then change. Make sure this does not
  49142. ** cause any problems.)
  49143. **
  49144. ** This instruction only works on tables. The equivalent instruction
  49145. ** for indices is OP_IdxInsert.
  49146. */
  49147. case OP_Insert: {
  49148. Mem *pData = &p->aMem[pOp->p2];
  49149. Mem *pKey = &p->aMem[pOp->p3];
  49150. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  49151. int i = pOp->p1;
  49152. VdbeCursor *pC;
  49153. assert( i>=0 && i<p->nCursor );
  49154. pC = p->apCsr[i];
  49155. assert( pC!=0 );
  49156. assert( pC->pCursor!=0 || pC->pseudoTable );
  49157. assert( pKey->flags & MEM_Int );
  49158. assert( pC->isTable );
  49159. REGISTER_TRACE(pOp->p2, pData);
  49160. REGISTER_TRACE(pOp->p3, pKey);
  49161. iKey = intToKey(pKey->u.i);
  49162. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  49163. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i;
  49164. if( pC->nextRowidValid && pKey->u.i>=pC->nextRowid ){
  49165. pC->nextRowidValid = 0;
  49166. }
  49167. if( pData->flags & MEM_Null ){
  49168. pData->z = 0;
  49169. pData->n = 0;
  49170. }else{
  49171. assert( pData->flags & (MEM_Blob|MEM_Str) );
  49172. }
  49173. if( pC->pseudoTable ){
  49174. if( !pC->ephemPseudoTable ){
  49175. sqlite3DbFree(db, pC->pData);
  49176. }
  49177. pC->iKey = iKey;
  49178. pC->nData = pData->n;
  49179. if( pData->z==pData->zMalloc || pC->ephemPseudoTable ){
  49180. pC->pData = pData->z;
  49181. if( !pC->ephemPseudoTable ){
  49182. pData->flags &= ~MEM_Dyn;
  49183. pData->flags |= MEM_Ephem;
  49184. pData->zMalloc = 0;
  49185. }
  49186. }else{
  49187. pC->pData = sqlite3Malloc( pC->nData+2 );
  49188. if( !pC->pData ) goto no_mem;
  49189. memcpy(pC->pData, pData->z, pC->nData);
  49190. pC->pData[pC->nData] = 0;
  49191. pC->pData[pC->nData+1] = 0;
  49192. }
  49193. pC->nullRow = 0;
  49194. }else{
  49195. int nZero;
  49196. if( pData->flags & MEM_Zero ){
  49197. nZero = pData->u.nZero;
  49198. }else{
  49199. nZero = 0;
  49200. }
  49201. rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
  49202. pData->z, pData->n, nZero,
  49203. pOp->p5 & OPFLAG_APPEND);
  49204. }
  49205. pC->rowidIsValid = 0;
  49206. pC->deferredMoveto = 0;
  49207. pC->cacheStatus = CACHE_STALE;
  49208. /* Invoke the update-hook if required. */
  49209. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  49210. const char *zDb = db->aDb[pC->iDb].zName;
  49211. const char *zTbl = pOp->p4.z;
  49212. int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  49213. assert( pC->isTable );
  49214. db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
  49215. assert( pC->iDb>=0 );
  49216. }
  49217. break;
  49218. }
  49219. /* Opcode: Delete P1 P2 * P4 *
  49220. **
  49221. ** Delete the record at which the P1 cursor is currently pointing.
  49222. **
  49223. ** The cursor will be left pointing at either the next or the previous
  49224. ** record in the table. If it is left pointing at the next record, then
  49225. ** the next Next instruction will be a no-op. Hence it is OK to delete
  49226. ** a record from within an Next loop.
  49227. **
  49228. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  49229. ** incremented (otherwise not).
  49230. **
  49231. ** P1 must not be pseudo-table. It has to be a real table with
  49232. ** multiple rows.
  49233. **
  49234. ** If P4 is not NULL, then it is the name of the table that P1 is
  49235. ** pointing to. The update hook will be invoked, if it exists.
  49236. ** If P4 is not NULL then the P1 cursor must have been positioned
  49237. ** using OP_NotFound prior to invoking this opcode.
  49238. */
  49239. case OP_Delete: {
  49240. int i = pOp->p1;
  49241. i64 iKey;
  49242. VdbeCursor *pC;
  49243. assert( i>=0 && i<p->nCursor );
  49244. pC = p->apCsr[i];
  49245. assert( pC!=0 );
  49246. assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  49247. /* If the update-hook will be invoked, set iKey to the rowid of the
  49248. ** row being deleted.
  49249. */
  49250. if( db->xUpdateCallback && pOp->p4.z ){
  49251. assert( pC->isTable );
  49252. assert( pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
  49253. iKey = pC->lastRowid;
  49254. }
  49255. rc = sqlite3VdbeCursorMoveto(pC);
  49256. if( rc ) goto abort_due_to_error;
  49257. rc = sqlite3BtreeDelete(pC->pCursor);
  49258. pC->nextRowidValid = 0;
  49259. pC->cacheStatus = CACHE_STALE;
  49260. /* Invoke the update-hook if required. */
  49261. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  49262. const char *zDb = db->aDb[pC->iDb].zName;
  49263. const char *zTbl = pOp->p4.z;
  49264. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
  49265. assert( pC->iDb>=0 );
  49266. }
  49267. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  49268. break;
  49269. }
  49270. /* Opcode: ResetCount P1 * *
  49271. **
  49272. ** This opcode resets the VMs internal change counter to 0. If P1 is true,
  49273. ** then the value of the change counter is copied to the database handle
  49274. ** change counter (returned by subsequent calls to sqlite3_changes())
  49275. ** before it is reset. This is used by trigger programs.
  49276. */
  49277. case OP_ResetCount: {
  49278. if( pOp->p1 ){
  49279. sqlite3VdbeSetChanges(db, p->nChange);
  49280. }
  49281. p->nChange = 0;
  49282. break;
  49283. }
  49284. /* Opcode: RowData P1 P2 * * *
  49285. **
  49286. ** Write into register P2 the complete row data for cursor P1.
  49287. ** There is no interpretation of the data.
  49288. ** It is just copied onto the P2 register exactly as
  49289. ** it is found in the database file.
  49290. **
  49291. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  49292. ** of a real table, not a pseudo-table.
  49293. */
  49294. /* Opcode: RowKey P1 P2 * * *
  49295. **
  49296. ** Write into register P2 the complete row key for cursor P1.
  49297. ** There is no interpretation of the data.
  49298. ** The key is copied onto the P3 register exactly as
  49299. ** it is found in the database file.
  49300. **
  49301. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  49302. ** of a real table, not a pseudo-table.
  49303. */
  49304. case OP_RowKey:
  49305. case OP_RowData: {
  49306. int i = pOp->p1;
  49307. VdbeCursor *pC;
  49308. BtCursor *pCrsr;
  49309. u32 n;
  49310. pOut = &p->aMem[pOp->p2];
  49311. /* Note that RowKey and RowData are really exactly the same instruction */
  49312. assert( i>=0 && i<p->nCursor );
  49313. pC = p->apCsr[i];
  49314. assert( pC->isTable || pOp->opcode==OP_RowKey );
  49315. assert( pC->isIndex || pOp->opcode==OP_RowData );
  49316. assert( pC!=0 );
  49317. assert( pC->nullRow==0 );
  49318. assert( pC->pseudoTable==0 );
  49319. assert( pC->pCursor!=0 );
  49320. pCrsr = pC->pCursor;
  49321. rc = sqlite3VdbeCursorMoveto(pC);
  49322. if( rc ) goto abort_due_to_error;
  49323. if( pC->isIndex ){
  49324. i64 n64;
  49325. assert( !pC->isTable );
  49326. sqlite3BtreeKeySize(pCrsr, &n64);
  49327. if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  49328. goto too_big;
  49329. }
  49330. n = (int)n64;
  49331. }else{
  49332. sqlite3BtreeDataSize(pCrsr, &n);
  49333. if( (int)n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  49334. goto too_big;
  49335. }
  49336. }
  49337. if( sqlite3VdbeMemGrow(pOut, n, 0) ){
  49338. goto no_mem;
  49339. }
  49340. pOut->n = n;
  49341. MemSetTypeFlag(pOut, MEM_Blob);
  49342. if( pC->isIndex ){
  49343. rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
  49344. }else{
  49345. rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
  49346. }
  49347. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  49348. UPDATE_MAX_BLOBSIZE(pOut);
  49349. break;
  49350. }
  49351. /* Opcode: Rowid P1 P2 * * *
  49352. **
  49353. ** Store in register P2 an integer which is the key of the table entry that
  49354. ** P1 is currently point to.
  49355. */
  49356. case OP_Rowid: { /* out2-prerelease */
  49357. int i = pOp->p1;
  49358. VdbeCursor *pC;
  49359. i64 v;
  49360. assert( i>=0 && i<p->nCursor );
  49361. pC = p->apCsr[i];
  49362. assert( pC!=0 );
  49363. rc = sqlite3VdbeCursorMoveto(pC);
  49364. if( rc ) goto abort_due_to_error;
  49365. if( pC->rowidIsValid ){
  49366. v = pC->lastRowid;
  49367. }else if( pC->pseudoTable ){
  49368. v = keyToInt(pC->iKey);
  49369. }else if( pC->nullRow ){
  49370. /* Leave the rowid set to a NULL */
  49371. break;
  49372. }else{
  49373. assert( pC->pCursor!=0 );
  49374. sqlite3BtreeKeySize(pC->pCursor, &v);
  49375. v = keyToInt(v);
  49376. }
  49377. pOut->u.i = v;
  49378. MemSetTypeFlag(pOut, MEM_Int);
  49379. break;
  49380. }
  49381. /* Opcode: NullRow P1 * * * *
  49382. **
  49383. ** Move the cursor P1 to a null row. Any OP_Column operations
  49384. ** that occur while the cursor is on the null row will always
  49385. ** write a NULL.
  49386. */
  49387. case OP_NullRow: {
  49388. int i = pOp->p1;
  49389. VdbeCursor *pC;
  49390. assert( i>=0 && i<p->nCursor );
  49391. pC = p->apCsr[i];
  49392. assert( pC!=0 );
  49393. pC->nullRow = 1;
  49394. pC->rowidIsValid = 0;
  49395. if( pC->pCursor ){
  49396. sqlite3BtreeClearCursor(pC->pCursor);
  49397. }
  49398. break;
  49399. }
  49400. /* Opcode: Last P1 P2 * * *
  49401. **
  49402. ** The next use of the Rowid or Column or Next instruction for P1
  49403. ** will refer to the last entry in the database table or index.
  49404. ** If the table or index is empty and P2>0, then jump immediately to P2.
  49405. ** If P2 is 0 or if the table or index is not empty, fall through
  49406. ** to the following instruction.
  49407. */
  49408. case OP_Last: { /* jump */
  49409. int i = pOp->p1;
  49410. VdbeCursor *pC;
  49411. BtCursor *pCrsr;
  49412. int res;
  49413. assert( i>=0 && i<p->nCursor );
  49414. pC = p->apCsr[i];
  49415. assert( pC!=0 );
  49416. pCrsr = pC->pCursor;
  49417. assert( pCrsr!=0 );
  49418. rc = sqlite3BtreeLast(pCrsr, &res);
  49419. pC->nullRow = (u8)res;
  49420. pC->deferredMoveto = 0;
  49421. pC->rowidIsValid = 0;
  49422. pC->cacheStatus = CACHE_STALE;
  49423. if( res && pOp->p2>0 ){
  49424. pc = pOp->p2 - 1;
  49425. }
  49426. break;
  49427. }
  49428. /* Opcode: Sort P1 P2 * * *
  49429. **
  49430. ** This opcode does exactly the same thing as OP_Rewind except that
  49431. ** it increments an undocumented global variable used for testing.
  49432. **
  49433. ** Sorting is accomplished by writing records into a sorting index,
  49434. ** then rewinding that index and playing it back from beginning to
  49435. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  49436. ** rewinding so that the global variable will be incremented and
  49437. ** regression tests can determine whether or not the optimizer is
  49438. ** correctly optimizing out sorts.
  49439. */
  49440. case OP_Sort: { /* jump */
  49441. #ifdef SQLITE_TEST
  49442. sqlite3_sort_count++;
  49443. sqlite3_search_count--;
  49444. #endif
  49445. p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
  49446. /* Fall through into OP_Rewind */
  49447. }
  49448. /* Opcode: Rewind P1 P2 * * *
  49449. **
  49450. ** The next use of the Rowid or Column or Next instruction for P1
  49451. ** will refer to the first entry in the database table or index.
  49452. ** If the table or index is empty and P2>0, then jump immediately to P2.
  49453. ** If P2 is 0 or if the table or index is not empty, fall through
  49454. ** to the following instruction.
  49455. */
  49456. case OP_Rewind: { /* jump */
  49457. int i = pOp->p1;
  49458. VdbeCursor *pC;
  49459. BtCursor *pCrsr;
  49460. int res;
  49461. assert( i>=0 && i<p->nCursor );
  49462. pC = p->apCsr[i];
  49463. assert( pC!=0 );
  49464. if( (pCrsr = pC->pCursor)!=0 ){
  49465. rc = sqlite3BtreeFirst(pCrsr, &res);
  49466. pC->atFirst = res==0 ?1:0;
  49467. pC->deferredMoveto = 0;
  49468. pC->cacheStatus = CACHE_STALE;
  49469. pC->rowidIsValid = 0;
  49470. }else{
  49471. res = 1;
  49472. }
  49473. pC->nullRow = (u8)res;
  49474. assert( pOp->p2>0 && pOp->p2<p->nOp );
  49475. if( res ){
  49476. pc = pOp->p2 - 1;
  49477. }
  49478. break;
  49479. }
  49480. /* Opcode: Next P1 P2 * * *
  49481. **
  49482. ** Advance cursor P1 so that it points to the next key/data pair in its
  49483. ** table or index. If there are no more key/value pairs then fall through
  49484. ** to the following instruction. But if the cursor advance was successful,
  49485. ** jump immediately to P2.
  49486. **
  49487. ** The P1 cursor must be for a real table, not a pseudo-table.
  49488. **
  49489. ** See also: Prev
  49490. */
  49491. /* Opcode: Prev P1 P2 * * *
  49492. **
  49493. ** Back up cursor P1 so that it points to the previous key/data pair in its
  49494. ** table or index. If there is no previous key/value pairs then fall through
  49495. ** to the following instruction. But if the cursor backup was successful,
  49496. ** jump immediately to P2.
  49497. **
  49498. ** The P1 cursor must be for a real table, not a pseudo-table.
  49499. */
  49500. case OP_Prev: /* jump */
  49501. case OP_Next: { /* jump */
  49502. VdbeCursor *pC;
  49503. BtCursor *pCrsr;
  49504. int res;
  49505. CHECK_FOR_INTERRUPT;
  49506. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  49507. pC = p->apCsr[pOp->p1];
  49508. if( pC==0 ){
  49509. break; /* See ticket #2273 */
  49510. }
  49511. pCrsr = pC->pCursor;
  49512. assert( pCrsr );
  49513. res = 1;
  49514. assert( pC->deferredMoveto==0 );
  49515. rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
  49516. sqlite3BtreePrevious(pCrsr, &res);
  49517. pC->nullRow = (u8)res;
  49518. pC->cacheStatus = CACHE_STALE;
  49519. if( res==0 ){
  49520. pc = pOp->p2 - 1;
  49521. if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
  49522. #ifdef SQLITE_TEST
  49523. sqlite3_search_count++;
  49524. #endif
  49525. }
  49526. pC->rowidIsValid = 0;
  49527. break;
  49528. }
  49529. /* Opcode: IdxInsert P1 P2 P3 * *
  49530. **
  49531. ** Register P2 holds a SQL index key made using the
  49532. ** MakeIdxRec instructions. This opcode writes that key
  49533. ** into the index P1. Data for the entry is nil.
  49534. **
  49535. ** P3 is a flag that provides a hint to the b-tree layer that this
  49536. ** insert is likely to be an append.
  49537. **
  49538. ** This instruction only works for indices. The equivalent instruction
  49539. ** for tables is OP_Insert.
  49540. */
  49541. case OP_IdxInsert: { /* in2 */
  49542. int i = pOp->p1;
  49543. VdbeCursor *pC;
  49544. BtCursor *pCrsr;
  49545. assert( i>=0 && i<p->nCursor );
  49546. assert( p->apCsr[i]!=0 );
  49547. assert( pIn2->flags & MEM_Blob );
  49548. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  49549. assert( pC->isTable==0 );
  49550. rc = ExpandBlob(pIn2);
  49551. if( rc==SQLITE_OK ){
  49552. int nKey = pIn2->n;
  49553. const char *zKey = pIn2->z;
  49554. rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
  49555. assert( pC->deferredMoveto==0 );
  49556. pC->cacheStatus = CACHE_STALE;
  49557. }
  49558. }
  49559. break;
  49560. }
  49561. /* Opcode: IdxDelete P1 P2 P3 * *
  49562. **
  49563. ** The content of P3 registers starting at register P2 form
  49564. ** an unpacked index key. This opcode removes that entry from the
  49565. ** index opened by cursor P1.
  49566. */
  49567. case OP_IdxDelete: {
  49568. int i = pOp->p1;
  49569. VdbeCursor *pC;
  49570. BtCursor *pCrsr;
  49571. assert( pOp->p3>0 );
  49572. assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem );
  49573. assert( i>=0 && i<p->nCursor );
  49574. assert( p->apCsr[i]!=0 );
  49575. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  49576. int res;
  49577. UnpackedRecord r;
  49578. r.pKeyInfo = pC->pKeyInfo;
  49579. r.nField = (u16)pOp->p3;
  49580. r.flags = 0;
  49581. r.aMem = &p->aMem[pOp->p2];
  49582. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  49583. if( rc==SQLITE_OK && res==0 ){
  49584. rc = sqlite3BtreeDelete(pCrsr);
  49585. }
  49586. assert( pC->deferredMoveto==0 );
  49587. pC->cacheStatus = CACHE_STALE;
  49588. }
  49589. break;
  49590. }
  49591. /* Opcode: IdxRowid P1 P2 * * *
  49592. **
  49593. ** Write into register P2 an integer which is the last entry in the record at
  49594. ** the end of the index key pointed to by cursor P1. This integer should be
  49595. ** the rowid of the table entry to which this index entry points.
  49596. **
  49597. ** See also: Rowid, MakeIdxRec.
  49598. */
  49599. case OP_IdxRowid: { /* out2-prerelease */
  49600. int i = pOp->p1;
  49601. BtCursor *pCrsr;
  49602. VdbeCursor *pC;
  49603. assert( i>=0 && i<p->nCursor );
  49604. assert( p->apCsr[i]!=0 );
  49605. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  49606. i64 rowid;
  49607. assert( pC->deferredMoveto==0 );
  49608. assert( pC->isTable==0 );
  49609. if( !pC->nullRow ){
  49610. rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
  49611. if( rc!=SQLITE_OK ){
  49612. goto abort_due_to_error;
  49613. }
  49614. MemSetTypeFlag(pOut, MEM_Int);
  49615. pOut->u.i = rowid;
  49616. }
  49617. }
  49618. break;
  49619. }
  49620. /* Opcode: IdxGE P1 P2 P3 P4 P5
  49621. **
  49622. ** The P4 register values beginning with P3 form an unpacked index
  49623. ** key that omits the ROWID. Compare this key value against the index
  49624. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  49625. **
  49626. ** If the P1 index entry is greater than or equal to the key value
  49627. ** then jump to P2. Otherwise fall through to the next instruction.
  49628. **
  49629. ** If P5 is non-zero then the key value is increased by an epsilon
  49630. ** prior to the comparison. This make the opcode work like IdxGT except
  49631. ** that if the key from register P3 is a prefix of the key in the cursor,
  49632. ** the result is false whereas it would be true with IdxGT.
  49633. */
  49634. /* Opcode: IdxLT P1 P2 P3 * P5
  49635. **
  49636. ** The P4 register values beginning with P3 form an unpacked index
  49637. ** key that omits the ROWID. Compare this key value against the index
  49638. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  49639. **
  49640. ** If the P1 index entry is less than the key value then jump to P2.
  49641. ** Otherwise fall through to the next instruction.
  49642. **
  49643. ** If P5 is non-zero then the key value is increased by an epsilon prior
  49644. ** to the comparison. This makes the opcode work like IdxLE.
  49645. */
  49646. case OP_IdxLT: /* jump, in3 */
  49647. case OP_IdxGE: { /* jump, in3 */
  49648. int i= pOp->p1;
  49649. VdbeCursor *pC;
  49650. assert( i>=0 && i<p->nCursor );
  49651. assert( p->apCsr[i]!=0 );
  49652. if( (pC = p->apCsr[i])->pCursor!=0 ){
  49653. int res;
  49654. UnpackedRecord r;
  49655. assert( pC->deferredMoveto==0 );
  49656. assert( pOp->p5==0 || pOp->p5==1 );
  49657. assert( pOp->p4type==P4_INT32 );
  49658. r.pKeyInfo = pC->pKeyInfo;
  49659. r.nField = (u16)pOp->p4.i;
  49660. if( pOp->p5 ){
  49661. r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
  49662. }else{
  49663. r.flags = UNPACKED_IGNORE_ROWID;
  49664. }
  49665. r.aMem = &p->aMem[pOp->p3];
  49666. rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
  49667. if( pOp->opcode==OP_IdxLT ){
  49668. res = -res;
  49669. }else{
  49670. assert( pOp->opcode==OP_IdxGE );
  49671. res++;
  49672. }
  49673. if( res>0 ){
  49674. pc = pOp->p2 - 1 ;
  49675. }
  49676. }
  49677. break;
  49678. }
  49679. /* Opcode: Destroy P1 P2 P3 * *
  49680. **
  49681. ** Delete an entire database table or index whose root page in the database
  49682. ** file is given by P1.
  49683. **
  49684. ** The table being destroyed is in the main database file if P3==0. If
  49685. ** P3==1 then the table to be clear is in the auxiliary database file
  49686. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  49687. **
  49688. ** If AUTOVACUUM is enabled then it is possible that another root page
  49689. ** might be moved into the newly deleted root page in order to keep all
  49690. ** root pages contiguous at the beginning of the database. The former
  49691. ** value of the root page that moved - its value before the move occurred -
  49692. ** is stored in register P2. If no page
  49693. ** movement was required (because the table being dropped was already
  49694. ** the last one in the database) then a zero is stored in register P2.
  49695. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  49696. **
  49697. ** See also: Clear
  49698. */
  49699. case OP_Destroy: { /* out2-prerelease */
  49700. int iMoved;
  49701. int iCnt;
  49702. #ifndef SQLITE_OMIT_VIRTUALTABLE
  49703. Vdbe *pVdbe;
  49704. iCnt = 0;
  49705. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  49706. if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
  49707. iCnt++;
  49708. }
  49709. }
  49710. #else
  49711. iCnt = db->activeVdbeCnt;
  49712. #endif
  49713. if( iCnt>1 ){
  49714. rc = SQLITE_LOCKED;
  49715. p->errorAction = OE_Abort;
  49716. }else{
  49717. int iDb = pOp->p3;
  49718. assert( iCnt==1 );
  49719. assert( (p->btreeMask & (1<<iDb))!=0 );
  49720. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  49721. MemSetTypeFlag(pOut, MEM_Int);
  49722. pOut->u.i = iMoved;
  49723. #ifndef SQLITE_OMIT_AUTOVACUUM
  49724. if( rc==SQLITE_OK && iMoved!=0 ){
  49725. sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
  49726. }
  49727. #endif
  49728. }
  49729. break;
  49730. }
  49731. /* Opcode: Clear P1 P2 P3
  49732. **
  49733. ** Delete all contents of the database table or index whose root page
  49734. ** in the database file is given by P1. But, unlike Destroy, do not
  49735. ** remove the table or index from the database file.
  49736. **
  49737. ** The table being clear is in the main database file if P2==0. If
  49738. ** P2==1 then the table to be clear is in the auxiliary database file
  49739. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  49740. **
  49741. ** If the P3 value is non-zero, then the table refered to must be an
  49742. ** intkey table (an SQL table, not an index). In this case the row change
  49743. ** count is incremented by the number of rows in the table being cleared.
  49744. ** If P3 is greater than zero, then the value stored in register P3 is
  49745. ** also incremented by the number of rows in the table being cleared.
  49746. **
  49747. ** See also: Destroy
  49748. */
  49749. case OP_Clear: {
  49750. int nChange = 0;
  49751. assert( (p->btreeMask & (1<<pOp->p2))!=0 );
  49752. rc = sqlite3BtreeClearTable(
  49753. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  49754. );
  49755. if( pOp->p3 ){
  49756. p->nChange += nChange;
  49757. if( pOp->p3>0 ){
  49758. p->aMem[pOp->p3].u.i += nChange;
  49759. }
  49760. }
  49761. break;
  49762. }
  49763. /* Opcode: CreateTable P1 P2 * * *
  49764. **
  49765. ** Allocate a new table in the main database file if P1==0 or in the
  49766. ** auxiliary database file if P1==1 or in an attached database if
  49767. ** P1>1. Write the root page number of the new table into
  49768. ** register P2
  49769. **
  49770. ** The difference between a table and an index is this: A table must
  49771. ** have a 4-byte integer key and can have arbitrary data. An index
  49772. ** has an arbitrary key but no data.
  49773. **
  49774. ** See also: CreateIndex
  49775. */
  49776. /* Opcode: CreateIndex P1 P2 * * *
  49777. **
  49778. ** Allocate a new index in the main database file if P1==0 or in the
  49779. ** auxiliary database file if P1==1 or in an attached database if
  49780. ** P1>1. Write the root page number of the new table into
  49781. ** register P2.
  49782. **
  49783. ** See documentation on OP_CreateTable for additional information.
  49784. */
  49785. case OP_CreateIndex: /* out2-prerelease */
  49786. case OP_CreateTable: { /* out2-prerelease */
  49787. int pgno = 0;
  49788. int flags;
  49789. Db *pDb;
  49790. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  49791. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  49792. pDb = &db->aDb[pOp->p1];
  49793. assert( pDb->pBt!=0 );
  49794. if( pOp->opcode==OP_CreateTable ){
  49795. /* flags = BTREE_INTKEY; */
  49796. flags = BTREE_LEAFDATA|BTREE_INTKEY;
  49797. }else{
  49798. flags = BTREE_ZERODATA;
  49799. }
  49800. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  49801. pOut->u.i = pgno;
  49802. MemSetTypeFlag(pOut, MEM_Int);
  49803. break;
  49804. }
  49805. /* Opcode: ParseSchema P1 P2 * P4 *
  49806. **
  49807. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  49808. ** that match the WHERE clause P4. P2 is the "force" flag. Always do
  49809. ** the parsing if P2 is true. If P2 is false, then this routine is a
  49810. ** no-op if the schema is not currently loaded. In other words, if P2
  49811. ** is false, the SQLITE_MASTER table is only parsed if the rest of the
  49812. ** schema is already loaded into the symbol table.
  49813. **
  49814. ** This opcode invokes the parser to create a new virtual machine,
  49815. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  49816. */
  49817. case OP_ParseSchema: {
  49818. char *zSql;
  49819. int iDb = pOp->p1;
  49820. const char *zMaster;
  49821. InitData initData;
  49822. assert( iDb>=0 && iDb<db->nDb );
  49823. if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
  49824. break;
  49825. }
  49826. zMaster = SCHEMA_TABLE(iDb);
  49827. initData.db = db;
  49828. initData.iDb = pOp->p1;
  49829. initData.pzErrMsg = &p->zErrMsg;
  49830. zSql = sqlite3MPrintf(db,
  49831. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
  49832. db->aDb[iDb].zName, zMaster, pOp->p4.z);
  49833. if( zSql==0 ) goto no_mem;
  49834. (void)sqlite3SafetyOff(db);
  49835. assert( db->init.busy==0 );
  49836. db->init.busy = 1;
  49837. initData.rc = SQLITE_OK;
  49838. assert( !db->mallocFailed );
  49839. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  49840. if( rc==SQLITE_OK ) rc = initData.rc;
  49841. sqlite3DbFree(db, zSql);
  49842. db->init.busy = 0;
  49843. (void)sqlite3SafetyOn(db);
  49844. if( rc==SQLITE_NOMEM ){
  49845. goto no_mem;
  49846. }
  49847. break;
  49848. }
  49849. #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
  49850. /* Opcode: LoadAnalysis P1 * * * *
  49851. **
  49852. ** Read the sqlite_stat1 table for database P1 and load the content
  49853. ** of that table into the internal index hash table. This will cause
  49854. ** the analysis to be used when preparing all subsequent queries.
  49855. */
  49856. case OP_LoadAnalysis: {
  49857. int iDb = pOp->p1;
  49858. assert( iDb>=0 && iDb<db->nDb );
  49859. rc = sqlite3AnalysisLoad(db, iDb);
  49860. break;
  49861. }
  49862. #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER) */
  49863. /* Opcode: DropTable P1 * * P4 *
  49864. **
  49865. ** Remove the internal (in-memory) data structures that describe
  49866. ** the table named P4 in database P1. This is called after a table
  49867. ** is dropped in order to keep the internal representation of the
  49868. ** schema consistent with what is on disk.
  49869. */
  49870. case OP_DropTable: {
  49871. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  49872. break;
  49873. }
  49874. /* Opcode: DropIndex P1 * * P4 *
  49875. **
  49876. ** Remove the internal (in-memory) data structures that describe
  49877. ** the index named P4 in database P1. This is called after an index
  49878. ** is dropped in order to keep the internal representation of the
  49879. ** schema consistent with what is on disk.
  49880. */
  49881. case OP_DropIndex: {
  49882. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  49883. break;
  49884. }
  49885. /* Opcode: DropTrigger P1 * * P4 *
  49886. **
  49887. ** Remove the internal (in-memory) data structures that describe
  49888. ** the trigger named P4 in database P1. This is called after a trigger
  49889. ** is dropped in order to keep the internal representation of the
  49890. ** schema consistent with what is on disk.
  49891. */
  49892. case OP_DropTrigger: {
  49893. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  49894. break;
  49895. }
  49896. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  49897. /* Opcode: IntegrityCk P1 P2 P3 * P5
  49898. **
  49899. ** Do an analysis of the currently open database. Store in
  49900. ** register P1 the text of an error message describing any problems.
  49901. ** If no problems are found, store a NULL in register P1.
  49902. **
  49903. ** The register P3 contains the maximum number of allowed errors.
  49904. ** At most reg(P3) errors will be reported.
  49905. ** In other words, the analysis stops as soon as reg(P1) errors are
  49906. ** seen. Reg(P1) is updated with the number of errors remaining.
  49907. **
  49908. ** The root page numbers of all tables in the database are integer
  49909. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  49910. ** total.
  49911. **
  49912. ** If P5 is not zero, the check is done on the auxiliary database
  49913. ** file, not the main database file.
  49914. **
  49915. ** This opcode is used to implement the integrity_check pragma.
  49916. */
  49917. case OP_IntegrityCk: {
  49918. int nRoot; /* Number of tables to check. (Number of root pages.) */
  49919. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  49920. int j; /* Loop counter */
  49921. int nErr; /* Number of errors reported */
  49922. char *z; /* Text of the error report */
  49923. Mem *pnErr; /* Register keeping track of errors remaining */
  49924. nRoot = pOp->p2;
  49925. assert( nRoot>0 );
  49926. aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
  49927. if( aRoot==0 ) goto no_mem;
  49928. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  49929. pnErr = &p->aMem[pOp->p3];
  49930. assert( (pnErr->flags & MEM_Int)!=0 );
  49931. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  49932. pIn1 = &p->aMem[pOp->p1];
  49933. for(j=0; j<nRoot; j++){
  49934. aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
  49935. }
  49936. aRoot[j] = 0;
  49937. assert( pOp->p5<db->nDb );
  49938. assert( (p->btreeMask & (1<<pOp->p5))!=0 );
  49939. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  49940. (int)pnErr->u.i, &nErr);
  49941. sqlite3DbFree(db, aRoot);
  49942. pnErr->u.i -= nErr;
  49943. sqlite3VdbeMemSetNull(pIn1);
  49944. if( nErr==0 ){
  49945. assert( z==0 );
  49946. }else if( z==0 ){
  49947. goto no_mem;
  49948. }else{
  49949. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  49950. }
  49951. UPDATE_MAX_BLOBSIZE(pIn1);
  49952. sqlite3VdbeChangeEncoding(pIn1, encoding);
  49953. break;
  49954. }
  49955. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  49956. /* Opcode: RowSetAdd P1 P2 * * *
  49957. **
  49958. ** Insert the integer value held by register P2 into a boolean index
  49959. ** held in register P1.
  49960. **
  49961. ** An assertion fails if P2 is not an integer.
  49962. */
  49963. case OP_RowSetAdd: { /* in2 */
  49964. Mem *pIdx;
  49965. Mem *pVal;
  49966. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  49967. pIdx = &p->aMem[pOp->p1];
  49968. assert( pOp->p2>0 && pOp->p2<=p->nMem );
  49969. pVal = &p->aMem[pOp->p2];
  49970. assert( (pVal->flags & MEM_Int)!=0 );
  49971. if( (pIdx->flags & MEM_RowSet)==0 ){
  49972. sqlite3VdbeMemSetRowSet(pIdx);
  49973. if( (pIdx->flags & MEM_RowSet)==0 ) goto no_mem;
  49974. }
  49975. sqlite3RowSetInsert(pIdx->u.pRowSet, pVal->u.i);
  49976. break;
  49977. }
  49978. /* Opcode: RowSetRead P1 P2 P3 * *
  49979. **
  49980. ** Extract the smallest value from boolean index P1 and put that value into
  49981. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  49982. ** unchanged and jump to instruction P2.
  49983. */
  49984. case OP_RowSetRead: { /* jump, out3 */
  49985. Mem *pIdx;
  49986. i64 val;
  49987. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  49988. CHECK_FOR_INTERRUPT;
  49989. pIdx = &p->aMem[pOp->p1];
  49990. pOut = &p->aMem[pOp->p3];
  49991. if( (pIdx->flags & MEM_RowSet)==0
  49992. || sqlite3RowSetNext(pIdx->u.pRowSet, &val)==0
  49993. ){
  49994. /* The boolean index is empty */
  49995. sqlite3VdbeMemSetNull(pIdx);
  49996. pc = pOp->p2 - 1;
  49997. }else{
  49998. /* A value was pulled from the index */
  49999. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  50000. sqlite3VdbeMemSetInt64(pOut, val);
  50001. }
  50002. break;
  50003. }
  50004. #ifndef SQLITE_OMIT_TRIGGER
  50005. /* Opcode: ContextPush * * *
  50006. **
  50007. ** Save the current Vdbe context such that it can be restored by a ContextPop
  50008. ** opcode. The context stores the last insert row id, the last statement change
  50009. ** count, and the current statement change count.
  50010. */
  50011. case OP_ContextPush: {
  50012. int i = p->contextStackTop++;
  50013. Context *pContext;
  50014. assert( i>=0 );
  50015. /* FIX ME: This should be allocated as part of the vdbe at compile-time */
  50016. if( i>=p->contextStackDepth ){
  50017. p->contextStackDepth = i+1;
  50018. p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
  50019. sizeof(Context)*(i+1));
  50020. if( p->contextStack==0 ) goto no_mem;
  50021. }
  50022. pContext = &p->contextStack[i];
  50023. pContext->lastRowid = db->lastRowid;
  50024. pContext->nChange = p->nChange;
  50025. break;
  50026. }
  50027. /* Opcode: ContextPop * * *
  50028. **
  50029. ** Restore the Vdbe context to the state it was in when contextPush was last
  50030. ** executed. The context stores the last insert row id, the last statement
  50031. ** change count, and the current statement change count.
  50032. */
  50033. case OP_ContextPop: {
  50034. Context *pContext = &p->contextStack[--p->contextStackTop];
  50035. assert( p->contextStackTop>=0 );
  50036. db->lastRowid = pContext->lastRowid;
  50037. p->nChange = pContext->nChange;
  50038. break;
  50039. }
  50040. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  50041. #ifndef SQLITE_OMIT_AUTOINCREMENT
  50042. /* Opcode: MemMax P1 P2 * * *
  50043. **
  50044. ** Set the value of register P1 to the maximum of its current value
  50045. ** and the value in register P2.
  50046. **
  50047. ** This instruction throws an error if the memory cell is not initially
  50048. ** an integer.
  50049. */
  50050. case OP_MemMax: { /* in1, in2 */
  50051. sqlite3VdbeMemIntegerify(pIn1);
  50052. sqlite3VdbeMemIntegerify(pIn2);
  50053. if( pIn1->u.i<pIn2->u.i){
  50054. pIn1->u.i = pIn2->u.i;
  50055. }
  50056. break;
  50057. }
  50058. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  50059. /* Opcode: IfPos P1 P2 * * *
  50060. **
  50061. ** If the value of register P1 is 1 or greater, jump to P2.
  50062. **
  50063. ** It is illegal to use this instruction on a register that does
  50064. ** not contain an integer. An assertion fault will result if you try.
  50065. */
  50066. case OP_IfPos: { /* jump, in1 */
  50067. assert( pIn1->flags&MEM_Int );
  50068. if( pIn1->u.i>0 ){
  50069. pc = pOp->p2 - 1;
  50070. }
  50071. break;
  50072. }
  50073. /* Opcode: IfNeg P1 P2 * * *
  50074. **
  50075. ** If the value of register P1 is less than zero, jump to P2.
  50076. **
  50077. ** It is illegal to use this instruction on a register that does
  50078. ** not contain an integer. An assertion fault will result if you try.
  50079. */
  50080. case OP_IfNeg: { /* jump, in1 */
  50081. assert( pIn1->flags&MEM_Int );
  50082. if( pIn1->u.i<0 ){
  50083. pc = pOp->p2 - 1;
  50084. }
  50085. break;
  50086. }
  50087. /* Opcode: IfZero P1 P2 * * *
  50088. **
  50089. ** If the value of register P1 is exactly 0, jump to P2.
  50090. **
  50091. ** It is illegal to use this instruction on a register that does
  50092. ** not contain an integer. An assertion fault will result if you try.
  50093. */
  50094. case OP_IfZero: { /* jump, in1 */
  50095. assert( pIn1->flags&MEM_Int );
  50096. if( pIn1->u.i==0 ){
  50097. pc = pOp->p2 - 1;
  50098. }
  50099. break;
  50100. }
  50101. /* Opcode: AggStep * P2 P3 P4 P5
  50102. **
  50103. ** Execute the step function for an aggregate. The
  50104. ** function has P5 arguments. P4 is a pointer to the FuncDef
  50105. ** structure that specifies the function. Use register
  50106. ** P3 as the accumulator.
  50107. **
  50108. ** The P5 arguments are taken from register P2 and its
  50109. ** successors.
  50110. */
  50111. case OP_AggStep: {
  50112. int n = pOp->p5;
  50113. int i;
  50114. Mem *pMem, *pRec;
  50115. sqlite3_context ctx;
  50116. sqlite3_value **apVal;
  50117. assert( n>=0 );
  50118. pRec = &p->aMem[pOp->p2];
  50119. apVal = p->apArg;
  50120. assert( apVal || n==0 );
  50121. for(i=0; i<n; i++, pRec++){
  50122. apVal[i] = pRec;
  50123. storeTypeInfo(pRec, encoding);
  50124. }
  50125. ctx.pFunc = pOp->p4.pFunc;
  50126. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  50127. ctx.pMem = pMem = &p->aMem[pOp->p3];
  50128. pMem->n++;
  50129. ctx.s.flags = MEM_Null;
  50130. ctx.s.z = 0;
  50131. ctx.s.zMalloc = 0;
  50132. ctx.s.xDel = 0;
  50133. ctx.s.db = db;
  50134. ctx.isError = 0;
  50135. ctx.pColl = 0;
  50136. if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  50137. assert( pOp>p->aOp );
  50138. assert( pOp[-1].p4type==P4_COLLSEQ );
  50139. assert( pOp[-1].opcode==OP_CollSeq );
  50140. ctx.pColl = pOp[-1].p4.pColl;
  50141. }
  50142. (ctx.pFunc->xStep)(&ctx, n, apVal);
  50143. if( ctx.isError ){
  50144. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
  50145. rc = ctx.isError;
  50146. }
  50147. sqlite3VdbeMemRelease(&ctx.s);
  50148. break;
  50149. }
  50150. /* Opcode: AggFinal P1 P2 * P4 *
  50151. **
  50152. ** Execute the finalizer function for an aggregate. P1 is
  50153. ** the memory location that is the accumulator for the aggregate.
  50154. **
  50155. ** P2 is the number of arguments that the step function takes and
  50156. ** P4 is a pointer to the FuncDef for this function. The P2
  50157. ** argument is not used by this opcode. It is only there to disambiguate
  50158. ** functions that can take varying numbers of arguments. The
  50159. ** P4 argument is only needed for the degenerate case where
  50160. ** the step function was not previously called.
  50161. */
  50162. case OP_AggFinal: {
  50163. Mem *pMem;
  50164. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  50165. pMem = &p->aMem[pOp->p1];
  50166. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  50167. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  50168. if( rc==SQLITE_ERROR ){
  50169. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
  50170. }
  50171. sqlite3VdbeChangeEncoding(pMem, encoding);
  50172. UPDATE_MAX_BLOBSIZE(pMem);
  50173. if( sqlite3VdbeMemTooBig(pMem) ){
  50174. goto too_big;
  50175. }
  50176. break;
  50177. }
  50178. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  50179. /* Opcode: Vacuum * * * * *
  50180. **
  50181. ** Vacuum the entire database. This opcode will cause other virtual
  50182. ** machines to be created and run. It may not be called from within
  50183. ** a transaction.
  50184. */
  50185. case OP_Vacuum: {
  50186. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  50187. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  50188. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  50189. break;
  50190. }
  50191. #endif
  50192. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  50193. /* Opcode: IncrVacuum P1 P2 * * *
  50194. **
  50195. ** Perform a single step of the incremental vacuum procedure on
  50196. ** the P1 database. If the vacuum has finished, jump to instruction
  50197. ** P2. Otherwise, fall through to the next instruction.
  50198. */
  50199. case OP_IncrVacuum: { /* jump */
  50200. Btree *pBt;
  50201. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  50202. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  50203. pBt = db->aDb[pOp->p1].pBt;
  50204. rc = sqlite3BtreeIncrVacuum(pBt);
  50205. if( rc==SQLITE_DONE ){
  50206. pc = pOp->p2 - 1;
  50207. rc = SQLITE_OK;
  50208. }
  50209. break;
  50210. }
  50211. #endif
  50212. /* Opcode: Expire P1 * * * *
  50213. **
  50214. ** Cause precompiled statements to become expired. An expired statement
  50215. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  50216. ** (via sqlite3_step()).
  50217. **
  50218. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  50219. ** then only the currently executing statement is affected.
  50220. */
  50221. case OP_Expire: {
  50222. if( !pOp->p1 ){
  50223. sqlite3ExpirePreparedStatements(db);
  50224. }else{
  50225. p->expired = 1;
  50226. }
  50227. break;
  50228. }
  50229. #ifndef SQLITE_OMIT_SHARED_CACHE
  50230. /* Opcode: TableLock P1 P2 P3 P4 *
  50231. **
  50232. ** Obtain a lock on a particular table. This instruction is only used when
  50233. ** the shared-cache feature is enabled.
  50234. **
  50235. ** If P1 is the index of the database in sqlite3.aDb[] of the database
  50236. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  50237. ** a write lock if P3==1.
  50238. **
  50239. ** P2 contains the root-page of the table to lock.
  50240. **
  50241. ** P4 contains a pointer to the name of the table being locked. This is only
  50242. ** used to generate an error message if the lock cannot be obtained.
  50243. */
  50244. case OP_TableLock: {
  50245. int p1 = pOp->p1;
  50246. u8 isWriteLock = (u8)pOp->p3;
  50247. assert( p1>=0 && p1<db->nDb );
  50248. assert( (p->btreeMask & (1<<p1))!=0 );
  50249. assert( isWriteLock==0 || isWriteLock==1 );
  50250. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  50251. if( rc==SQLITE_LOCKED ){
  50252. const char *z = pOp->p4.z;
  50253. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  50254. }
  50255. break;
  50256. }
  50257. #endif /* SQLITE_OMIT_SHARED_CACHE */
  50258. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50259. /* Opcode: VBegin * * * P4 *
  50260. **
  50261. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  50262. ** xBegin method for that table.
  50263. **
  50264. ** Also, whether or not P4 is set, check that this is not being called from
  50265. ** within a callback to a virtual table xSync() method. If it is, set the
  50266. ** error code to SQLITE_LOCKED.
  50267. */
  50268. case OP_VBegin: {
  50269. sqlite3_vtab *pVtab = pOp->p4.pVtab;
  50270. rc = sqlite3VtabBegin(db, pVtab);
  50271. if( pVtab ){
  50272. sqlite3DbFree(db, p->zErrMsg);
  50273. p->zErrMsg = pVtab->zErrMsg;
  50274. pVtab->zErrMsg = 0;
  50275. }
  50276. break;
  50277. }
  50278. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50279. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50280. /* Opcode: VCreate P1 * * P4 *
  50281. **
  50282. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  50283. ** for that table.
  50284. */
  50285. case OP_VCreate: {
  50286. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  50287. break;
  50288. }
  50289. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50290. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50291. /* Opcode: VDestroy P1 * * P4 *
  50292. **
  50293. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  50294. ** of that table.
  50295. */
  50296. case OP_VDestroy: {
  50297. p->inVtabMethod = 2;
  50298. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  50299. p->inVtabMethod = 0;
  50300. break;
  50301. }
  50302. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50303. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50304. /* Opcode: VOpen P1 * * P4 *
  50305. **
  50306. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  50307. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  50308. ** table and stores that cursor in P1.
  50309. */
  50310. case OP_VOpen: {
  50311. VdbeCursor *pCur = 0;
  50312. sqlite3_vtab_cursor *pVtabCursor = 0;
  50313. sqlite3_vtab *pVtab = pOp->p4.pVtab;
  50314. sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
  50315. assert(pVtab && pModule);
  50316. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  50317. rc = pModule->xOpen(pVtab, &pVtabCursor);
  50318. sqlite3DbFree(db, p->zErrMsg);
  50319. p->zErrMsg = pVtab->zErrMsg;
  50320. pVtab->zErrMsg = 0;
  50321. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  50322. if( SQLITE_OK==rc ){
  50323. /* Initialize sqlite3_vtab_cursor base class */
  50324. pVtabCursor->pVtab = pVtab;
  50325. /* Initialise vdbe cursor object */
  50326. pCur = allocateCursor(p, pOp->p1, &pOp[-1], -1, 0);
  50327. if( pCur ){
  50328. pCur->pVtabCursor = pVtabCursor;
  50329. pCur->pModule = pVtabCursor->pVtab->pModule;
  50330. }else{
  50331. db->mallocFailed = 1;
  50332. pModule->xClose(pVtabCursor);
  50333. }
  50334. }
  50335. break;
  50336. }
  50337. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50338. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50339. /* Opcode: VFilter P1 P2 P3 P4 *
  50340. **
  50341. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  50342. ** the filtered result set is empty.
  50343. **
  50344. ** P4 is either NULL or a string that was generated by the xBestIndex
  50345. ** method of the module. The interpretation of the P4 string is left
  50346. ** to the module implementation.
  50347. **
  50348. ** This opcode invokes the xFilter method on the virtual table specified
  50349. ** by P1. The integer query plan parameter to xFilter is stored in register
  50350. ** P3. Register P3+1 stores the argc parameter to be passed to the
  50351. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  50352. ** additional parameters which are passed to
  50353. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  50354. **
  50355. ** A jump is made to P2 if the result set after filtering would be empty.
  50356. */
  50357. case OP_VFilter: { /* jump */
  50358. int nArg;
  50359. int iQuery;
  50360. const sqlite3_module *pModule;
  50361. Mem *pQuery = &p->aMem[pOp->p3];
  50362. Mem *pArgc = &pQuery[1];
  50363. sqlite3_vtab_cursor *pVtabCursor;
  50364. sqlite3_vtab *pVtab;
  50365. VdbeCursor *pCur = p->apCsr[pOp->p1];
  50366. REGISTER_TRACE(pOp->p3, pQuery);
  50367. assert( pCur->pVtabCursor );
  50368. pVtabCursor = pCur->pVtabCursor;
  50369. pVtab = pVtabCursor->pVtab;
  50370. pModule = pVtab->pModule;
  50371. /* Grab the index number and argc parameters */
  50372. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  50373. nArg = (int)pArgc->u.i;
  50374. iQuery = (int)pQuery->u.i;
  50375. /* Invoke the xFilter method */
  50376. {
  50377. int res = 0;
  50378. int i;
  50379. Mem **apArg = p->apArg;
  50380. for(i = 0; i<nArg; i++){
  50381. apArg[i] = &pArgc[i+1];
  50382. storeTypeInfo(apArg[i], 0);
  50383. }
  50384. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  50385. sqlite3VtabLock(pVtab);
  50386. p->inVtabMethod = 1;
  50387. rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
  50388. p->inVtabMethod = 0;
  50389. sqlite3DbFree(db, p->zErrMsg);
  50390. p->zErrMsg = pVtab->zErrMsg;
  50391. pVtab->zErrMsg = 0;
  50392. sqlite3VtabUnlock(db, pVtab);
  50393. if( rc==SQLITE_OK ){
  50394. res = pModule->xEof(pVtabCursor);
  50395. }
  50396. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  50397. if( res ){
  50398. pc = pOp->p2 - 1;
  50399. }
  50400. }
  50401. pCur->nullRow = 0;
  50402. break;
  50403. }
  50404. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50405. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50406. /* Opcode: VRowid P1 P2 * * *
  50407. **
  50408. ** Store into register P2 the rowid of
  50409. ** the virtual-table that the P1 cursor is pointing to.
  50410. */
  50411. case OP_VRowid: { /* out2-prerelease */
  50412. sqlite3_vtab *pVtab;
  50413. const sqlite3_module *pModule;
  50414. sqlite_int64 iRow;
  50415. VdbeCursor *pCur = p->apCsr[pOp->p1];
  50416. assert( pCur->pVtabCursor );
  50417. if( pCur->nullRow ){
  50418. break;
  50419. }
  50420. pVtab = pCur->pVtabCursor->pVtab;
  50421. pModule = pVtab->pModule;
  50422. assert( pModule->xRowid );
  50423. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  50424. rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
  50425. sqlite3DbFree(db, p->zErrMsg);
  50426. p->zErrMsg = pVtab->zErrMsg;
  50427. pVtab->zErrMsg = 0;
  50428. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  50429. MemSetTypeFlag(pOut, MEM_Int);
  50430. pOut->u.i = iRow;
  50431. break;
  50432. }
  50433. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50434. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50435. /* Opcode: VColumn P1 P2 P3 * *
  50436. **
  50437. ** Store the value of the P2-th column of
  50438. ** the row of the virtual-table that the
  50439. ** P1 cursor is pointing to into register P3.
  50440. */
  50441. case OP_VColumn: {
  50442. sqlite3_vtab *pVtab;
  50443. const sqlite3_module *pModule;
  50444. Mem *pDest;
  50445. sqlite3_context sContext;
  50446. VdbeCursor *pCur = p->apCsr[pOp->p1];
  50447. assert( pCur->pVtabCursor );
  50448. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  50449. pDest = &p->aMem[pOp->p3];
  50450. if( pCur->nullRow ){
  50451. sqlite3VdbeMemSetNull(pDest);
  50452. break;
  50453. }
  50454. pVtab = pCur->pVtabCursor->pVtab;
  50455. pModule = pVtab->pModule;
  50456. assert( pModule->xColumn );
  50457. memset(&sContext, 0, sizeof(sContext));
  50458. /* The output cell may already have a buffer allocated. Move
  50459. ** the current contents to sContext.s so in case the user-function
  50460. ** can use the already allocated buffer instead of allocating a
  50461. ** new one.
  50462. */
  50463. sqlite3VdbeMemMove(&sContext.s, pDest);
  50464. MemSetTypeFlag(&sContext.s, MEM_Null);
  50465. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  50466. rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
  50467. sqlite3DbFree(db, p->zErrMsg);
  50468. p->zErrMsg = pVtab->zErrMsg;
  50469. pVtab->zErrMsg = 0;
  50470. /* Copy the result of the function to the P3 register. We
  50471. ** do this regardless of whether or not an error occured to ensure any
  50472. ** dynamic allocation in sContext.s (a Mem struct) is released.
  50473. */
  50474. sqlite3VdbeChangeEncoding(&sContext.s, encoding);
  50475. REGISTER_TRACE(pOp->p3, pDest);
  50476. sqlite3VdbeMemMove(pDest, &sContext.s);
  50477. UPDATE_MAX_BLOBSIZE(pDest);
  50478. if( sqlite3SafetyOn(db) ){
  50479. goto abort_due_to_misuse;
  50480. }
  50481. if( sqlite3VdbeMemTooBig(pDest) ){
  50482. goto too_big;
  50483. }
  50484. break;
  50485. }
  50486. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50487. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50488. /* Opcode: VNext P1 P2 * * *
  50489. **
  50490. ** Advance virtual table P1 to the next row in its result set and
  50491. ** jump to instruction P2. Or, if the virtual table has reached
  50492. ** the end of its result set, then fall through to the next instruction.
  50493. */
  50494. case OP_VNext: { /* jump */
  50495. sqlite3_vtab *pVtab;
  50496. const sqlite3_module *pModule;
  50497. int res = 0;
  50498. VdbeCursor *pCur = p->apCsr[pOp->p1];
  50499. assert( pCur->pVtabCursor );
  50500. if( pCur->nullRow ){
  50501. break;
  50502. }
  50503. pVtab = pCur->pVtabCursor->pVtab;
  50504. pModule = pVtab->pModule;
  50505. assert( pModule->xNext );
  50506. /* Invoke the xNext() method of the module. There is no way for the
  50507. ** underlying implementation to return an error if one occurs during
  50508. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  50509. ** data is available) and the error code returned when xColumn or
  50510. ** some other method is next invoked on the save virtual table cursor.
  50511. */
  50512. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  50513. sqlite3VtabLock(pVtab);
  50514. p->inVtabMethod = 1;
  50515. rc = pModule->xNext(pCur->pVtabCursor);
  50516. p->inVtabMethod = 0;
  50517. sqlite3DbFree(db, p->zErrMsg);
  50518. p->zErrMsg = pVtab->zErrMsg;
  50519. pVtab->zErrMsg = 0;
  50520. sqlite3VtabUnlock(db, pVtab);
  50521. if( rc==SQLITE_OK ){
  50522. res = pModule->xEof(pCur->pVtabCursor);
  50523. }
  50524. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  50525. if( !res ){
  50526. /* If there is data, jump to P2 */
  50527. pc = pOp->p2 - 1;
  50528. }
  50529. break;
  50530. }
  50531. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50532. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50533. /* Opcode: VRename P1 * * P4 *
  50534. **
  50535. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  50536. ** This opcode invokes the corresponding xRename method. The value
  50537. ** in register P1 is passed as the zName argument to the xRename method.
  50538. */
  50539. case OP_VRename: {
  50540. sqlite3_vtab *pVtab = pOp->p4.pVtab;
  50541. Mem *pName = &p->aMem[pOp->p1];
  50542. assert( pVtab->pModule->xRename );
  50543. REGISTER_TRACE(pOp->p1, pName);
  50544. Stringify(pName, encoding);
  50545. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  50546. sqlite3VtabLock(pVtab);
  50547. rc = pVtab->pModule->xRename(pVtab, pName->z);
  50548. sqlite3DbFree(db, p->zErrMsg);
  50549. p->zErrMsg = pVtab->zErrMsg;
  50550. pVtab->zErrMsg = 0;
  50551. sqlite3VtabUnlock(db, pVtab);
  50552. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  50553. break;
  50554. }
  50555. #endif
  50556. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50557. /* Opcode: VUpdate P1 P2 P3 P4 *
  50558. **
  50559. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  50560. ** This opcode invokes the corresponding xUpdate method. P2 values
  50561. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  50562. ** invocation. The value in register (P3+P2-1) corresponds to the
  50563. ** p2th element of the argv array passed to xUpdate.
  50564. **
  50565. ** The xUpdate method will do a DELETE or an INSERT or both.
  50566. ** The argv[0] element (which corresponds to memory cell P3)
  50567. ** is the rowid of a row to delete. If argv[0] is NULL then no
  50568. ** deletion occurs. The argv[1] element is the rowid of the new
  50569. ** row. This can be NULL to have the virtual table select the new
  50570. ** rowid for itself. The subsequent elements in the array are
  50571. ** the values of columns in the new row.
  50572. **
  50573. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  50574. ** a row to delete.
  50575. **
  50576. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  50577. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  50578. ** is set to the value of the rowid for the row just inserted.
  50579. */
  50580. case OP_VUpdate: {
  50581. sqlite3_vtab *pVtab = pOp->p4.pVtab;
  50582. sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
  50583. int nArg = pOp->p2;
  50584. assert( pOp->p4type==P4_VTAB );
  50585. if( pModule->xUpdate==0 ){
  50586. sqlite3SetString(&p->zErrMsg, db, "read-only table");
  50587. rc = SQLITE_ERROR;
  50588. }else{
  50589. int i;
  50590. sqlite_int64 rowid;
  50591. Mem **apArg = p->apArg;
  50592. Mem *pX = &p->aMem[pOp->p3];
  50593. for(i=0; i<nArg; i++){
  50594. storeTypeInfo(pX, 0);
  50595. apArg[i] = pX;
  50596. pX++;
  50597. }
  50598. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  50599. sqlite3VtabLock(pVtab);
  50600. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  50601. sqlite3DbFree(db, p->zErrMsg);
  50602. p->zErrMsg = pVtab->zErrMsg;
  50603. pVtab->zErrMsg = 0;
  50604. sqlite3VtabUnlock(db, pVtab);
  50605. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  50606. if( pOp->p1 && rc==SQLITE_OK ){
  50607. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  50608. db->lastRowid = rowid;
  50609. }
  50610. p->nChange++;
  50611. }
  50612. break;
  50613. }
  50614. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50615. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  50616. /* Opcode: Pagecount P1 P2 * * *
  50617. **
  50618. ** Write the current number of pages in database P1 to memory cell P2.
  50619. */
  50620. case OP_Pagecount: { /* out2-prerelease */
  50621. int p1 = pOp->p1;
  50622. int nPage;
  50623. Pager *pPager = sqlite3BtreePager(db->aDb[p1].pBt);
  50624. rc = sqlite3PagerPagecount(pPager, &nPage);
  50625. if( rc==SQLITE_OK ){
  50626. pOut->flags = MEM_Int;
  50627. pOut->u.i = nPage;
  50628. }
  50629. break;
  50630. }
  50631. #endif
  50632. #ifndef SQLITE_OMIT_TRACE
  50633. /* Opcode: Trace * * * P4 *
  50634. **
  50635. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  50636. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  50637. */
  50638. case OP_Trace: {
  50639. if( pOp->p4.z ){
  50640. if( db->xTrace ){
  50641. db->xTrace(db->pTraceArg, pOp->p4.z);
  50642. }
  50643. #ifdef SQLITE_DEBUG
  50644. if( (db->flags & SQLITE_SqlTrace)!=0 ){
  50645. sqlite3DebugPrintf("SQL-trace: %s\n", pOp->p4.z);
  50646. }
  50647. #endif /* SQLITE_DEBUG */
  50648. }
  50649. break;
  50650. }
  50651. #endif
  50652. /* Opcode: Noop * * * * *
  50653. **
  50654. ** Do nothing. This instruction is often useful as a jump
  50655. ** destination.
  50656. */
  50657. /*
  50658. ** The magic Explain opcode are only inserted when explain==2 (which
  50659. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  50660. ** This opcode records information from the optimizer. It is the
  50661. ** the same as a no-op. This opcodesnever appears in a real VM program.
  50662. */
  50663. default: { /* This is really OP_Noop and OP_Explain */
  50664. break;
  50665. }
  50666. /*****************************************************************************
  50667. ** The cases of the switch statement above this line should all be indented
  50668. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  50669. ** readability. From this point on down, the normal indentation rules are
  50670. ** restored.
  50671. *****************************************************************************/
  50672. }
  50673. #ifdef VDBE_PROFILE
  50674. {
  50675. u64 elapsed = sqlite3Hwtime() - start;
  50676. pOp->cycles += elapsed;
  50677. pOp->cnt++;
  50678. #if 0
  50679. fprintf(stdout, "%10llu ", elapsed);
  50680. sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
  50681. #endif
  50682. }
  50683. #endif
  50684. /* The following code adds nothing to the actual functionality
  50685. ** of the program. It is only here for testing and debugging.
  50686. ** On the other hand, it does burn CPU cycles every time through
  50687. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  50688. */
  50689. #ifndef NDEBUG
  50690. assert( pc>=-1 && pc<p->nOp );
  50691. #ifdef SQLITE_DEBUG
  50692. if( p->trace ){
  50693. if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
  50694. if( opProperty & OPFLG_OUT2_PRERELEASE ){
  50695. registerTrace(p->trace, pOp->p2, pOut);
  50696. }
  50697. if( opProperty & OPFLG_OUT3 ){
  50698. registerTrace(p->trace, pOp->p3, pOut);
  50699. }
  50700. }
  50701. #endif /* SQLITE_DEBUG */
  50702. #endif /* NDEBUG */
  50703. } /* The end of the for(;;) loop the loops through opcodes */
  50704. /* If we reach this point, it means that execution is finished with
  50705. ** an error of some kind.
  50706. */
  50707. vdbe_error_halt:
  50708. assert( rc );
  50709. p->rc = rc;
  50710. sqlite3VdbeHalt(p);
  50711. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  50712. rc = SQLITE_ERROR;
  50713. /* This is the only way out of this procedure. We have to
  50714. ** release the mutexes on btrees that were acquired at the
  50715. ** top. */
  50716. vdbe_return:
  50717. sqlite3BtreeMutexArrayLeave(&p->aMutex);
  50718. return rc;
  50719. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  50720. ** is encountered.
  50721. */
  50722. too_big:
  50723. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  50724. rc = SQLITE_TOOBIG;
  50725. goto vdbe_error_halt;
  50726. /* Jump to here if a malloc() fails.
  50727. */
  50728. no_mem:
  50729. db->mallocFailed = 1;
  50730. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  50731. rc = SQLITE_NOMEM;
  50732. goto vdbe_error_halt;
  50733. /* Jump to here for an SQLITE_MISUSE error.
  50734. */
  50735. abort_due_to_misuse:
  50736. rc = SQLITE_MISUSE;
  50737. /* Fall thru into abort_due_to_error */
  50738. /* Jump to here for any other kind of fatal error. The "rc" variable
  50739. ** should hold the error number.
  50740. */
  50741. abort_due_to_error:
  50742. assert( p->zErrMsg==0 );
  50743. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  50744. if( rc!=SQLITE_IOERR_NOMEM ){
  50745. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  50746. }
  50747. goto vdbe_error_halt;
  50748. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  50749. ** flag.
  50750. */
  50751. abort_due_to_interrupt:
  50752. assert( db->u1.isInterrupted );
  50753. rc = SQLITE_INTERRUPT;
  50754. p->rc = rc;
  50755. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  50756. goto vdbe_error_halt;
  50757. }
  50758. /************** End of vdbe.c ************************************************/
  50759. /************** Begin file vdbeblob.c ****************************************/
  50760. /*
  50761. ** 2007 May 1
  50762. **
  50763. ** The author disclaims copyright to this source code. In place of
  50764. ** a legal notice, here is a blessing:
  50765. **
  50766. ** May you do good and not evil.
  50767. ** May you find forgiveness for yourself and forgive others.
  50768. ** May you share freely, never taking more than you give.
  50769. **
  50770. *************************************************************************
  50771. **
  50772. ** This file contains code used to implement incremental BLOB I/O.
  50773. **
  50774. ** $Id: vdbeblob.c,v 1.26 2008/10/02 14:49:02 danielk1977 Exp $
  50775. */
  50776. #ifndef SQLITE_OMIT_INCRBLOB
  50777. /*
  50778. ** Valid sqlite3_blob* handles point to Incrblob structures.
  50779. */
  50780. typedef struct Incrblob Incrblob;
  50781. struct Incrblob {
  50782. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  50783. int nByte; /* Size of open blob, in bytes */
  50784. int iOffset; /* Byte offset of blob in cursor data */
  50785. BtCursor *pCsr; /* Cursor pointing at blob row */
  50786. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  50787. sqlite3 *db; /* The associated database */
  50788. };
  50789. /*
  50790. ** Open a blob handle.
  50791. */
  50792. SQLITE_API int sqlite3_blob_open(
  50793. sqlite3* db, /* The database connection */
  50794. const char *zDb, /* The attached database containing the blob */
  50795. const char *zTable, /* The table containing the blob */
  50796. const char *zColumn, /* The column containing the blob */
  50797. sqlite_int64 iRow, /* The row containing the glob */
  50798. int flags, /* True -> read/write access, false -> read-only */
  50799. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  50800. ){
  50801. int nAttempt = 0;
  50802. int iCol; /* Index of zColumn in row-record */
  50803. /* This VDBE program seeks a btree cursor to the identified
  50804. ** db/table/row entry. The reason for using a vdbe program instead
  50805. ** of writing code to use the b-tree layer directly is that the
  50806. ** vdbe program will take advantage of the various transaction,
  50807. ** locking and error handling infrastructure built into the vdbe.
  50808. **
  50809. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  50810. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  50811. ** uses it to implement the blob_read(), blob_write() and
  50812. ** blob_bytes() functions.
  50813. **
  50814. ** The sqlite3_blob_close() function finalizes the vdbe program,
  50815. ** which closes the b-tree cursor and (possibly) commits the
  50816. ** transaction.
  50817. */
  50818. static const VdbeOpList openBlob[] = {
  50819. {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
  50820. {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
  50821. /* One of the following two instructions is replaced by an
  50822. ** OP_Noop before exection.
  50823. */
  50824. {OP_SetNumColumns, 0, 0, 0}, /* 2: Num cols for cursor */
  50825. {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
  50826. {OP_SetNumColumns, 0, 0, 0}, /* 4: Num cols for cursor */
  50827. {OP_OpenWrite, 0, 0, 0}, /* 5: Open cursor 0 for read/write */
  50828. {OP_Variable, 1, 1, 0}, /* 6: Push the rowid to the stack */
  50829. {OP_NotExists, 0, 10, 1}, /* 7: Seek the cursor */
  50830. {OP_Column, 0, 0, 1}, /* 8 */
  50831. {OP_ResultRow, 1, 0, 0}, /* 9 */
  50832. {OP_Close, 0, 0, 0}, /* 10 */
  50833. {OP_Halt, 0, 0, 0}, /* 11 */
  50834. };
  50835. Vdbe *v = 0;
  50836. int rc = SQLITE_OK;
  50837. char zErr[128];
  50838. zErr[0] = 0;
  50839. sqlite3_mutex_enter(db->mutex);
  50840. do {
  50841. Parse sParse;
  50842. Table *pTab;
  50843. memset(&sParse, 0, sizeof(Parse));
  50844. sParse.db = db;
  50845. if( sqlite3SafetyOn(db) ){
  50846. sqlite3_mutex_leave(db->mutex);
  50847. return SQLITE_MISUSE;
  50848. }
  50849. sqlite3BtreeEnterAll(db);
  50850. pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
  50851. if( pTab && IsVirtual(pTab) ){
  50852. pTab = 0;
  50853. sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
  50854. }
  50855. #ifndef SQLITE_OMIT_VIEW
  50856. if( pTab && pTab->pSelect ){
  50857. pTab = 0;
  50858. sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
  50859. }
  50860. #endif
  50861. if( !pTab ){
  50862. if( sParse.zErrMsg ){
  50863. sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
  50864. }
  50865. sqlite3DbFree(db, sParse.zErrMsg);
  50866. rc = SQLITE_ERROR;
  50867. (void)sqlite3SafetyOff(db);
  50868. sqlite3BtreeLeaveAll(db);
  50869. goto blob_open_out;
  50870. }
  50871. /* Now search pTab for the exact column. */
  50872. for(iCol=0; iCol < pTab->nCol; iCol++) {
  50873. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  50874. break;
  50875. }
  50876. }
  50877. if( iCol==pTab->nCol ){
  50878. sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
  50879. rc = SQLITE_ERROR;
  50880. (void)sqlite3SafetyOff(db);
  50881. sqlite3BtreeLeaveAll(db);
  50882. goto blob_open_out;
  50883. }
  50884. /* If the value is being opened for writing, check that the
  50885. ** column is not indexed. It is against the rules to open an
  50886. ** indexed column for writing.
  50887. */
  50888. if( flags ){
  50889. Index *pIdx;
  50890. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  50891. int j;
  50892. for(j=0; j<pIdx->nColumn; j++){
  50893. if( pIdx->aiColumn[j]==iCol ){
  50894. sqlite3_snprintf(sizeof(zErr), zErr,
  50895. "cannot open indexed column for writing");
  50896. rc = SQLITE_ERROR;
  50897. (void)sqlite3SafetyOff(db);
  50898. sqlite3BtreeLeaveAll(db);
  50899. goto blob_open_out;
  50900. }
  50901. }
  50902. }
  50903. }
  50904. v = sqlite3VdbeCreate(db);
  50905. if( v ){
  50906. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  50907. sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
  50908. /* Configure the OP_Transaction */
  50909. sqlite3VdbeChangeP1(v, 0, iDb);
  50910. sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
  50911. /* Configure the OP_VerifyCookie */
  50912. sqlite3VdbeChangeP1(v, 1, iDb);
  50913. sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
  50914. /* Make sure a mutex is held on the table to be accessed */
  50915. sqlite3VdbeUsesBtree(v, iDb);
  50916. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  50917. ** parameter of the other to pTab->tnum.
  50918. */
  50919. sqlite3VdbeChangeToNoop(v, (flags ? 3 : 5), 1);
  50920. sqlite3VdbeChangeP2(v, (flags ? 5 : 3), pTab->tnum);
  50921. sqlite3VdbeChangeP3(v, (flags ? 5 : 3), iDb);
  50922. /* Configure the OP_SetNumColumns. Configure the cursor to
  50923. ** think that the table has one more column than it really
  50924. ** does. An OP_Column to retrieve this imaginary column will
  50925. ** always return an SQL NULL. This is useful because it means
  50926. ** we can invoke OP_Column to fill in the vdbe cursors type
  50927. ** and offset cache without causing any IO.
  50928. */
  50929. sqlite3VdbeChangeP2(v, flags ? 4 : 2, pTab->nCol+1);
  50930. sqlite3VdbeChangeP2(v, 8, pTab->nCol);
  50931. if( !db->mallocFailed ){
  50932. sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
  50933. }
  50934. }
  50935. sqlite3BtreeLeaveAll(db);
  50936. rc = sqlite3SafetyOff(db);
  50937. if( rc!=SQLITE_OK || db->mallocFailed ){
  50938. goto blob_open_out;
  50939. }
  50940. sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
  50941. rc = sqlite3_step((sqlite3_stmt *)v);
  50942. if( rc!=SQLITE_ROW ){
  50943. nAttempt++;
  50944. rc = sqlite3_finalize((sqlite3_stmt *)v);
  50945. sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
  50946. v = 0;
  50947. }
  50948. } while( nAttempt<5 && rc==SQLITE_SCHEMA );
  50949. if( rc==SQLITE_ROW ){
  50950. /* The row-record has been opened successfully. Check that the
  50951. ** column in question contains text or a blob. If it contains
  50952. ** text, it is up to the caller to get the encoding right.
  50953. */
  50954. Incrblob *pBlob;
  50955. u32 type = v->apCsr[0]->aType[iCol];
  50956. if( type<12 ){
  50957. sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
  50958. type==0?"null": type==7?"real": "integer"
  50959. );
  50960. rc = SQLITE_ERROR;
  50961. goto blob_open_out;
  50962. }
  50963. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  50964. if( db->mallocFailed ){
  50965. sqlite3DbFree(db, pBlob);
  50966. goto blob_open_out;
  50967. }
  50968. pBlob->flags = flags;
  50969. pBlob->pCsr = v->apCsr[0]->pCursor;
  50970. sqlite3BtreeEnterCursor(pBlob->pCsr);
  50971. sqlite3BtreeCacheOverflow(pBlob->pCsr);
  50972. sqlite3BtreeLeaveCursor(pBlob->pCsr);
  50973. pBlob->pStmt = (sqlite3_stmt *)v;
  50974. pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
  50975. pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
  50976. pBlob->db = db;
  50977. *ppBlob = (sqlite3_blob *)pBlob;
  50978. rc = SQLITE_OK;
  50979. }else if( rc==SQLITE_OK ){
  50980. sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
  50981. rc = SQLITE_ERROR;
  50982. }
  50983. blob_open_out:
  50984. zErr[sizeof(zErr)-1] = '\0';
  50985. if( rc!=SQLITE_OK || db->mallocFailed ){
  50986. sqlite3_finalize((sqlite3_stmt *)v);
  50987. }
  50988. sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
  50989. rc = sqlite3ApiExit(db, rc);
  50990. sqlite3_mutex_leave(db->mutex);
  50991. return rc;
  50992. }
  50993. /*
  50994. ** Close a blob handle that was previously created using
  50995. ** sqlite3_blob_open().
  50996. */
  50997. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  50998. Incrblob *p = (Incrblob *)pBlob;
  50999. int rc;
  51000. rc = sqlite3_finalize(p->pStmt);
  51001. sqlite3DbFree(p->db, p);
  51002. return rc;
  51003. }
  51004. /*
  51005. ** Perform a read or write operation on a blob
  51006. */
  51007. static int blobReadWrite(
  51008. sqlite3_blob *pBlob,
  51009. void *z,
  51010. int n,
  51011. int iOffset,
  51012. int (*xCall)(BtCursor*, u32, u32, void*)
  51013. ){
  51014. int rc;
  51015. Incrblob *p = (Incrblob *)pBlob;
  51016. Vdbe *v;
  51017. sqlite3 *db = p->db;
  51018. sqlite3_mutex_enter(db->mutex);
  51019. v = (Vdbe*)p->pStmt;
  51020. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  51021. /* Request is out of range. Return a transient error. */
  51022. rc = SQLITE_ERROR;
  51023. sqlite3Error(db, SQLITE_ERROR, 0);
  51024. } else if( v==0 ){
  51025. /* If there is no statement handle, then the blob-handle has
  51026. ** already been invalidated. Return SQLITE_ABORT in this case.
  51027. */
  51028. rc = SQLITE_ABORT;
  51029. }else{
  51030. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  51031. ** returned, clean-up the statement handle.
  51032. */
  51033. assert( db == v->db );
  51034. sqlite3BtreeEnterCursor(p->pCsr);
  51035. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  51036. sqlite3BtreeLeaveCursor(p->pCsr);
  51037. if( rc==SQLITE_ABORT ){
  51038. sqlite3VdbeFinalize(v);
  51039. p->pStmt = 0;
  51040. }else{
  51041. db->errCode = rc;
  51042. v->rc = rc;
  51043. }
  51044. }
  51045. rc = sqlite3ApiExit(db, rc);
  51046. sqlite3_mutex_leave(db->mutex);
  51047. return rc;
  51048. }
  51049. /*
  51050. ** Read data from a blob handle.
  51051. */
  51052. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  51053. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  51054. }
  51055. /*
  51056. ** Write data to a blob handle.
  51057. */
  51058. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  51059. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  51060. }
  51061. /*
  51062. ** Query a blob handle for the size of the data.
  51063. **
  51064. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  51065. ** so no mutex is required for access.
  51066. */
  51067. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  51068. Incrblob *p = (Incrblob *)pBlob;
  51069. return p->nByte;
  51070. }
  51071. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  51072. /************** End of vdbeblob.c ********************************************/
  51073. /************** Begin file journal.c *****************************************/
  51074. /*
  51075. ** 2007 August 22
  51076. **
  51077. ** The author disclaims copyright to this source code. In place of
  51078. ** a legal notice, here is a blessing:
  51079. **
  51080. ** May you do good and not evil.
  51081. ** May you find forgiveness for yourself and forgive others.
  51082. ** May you share freely, never taking more than you give.
  51083. **
  51084. *************************************************************************
  51085. **
  51086. ** @(#) $Id: journal.c,v 1.8 2008/05/01 18:01:47 drh Exp $
  51087. */
  51088. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  51089. /*
  51090. ** This file implements a special kind of sqlite3_file object used
  51091. ** by SQLite to create journal files if the atomic-write optimization
  51092. ** is enabled.
  51093. **
  51094. ** The distinctive characteristic of this sqlite3_file is that the
  51095. ** actual on disk file is created lazily. When the file is created,
  51096. ** the caller specifies a buffer size for an in-memory buffer to
  51097. ** be used to service read() and write() requests. The actual file
  51098. ** on disk is not created or populated until either:
  51099. **
  51100. ** 1) The in-memory representation grows too large for the allocated
  51101. ** buffer, or
  51102. ** 2) The xSync() method is called.
  51103. */
  51104. /*
  51105. ** A JournalFile object is a subclass of sqlite3_file used by
  51106. ** as an open file handle for journal files.
  51107. */
  51108. struct JournalFile {
  51109. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  51110. int nBuf; /* Size of zBuf[] in bytes */
  51111. char *zBuf; /* Space to buffer journal writes */
  51112. int iSize; /* Amount of zBuf[] currently used */
  51113. int flags; /* xOpen flags */
  51114. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  51115. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  51116. const char *zJournal; /* Name of the journal file */
  51117. };
  51118. typedef struct JournalFile JournalFile;
  51119. /*
  51120. ** If it does not already exists, create and populate the on-disk file
  51121. ** for JournalFile p.
  51122. */
  51123. static int createFile(JournalFile *p){
  51124. int rc = SQLITE_OK;
  51125. if( !p->pReal ){
  51126. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  51127. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  51128. if( rc==SQLITE_OK ){
  51129. p->pReal = pReal;
  51130. if( p->iSize>0 ){
  51131. assert(p->iSize<=p->nBuf);
  51132. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  51133. }
  51134. }
  51135. }
  51136. return rc;
  51137. }
  51138. /*
  51139. ** Close the file.
  51140. */
  51141. static int jrnlClose(sqlite3_file *pJfd){
  51142. JournalFile *p = (JournalFile *)pJfd;
  51143. if( p->pReal ){
  51144. sqlite3OsClose(p->pReal);
  51145. }
  51146. sqlite3_free(p->zBuf);
  51147. return SQLITE_OK;
  51148. }
  51149. /*
  51150. ** Read data from the file.
  51151. */
  51152. static int jrnlRead(
  51153. sqlite3_file *pJfd, /* The journal file from which to read */
  51154. void *zBuf, /* Put the results here */
  51155. int iAmt, /* Number of bytes to read */
  51156. sqlite_int64 iOfst /* Begin reading at this offset */
  51157. ){
  51158. int rc = SQLITE_OK;
  51159. JournalFile *p = (JournalFile *)pJfd;
  51160. if( p->pReal ){
  51161. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  51162. }else{
  51163. assert( iAmt+iOfst<=p->iSize );
  51164. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  51165. }
  51166. return rc;
  51167. }
  51168. /*
  51169. ** Write data to the file.
  51170. */
  51171. static int jrnlWrite(
  51172. sqlite3_file *pJfd, /* The journal file into which to write */
  51173. const void *zBuf, /* Take data to be written from here */
  51174. int iAmt, /* Number of bytes to write */
  51175. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  51176. ){
  51177. int rc = SQLITE_OK;
  51178. JournalFile *p = (JournalFile *)pJfd;
  51179. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  51180. rc = createFile(p);
  51181. }
  51182. if( rc==SQLITE_OK ){
  51183. if( p->pReal ){
  51184. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  51185. }else{
  51186. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  51187. if( p->iSize<(iOfst+iAmt) ){
  51188. p->iSize = (iOfst+iAmt);
  51189. }
  51190. }
  51191. }
  51192. return rc;
  51193. }
  51194. /*
  51195. ** Truncate the file.
  51196. */
  51197. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  51198. int rc = SQLITE_OK;
  51199. JournalFile *p = (JournalFile *)pJfd;
  51200. if( p->pReal ){
  51201. rc = sqlite3OsTruncate(p->pReal, size);
  51202. }else if( size<p->iSize ){
  51203. p->iSize = size;
  51204. }
  51205. return rc;
  51206. }
  51207. /*
  51208. ** Sync the file.
  51209. */
  51210. static int jrnlSync(sqlite3_file *pJfd, int flags){
  51211. int rc;
  51212. JournalFile *p = (JournalFile *)pJfd;
  51213. if( p->pReal ){
  51214. rc = sqlite3OsSync(p->pReal, flags);
  51215. }else{
  51216. rc = SQLITE_OK;
  51217. }
  51218. return rc;
  51219. }
  51220. /*
  51221. ** Query the size of the file in bytes.
  51222. */
  51223. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  51224. int rc = SQLITE_OK;
  51225. JournalFile *p = (JournalFile *)pJfd;
  51226. if( p->pReal ){
  51227. rc = sqlite3OsFileSize(p->pReal, pSize);
  51228. }else{
  51229. *pSize = (sqlite_int64) p->iSize;
  51230. }
  51231. return rc;
  51232. }
  51233. /*
  51234. ** Table of methods for JournalFile sqlite3_file object.
  51235. */
  51236. static struct sqlite3_io_methods JournalFileMethods = {
  51237. 1, /* iVersion */
  51238. jrnlClose, /* xClose */
  51239. jrnlRead, /* xRead */
  51240. jrnlWrite, /* xWrite */
  51241. jrnlTruncate, /* xTruncate */
  51242. jrnlSync, /* xSync */
  51243. jrnlFileSize, /* xFileSize */
  51244. 0, /* xLock */
  51245. 0, /* xUnlock */
  51246. 0, /* xCheckReservedLock */
  51247. 0, /* xFileControl */
  51248. 0, /* xSectorSize */
  51249. 0 /* xDeviceCharacteristics */
  51250. };
  51251. /*
  51252. ** Open a journal file.
  51253. */
  51254. SQLITE_PRIVATE int sqlite3JournalOpen(
  51255. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  51256. const char *zName, /* Name of the journal file */
  51257. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  51258. int flags, /* Opening flags */
  51259. int nBuf /* Bytes buffered before opening the file */
  51260. ){
  51261. JournalFile *p = (JournalFile *)pJfd;
  51262. memset(p, 0, sqlite3JournalSize(pVfs));
  51263. if( nBuf>0 ){
  51264. p->zBuf = sqlite3MallocZero(nBuf);
  51265. if( !p->zBuf ){
  51266. return SQLITE_NOMEM;
  51267. }
  51268. }else{
  51269. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  51270. }
  51271. p->pMethod = &JournalFileMethods;
  51272. p->nBuf = nBuf;
  51273. p->flags = flags;
  51274. p->zJournal = zName;
  51275. p->pVfs = pVfs;
  51276. return SQLITE_OK;
  51277. }
  51278. /*
  51279. ** If the argument p points to a JournalFile structure, and the underlying
  51280. ** file has not yet been created, create it now.
  51281. */
  51282. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  51283. if( p->pMethods!=&JournalFileMethods ){
  51284. return SQLITE_OK;
  51285. }
  51286. return createFile((JournalFile *)p);
  51287. }
  51288. /*
  51289. ** Return the number of bytes required to store a JournalFile that uses vfs
  51290. ** pVfs to create the underlying on-disk files.
  51291. */
  51292. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  51293. return (pVfs->szOsFile+sizeof(JournalFile));
  51294. }
  51295. #endif
  51296. /************** End of journal.c *********************************************/
  51297. /************** Begin file memjournal.c **************************************/
  51298. /*
  51299. ** 2008 October 7
  51300. **
  51301. ** The author disclaims copyright to this source code. In place of
  51302. ** a legal notice, here is a blessing:
  51303. **
  51304. ** May you do good and not evil.
  51305. ** May you find forgiveness for yourself and forgive others.
  51306. ** May you share freely, never taking more than you give.
  51307. **
  51308. *************************************************************************
  51309. **
  51310. ** This file contains code use to implement an in-memory rollback journal.
  51311. ** The in-memory rollback journal is used to journal transactions for
  51312. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  51313. **
  51314. ** @(#) $Id: memjournal.c,v 1.8 2008/12/20 02:14:40 drh Exp $
  51315. */
  51316. /* Forward references to internal structures */
  51317. typedef struct MemJournal MemJournal;
  51318. typedef struct FilePoint FilePoint;
  51319. typedef struct FileChunk FileChunk;
  51320. /* Space to hold the rollback journal is allocated in increments of
  51321. ** this many bytes.
  51322. */
  51323. #define JOURNAL_CHUNKSIZE 1024
  51324. /* Macro to find the minimum of two numeric values.
  51325. */
  51326. #ifndef MIN
  51327. # define MIN(x,y) ((x)<(y)?(x):(y))
  51328. #endif
  51329. /*
  51330. ** The rollback journal is composed of a linked list of these structures.
  51331. */
  51332. struct FileChunk {
  51333. FileChunk *pNext; /* Next chunk in the journal */
  51334. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  51335. };
  51336. /*
  51337. ** An instance of this object serves as a cursor into the rollback journal.
  51338. ** The cursor can be either for reading or writing.
  51339. */
  51340. struct FilePoint {
  51341. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  51342. FileChunk *pChunk; /* Specific chunk into which cursor points */
  51343. };
  51344. /*
  51345. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  51346. ** is an instance of this class.
  51347. */
  51348. struct MemJournal {
  51349. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  51350. FileChunk *pFirst; /* Head of in-memory chunk-list */
  51351. FilePoint endpoint; /* Pointer to the end of the file */
  51352. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  51353. };
  51354. /*
  51355. ** Read data from the file.
  51356. */
  51357. static int memjrnlRead(
  51358. sqlite3_file *pJfd, /* The journal file from which to read */
  51359. void *zBuf, /* Put the results here */
  51360. int iAmt, /* Number of bytes to read */
  51361. sqlite_int64 iOfst /* Begin reading at this offset */
  51362. ){
  51363. MemJournal *p = (MemJournal *)pJfd;
  51364. u8 *zOut = zBuf;
  51365. int nRead = iAmt;
  51366. int iChunkOffset;
  51367. FileChunk *pChunk;
  51368. assert( iOfst+iAmt<=p->endpoint.iOffset );
  51369. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  51370. sqlite3_int64 iOff = 0;
  51371. for(pChunk=p->pFirst;
  51372. pChunk && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  51373. pChunk=pChunk->pNext
  51374. ){
  51375. iOff += JOURNAL_CHUNKSIZE;
  51376. }
  51377. }else{
  51378. pChunk = p->readpoint.pChunk;
  51379. }
  51380. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  51381. do {
  51382. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  51383. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  51384. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  51385. zOut += nCopy;
  51386. nRead -= iSpace;
  51387. iChunkOffset = 0;
  51388. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  51389. p->readpoint.iOffset = iOfst+iAmt;
  51390. p->readpoint.pChunk = pChunk;
  51391. return SQLITE_OK;
  51392. }
  51393. /*
  51394. ** Write data to the file.
  51395. */
  51396. static int memjrnlWrite(
  51397. sqlite3_file *pJfd, /* The journal file into which to write */
  51398. const void *zBuf, /* Take data to be written from here */
  51399. int iAmt, /* Number of bytes to write */
  51400. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  51401. ){
  51402. MemJournal *p = (MemJournal *)pJfd;
  51403. int nWrite = iAmt;
  51404. u8 *zWrite = (u8 *)zBuf;
  51405. /* An in-memory journal file should only ever be appended to. Random
  51406. ** access writes are not required by sqlite.
  51407. */
  51408. assert(iOfst==p->endpoint.iOffset);
  51409. UNUSED_PARAMETER(iOfst);
  51410. while( nWrite>0 ){
  51411. FileChunk *pChunk = p->endpoint.pChunk;
  51412. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  51413. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  51414. if( iChunkOffset==0 ){
  51415. /* New chunk is required to extend the file. */
  51416. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  51417. if( !pNew ){
  51418. return SQLITE_IOERR_NOMEM;
  51419. }
  51420. pNew->pNext = 0;
  51421. if( pChunk ){
  51422. assert( p->pFirst );
  51423. pChunk->pNext = pNew;
  51424. }else{
  51425. assert( !p->pFirst );
  51426. p->pFirst = pNew;
  51427. }
  51428. p->endpoint.pChunk = pNew;
  51429. }
  51430. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  51431. zWrite += iSpace;
  51432. nWrite -= iSpace;
  51433. p->endpoint.iOffset += iSpace;
  51434. }
  51435. return SQLITE_OK;
  51436. }
  51437. /*
  51438. ** Truncate the file.
  51439. */
  51440. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  51441. MemJournal *p = (MemJournal *)pJfd;
  51442. FileChunk *pChunk;
  51443. assert(size==0);
  51444. UNUSED_PARAMETER(size);
  51445. pChunk = p->pFirst;
  51446. while( pChunk ){
  51447. FileChunk *pTmp = pChunk;
  51448. pChunk = pChunk->pNext;
  51449. sqlite3_free(pTmp);
  51450. }
  51451. sqlite3MemJournalOpen(pJfd);
  51452. return SQLITE_OK;
  51453. }
  51454. /*
  51455. ** Close the file.
  51456. */
  51457. static int memjrnlClose(sqlite3_file *pJfd){
  51458. memjrnlTruncate(pJfd, 0);
  51459. return SQLITE_OK;
  51460. }
  51461. /*
  51462. ** Sync the file.
  51463. */
  51464. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  51465. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  51466. return SQLITE_OK;
  51467. }
  51468. /*
  51469. ** Query the size of the file in bytes.
  51470. */
  51471. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  51472. MemJournal *p = (MemJournal *)pJfd;
  51473. *pSize = (sqlite_int64) p->endpoint.iOffset;
  51474. return SQLITE_OK;
  51475. }
  51476. /*
  51477. ** Table of methods for MemJournal sqlite3_file object.
  51478. */
  51479. static struct sqlite3_io_methods MemJournalMethods = {
  51480. 1, /* iVersion */
  51481. memjrnlClose, /* xClose */
  51482. memjrnlRead, /* xRead */
  51483. memjrnlWrite, /* xWrite */
  51484. memjrnlTruncate, /* xTruncate */
  51485. memjrnlSync, /* xSync */
  51486. memjrnlFileSize, /* xFileSize */
  51487. 0, /* xLock */
  51488. 0, /* xUnlock */
  51489. 0, /* xCheckReservedLock */
  51490. 0, /* xFileControl */
  51491. 0, /* xSectorSize */
  51492. 0 /* xDeviceCharacteristics */
  51493. };
  51494. /*
  51495. ** Open a journal file.
  51496. */
  51497. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  51498. MemJournal *p = (MemJournal *)pJfd;
  51499. memset(p, 0, sqlite3MemJournalSize());
  51500. p->pMethod = &MemJournalMethods;
  51501. }
  51502. /*
  51503. ** Return true if the file-handle passed as an argument is
  51504. ** an in-memory journal
  51505. */
  51506. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  51507. return pJfd->pMethods==&MemJournalMethods;
  51508. }
  51509. /*
  51510. ** Return the number of bytes required to store a MemJournal that uses vfs
  51511. ** pVfs to create the underlying on-disk files.
  51512. */
  51513. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  51514. return sizeof(MemJournal);
  51515. }
  51516. /************** End of memjournal.c ******************************************/
  51517. /************** Begin file walker.c ******************************************/
  51518. /*
  51519. ** 2008 August 16
  51520. **
  51521. ** The author disclaims copyright to this source code. In place of
  51522. ** a legal notice, here is a blessing:
  51523. **
  51524. ** May you do good and not evil.
  51525. ** May you find forgiveness for yourself and forgive others.
  51526. ** May you share freely, never taking more than you give.
  51527. **
  51528. *************************************************************************
  51529. ** This file contains routines used for walking the parser tree for
  51530. ** an SQL statement.
  51531. **
  51532. ** $Id: walker.c,v 1.1 2008/08/20 16:35:10 drh Exp $
  51533. */
  51534. /*
  51535. ** Walk an expression tree. Invoke the callback once for each node
  51536. ** of the expression, while decending. (In other words, the callback
  51537. ** is invoked before visiting children.)
  51538. **
  51539. ** The return value from the callback should be one of the WRC_*
  51540. ** constants to specify how to proceed with the walk.
  51541. **
  51542. ** WRC_Continue Continue descending down the tree.
  51543. **
  51544. ** WRC_Prune Do not descend into child nodes. But allow
  51545. ** the walk to continue with sibling nodes.
  51546. **
  51547. ** WRC_Abort Do no more callbacks. Unwind the stack and
  51548. ** return the top-level walk call.
  51549. **
  51550. ** The return value from this routine is WRC_Abort to abandon the tree walk
  51551. ** and WRC_Continue to continue.
  51552. */
  51553. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  51554. int rc;
  51555. if( pExpr==0 ) return WRC_Continue;
  51556. rc = pWalker->xExprCallback(pWalker, pExpr);
  51557. if( rc==WRC_Continue ){
  51558. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  51559. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  51560. if( sqlite3WalkExprList(pWalker, pExpr->pList) ) return WRC_Abort;
  51561. if( sqlite3WalkSelect(pWalker, pExpr->pSelect) ){
  51562. return WRC_Abort;
  51563. }
  51564. }
  51565. return rc & WRC_Abort;
  51566. }
  51567. /*
  51568. ** Call sqlite3WalkExpr() for every expression in list p or until
  51569. ** an abort request is seen.
  51570. */
  51571. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  51572. int i, rc = WRC_Continue;
  51573. struct ExprList_item *pItem;
  51574. if( p ){
  51575. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  51576. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  51577. }
  51578. }
  51579. return rc & WRC_Continue;
  51580. }
  51581. /*
  51582. ** Walk all expressions associated with SELECT statement p. Do
  51583. ** not invoke the SELECT callback on p, but do (of course) invoke
  51584. ** any expr callbacks and SELECT callbacks that come from subqueries.
  51585. ** Return WRC_Abort or WRC_Continue.
  51586. */
  51587. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  51588. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  51589. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  51590. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  51591. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  51592. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  51593. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  51594. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  51595. return WRC_Continue;
  51596. }
  51597. /*
  51598. ** Walk the parse trees associated with all subqueries in the
  51599. ** FROM clause of SELECT statement p. Do not invoke the select
  51600. ** callback on p, but do invoke it on each FROM clause subquery
  51601. ** and on any subqueries further down in the tree. Return
  51602. ** WRC_Abort or WRC_Continue;
  51603. */
  51604. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  51605. SrcList *pSrc;
  51606. int i;
  51607. struct SrcList_item *pItem;
  51608. pSrc = p->pSrc;
  51609. if( pSrc ){
  51610. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  51611. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  51612. return WRC_Abort;
  51613. }
  51614. }
  51615. }
  51616. return WRC_Continue;
  51617. }
  51618. /*
  51619. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  51620. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  51621. ** on the compound select chain, p->pPrior.
  51622. **
  51623. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  51624. ** there is an abort request.
  51625. **
  51626. ** If the Walker does not have an xSelectCallback() then this routine
  51627. ** is a no-op returning WRC_Continue.
  51628. */
  51629. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  51630. int rc;
  51631. if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  51632. rc = WRC_Continue;
  51633. while( p ){
  51634. rc = pWalker->xSelectCallback(pWalker, p);
  51635. if( rc ) break;
  51636. if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
  51637. if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
  51638. p = p->pPrior;
  51639. }
  51640. return rc & WRC_Abort;
  51641. }
  51642. /************** End of walker.c **********************************************/
  51643. /************** Begin file resolve.c *****************************************/
  51644. /*
  51645. ** 2008 August 18
  51646. **
  51647. ** The author disclaims copyright to this source code. In place of
  51648. ** a legal notice, here is a blessing:
  51649. **
  51650. ** May you do good and not evil.
  51651. ** May you find forgiveness for yourself and forgive others.
  51652. ** May you share freely, never taking more than you give.
  51653. **
  51654. *************************************************************************
  51655. **
  51656. ** This file contains routines used for walking the parser tree and
  51657. ** resolve all identifiers by associating them with a particular
  51658. ** table and column.
  51659. **
  51660. ** $Id: resolve.c,v 1.15 2008/12/10 19:26:24 drh Exp $
  51661. */
  51662. /*
  51663. ** Turn the pExpr expression into an alias for the iCol-th column of the
  51664. ** result set in pEList.
  51665. **
  51666. ** If the result set column is a simple column reference, then this routine
  51667. ** makes an exact copy. But for any other kind of expression, this
  51668. ** routine make a copy of the result set column as the argument to the
  51669. ** TK_AS operator. The TK_AS operator causes the expression to be
  51670. ** evaluated just once and then reused for each alias.
  51671. **
  51672. ** The reason for suppressing the TK_AS term when the expression is a simple
  51673. ** column reference is so that the column reference will be recognized as
  51674. ** usable by indices within the WHERE clause processing logic.
  51675. **
  51676. ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
  51677. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  51678. **
  51679. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  51680. **
  51681. ** Is equivalent to:
  51682. **
  51683. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  51684. **
  51685. ** The result of random()%5 in the GROUP BY clause is probably different
  51686. ** from the result in the result-set. We might fix this someday. Or
  51687. ** then again, we might not...
  51688. */
  51689. static void resolveAlias(
  51690. Parse *pParse, /* Parsing context */
  51691. ExprList *pEList, /* A result set */
  51692. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  51693. Expr *pExpr, /* Transform this into an alias to the result set */
  51694. const char *zType /* "GROUP" or "ORDER" or "" */
  51695. ){
  51696. Expr *pOrig; /* The iCol-th column of the result set */
  51697. Expr *pDup; /* Copy of pOrig */
  51698. sqlite3 *db; /* The database connection */
  51699. assert( iCol>=0 && iCol<pEList->nExpr );
  51700. pOrig = pEList->a[iCol].pExpr;
  51701. assert( pOrig!=0 );
  51702. assert( pOrig->flags & EP_Resolved );
  51703. db = pParse->db;
  51704. pDup = sqlite3ExprDup(db, pOrig);
  51705. if( pDup==0 ) return;
  51706. if( pDup->op!=TK_COLUMN && zType[0]!='G' ){
  51707. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  51708. if( pDup==0 ) return;
  51709. if( pEList->a[iCol].iAlias==0 ){
  51710. pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
  51711. }
  51712. pDup->iTable = pEList->a[iCol].iAlias;
  51713. }
  51714. if( pExpr->flags & EP_ExpCollate ){
  51715. pDup->pColl = pExpr->pColl;
  51716. pDup->flags |= EP_ExpCollate;
  51717. }
  51718. sqlite3ExprClear(db, pExpr);
  51719. memcpy(pExpr, pDup, sizeof(*pExpr));
  51720. sqlite3DbFree(db, pDup);
  51721. }
  51722. /*
  51723. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  51724. ** that name in the set of source tables in pSrcList and make the pExpr
  51725. ** expression node refer back to that source column. The following changes
  51726. ** are made to pExpr:
  51727. **
  51728. ** pExpr->iDb Set the index in db->aDb[] of the database X
  51729. ** (even if X is implied).
  51730. ** pExpr->iTable Set to the cursor number for the table obtained
  51731. ** from pSrcList.
  51732. ** pExpr->pTab Points to the Table structure of X.Y (even if
  51733. ** X and/or Y are implied.)
  51734. ** pExpr->iColumn Set to the column number within the table.
  51735. ** pExpr->op Set to TK_COLUMN.
  51736. ** pExpr->pLeft Any expression this points to is deleted
  51737. ** pExpr->pRight Any expression this points to is deleted.
  51738. **
  51739. ** The pDbToken is the name of the database (the "X"). This value may be
  51740. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  51741. ** can be used. The pTableToken is the name of the table (the "Y"). This
  51742. ** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
  51743. ** means that the form of the name is Z and that columns from any table
  51744. ** can be used.
  51745. **
  51746. ** If the name cannot be resolved unambiguously, leave an error message
  51747. ** in pParse and return non-zero. Return zero on success.
  51748. */
  51749. static int lookupName(
  51750. Parse *pParse, /* The parsing context */
  51751. Token *pDbToken, /* Name of the database containing table, or NULL */
  51752. Token *pTableToken, /* Name of table containing column, or NULL */
  51753. Token *pColumnToken, /* Name of the column. */
  51754. NameContext *pNC, /* The name context used to resolve the name */
  51755. Expr *pExpr /* Make this EXPR node point to the selected column */
  51756. ){
  51757. char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
  51758. char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
  51759. char *zCol = 0; /* Name of the column. The "Z" */
  51760. int i, j; /* Loop counters */
  51761. int cnt = 0; /* Number of matching column names */
  51762. int cntTab = 0; /* Number of matching table names */
  51763. sqlite3 *db = pParse->db; /* The database connection */
  51764. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  51765. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  51766. NameContext *pTopNC = pNC; /* First namecontext in the list */
  51767. Schema *pSchema = 0; /* Schema of the expression */
  51768. assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
  51769. /* Dequote and zero-terminate the names */
  51770. zDb = sqlite3NameFromToken(db, pDbToken);
  51771. zTab = sqlite3NameFromToken(db, pTableToken);
  51772. zCol = sqlite3NameFromToken(db, pColumnToken);
  51773. if( db->mallocFailed ){
  51774. goto lookupname_end;
  51775. }
  51776. /* Initialize the node to no-match */
  51777. pExpr->iTable = -1;
  51778. pExpr->pTab = 0;
  51779. /* Start at the inner-most context and move outward until a match is found */
  51780. while( pNC && cnt==0 ){
  51781. ExprList *pEList;
  51782. SrcList *pSrcList = pNC->pSrcList;
  51783. if( pSrcList ){
  51784. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  51785. Table *pTab;
  51786. int iDb;
  51787. Column *pCol;
  51788. pTab = pItem->pTab;
  51789. assert( pTab!=0 && pTab->zName!=0 );
  51790. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  51791. assert( pTab->nCol>0 );
  51792. if( zTab ){
  51793. if( pItem->zAlias ){
  51794. char *zTabName = pItem->zAlias;
  51795. if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
  51796. }else{
  51797. char *zTabName = pTab->zName;
  51798. if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
  51799. if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
  51800. continue;
  51801. }
  51802. }
  51803. }
  51804. if( 0==(cntTab++) ){
  51805. pExpr->iTable = pItem->iCursor;
  51806. pExpr->pTab = pTab;
  51807. pSchema = pTab->pSchema;
  51808. pMatch = pItem;
  51809. }
  51810. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  51811. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  51812. IdList *pUsing;
  51813. cnt++;
  51814. pExpr->iTable = pItem->iCursor;
  51815. pExpr->pTab = pTab;
  51816. pMatch = pItem;
  51817. pSchema = pTab->pSchema;
  51818. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  51819. pExpr->iColumn = j==pTab->iPKey ? -1 : j;
  51820. if( i<pSrcList->nSrc-1 ){
  51821. if( pItem[1].jointype & JT_NATURAL ){
  51822. /* If this match occurred in the left table of a natural join,
  51823. ** then skip the right table to avoid a duplicate match */
  51824. pItem++;
  51825. i++;
  51826. }else if( (pUsing = pItem[1].pUsing)!=0 ){
  51827. /* If this match occurs on a column that is in the USING clause
  51828. ** of a join, skip the search of the right table of the join
  51829. ** to avoid a duplicate match there. */
  51830. int k;
  51831. for(k=0; k<pUsing->nId; k++){
  51832. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
  51833. pItem++;
  51834. i++;
  51835. break;
  51836. }
  51837. }
  51838. }
  51839. }
  51840. break;
  51841. }
  51842. }
  51843. }
  51844. }
  51845. #ifndef SQLITE_OMIT_TRIGGER
  51846. /* If we have not already resolved the name, then maybe
  51847. ** it is a new.* or old.* trigger argument reference
  51848. */
  51849. if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
  51850. TriggerStack *pTriggerStack = pParse->trigStack;
  51851. Table *pTab = 0;
  51852. u32 *piColMask = 0;
  51853. if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
  51854. pExpr->iTable = pTriggerStack->newIdx;
  51855. assert( pTriggerStack->pTab );
  51856. pTab = pTriggerStack->pTab;
  51857. piColMask = &(pTriggerStack->newColMask);
  51858. }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
  51859. pExpr->iTable = pTriggerStack->oldIdx;
  51860. assert( pTriggerStack->pTab );
  51861. pTab = pTriggerStack->pTab;
  51862. piColMask = &(pTriggerStack->oldColMask);
  51863. }
  51864. if( pTab ){
  51865. int iCol;
  51866. Column *pCol = pTab->aCol;
  51867. pSchema = pTab->pSchema;
  51868. cntTab++;
  51869. for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
  51870. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  51871. cnt++;
  51872. pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
  51873. pExpr->pTab = pTab;
  51874. if( iCol>=0 ){
  51875. testcase( iCol==31 );
  51876. testcase( iCol==32 );
  51877. *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
  51878. }
  51879. break;
  51880. }
  51881. }
  51882. }
  51883. }
  51884. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  51885. /*
  51886. ** Perhaps the name is a reference to the ROWID
  51887. */
  51888. if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
  51889. cnt = 1;
  51890. pExpr->iColumn = -1;
  51891. pExpr->affinity = SQLITE_AFF_INTEGER;
  51892. }
  51893. /*
  51894. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  51895. ** might refer to an result-set alias. This happens, for example, when
  51896. ** we are resolving names in the WHERE clause of the following command:
  51897. **
  51898. ** SELECT a+b AS x FROM table WHERE x<10;
  51899. **
  51900. ** In cases like this, replace pExpr with a copy of the expression that
  51901. ** forms the result set entry ("a+b" in the example) and return immediately.
  51902. ** Note that the expression in the result set should have already been
  51903. ** resolved by the time the WHERE clause is resolved.
  51904. */
  51905. if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
  51906. for(j=0; j<pEList->nExpr; j++){
  51907. char *zAs = pEList->a[j].zName;
  51908. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  51909. Expr *pOrig;
  51910. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  51911. assert( pExpr->pList==0 );
  51912. assert( pExpr->pSelect==0 );
  51913. pOrig = pEList->a[j].pExpr;
  51914. if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
  51915. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  51916. sqlite3DbFree(db, zCol);
  51917. return 2;
  51918. }
  51919. resolveAlias(pParse, pEList, j, pExpr, "");
  51920. cnt = 1;
  51921. pMatch = 0;
  51922. assert( zTab==0 && zDb==0 );
  51923. goto lookupname_end_2;
  51924. }
  51925. }
  51926. }
  51927. /* Advance to the next name context. The loop will exit when either
  51928. ** we have a match (cnt>0) or when we run out of name contexts.
  51929. */
  51930. if( cnt==0 ){
  51931. pNC = pNC->pNext;
  51932. }
  51933. }
  51934. /*
  51935. ** If X and Y are NULL (in other words if only the column name Z is
  51936. ** supplied) and the value of Z is enclosed in double-quotes, then
  51937. ** Z is a string literal if it doesn't match any column names. In that
  51938. ** case, we need to return right away and not make any changes to
  51939. ** pExpr.
  51940. **
  51941. ** Because no reference was made to outer contexts, the pNC->nRef
  51942. ** fields are not changed in any context.
  51943. */
  51944. if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
  51945. sqlite3DbFree(db, zCol);
  51946. pExpr->op = TK_STRING;
  51947. pExpr->pTab = 0;
  51948. return 0;
  51949. }
  51950. /*
  51951. ** cnt==0 means there was not match. cnt>1 means there were two or
  51952. ** more matches. Either way, we have an error.
  51953. */
  51954. if( cnt!=1 ){
  51955. const char *zErr;
  51956. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  51957. if( zDb ){
  51958. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  51959. }else if( zTab ){
  51960. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  51961. }else{
  51962. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  51963. }
  51964. pTopNC->nErr++;
  51965. }
  51966. /* If a column from a table in pSrcList is referenced, then record
  51967. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  51968. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  51969. ** column number is greater than the number of bits in the bitmask
  51970. ** then set the high-order bit of the bitmask.
  51971. */
  51972. if( pExpr->iColumn>=0 && pMatch!=0 ){
  51973. int n = pExpr->iColumn;
  51974. testcase( n==BMS-1 );
  51975. if( n>=BMS ){
  51976. n = BMS-1;
  51977. }
  51978. assert( pMatch->iCursor==pExpr->iTable );
  51979. pMatch->colUsed |= ((Bitmask)1)<<n;
  51980. }
  51981. lookupname_end:
  51982. /* Clean up and return
  51983. */
  51984. sqlite3DbFree(db, zDb);
  51985. sqlite3DbFree(db, zTab);
  51986. sqlite3ExprDelete(db, pExpr->pLeft);
  51987. pExpr->pLeft = 0;
  51988. sqlite3ExprDelete(db, pExpr->pRight);
  51989. pExpr->pRight = 0;
  51990. pExpr->op = TK_COLUMN;
  51991. lookupname_end_2:
  51992. sqlite3DbFree(db, zCol);
  51993. if( cnt==1 ){
  51994. assert( pNC!=0 );
  51995. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  51996. /* Increment the nRef value on all name contexts from TopNC up to
  51997. ** the point where the name matched. */
  51998. for(;;){
  51999. assert( pTopNC!=0 );
  52000. pTopNC->nRef++;
  52001. if( pTopNC==pNC ) break;
  52002. pTopNC = pTopNC->pNext;
  52003. }
  52004. return 0;
  52005. } else {
  52006. return 1;
  52007. }
  52008. }
  52009. /*
  52010. ** This routine is callback for sqlite3WalkExpr().
  52011. **
  52012. ** Resolve symbolic names into TK_COLUMN operators for the current
  52013. ** node in the expression tree. Return 0 to continue the search down
  52014. ** the tree or 2 to abort the tree walk.
  52015. **
  52016. ** This routine also does error checking and name resolution for
  52017. ** function names. The operator for aggregate functions is changed
  52018. ** to TK_AGG_FUNCTION.
  52019. */
  52020. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  52021. NameContext *pNC;
  52022. Parse *pParse;
  52023. pNC = pWalker->u.pNC;
  52024. assert( pNC!=0 );
  52025. pParse = pNC->pParse;
  52026. assert( pParse==pWalker->pParse );
  52027. if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  52028. ExprSetProperty(pExpr, EP_Resolved);
  52029. #ifndef NDEBUG
  52030. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  52031. SrcList *pSrcList = pNC->pSrcList;
  52032. int i;
  52033. for(i=0; i<pNC->pSrcList->nSrc; i++){
  52034. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  52035. }
  52036. }
  52037. #endif
  52038. switch( pExpr->op ){
  52039. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  52040. /* The special operator TK_ROW means use the rowid for the first
  52041. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  52042. ** clause processing on UPDATE and DELETE statements.
  52043. */
  52044. case TK_ROW: {
  52045. SrcList *pSrcList = pNC->pSrcList;
  52046. struct SrcList_item *pItem;
  52047. assert( pSrcList && pSrcList->nSrc==1 );
  52048. pItem = pSrcList->a;
  52049. pExpr->op = TK_COLUMN;
  52050. pExpr->pTab = pItem->pTab;
  52051. pExpr->iTable = pItem->iCursor;
  52052. pExpr->iColumn = -1;
  52053. pExpr->affinity = SQLITE_AFF_INTEGER;
  52054. break;
  52055. }
  52056. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  52057. /* A lone identifier is the name of a column.
  52058. */
  52059. case TK_ID: {
  52060. lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
  52061. return WRC_Prune;
  52062. }
  52063. /* A table name and column name: ID.ID
  52064. ** Or a database, table and column: ID.ID.ID
  52065. */
  52066. case TK_DOT: {
  52067. Token *pColumn;
  52068. Token *pTable;
  52069. Token *pDb;
  52070. Expr *pRight;
  52071. /* if( pSrcList==0 ) break; */
  52072. pRight = pExpr->pRight;
  52073. if( pRight->op==TK_ID ){
  52074. pDb = 0;
  52075. pTable = &pExpr->pLeft->token;
  52076. pColumn = &pRight->token;
  52077. }else{
  52078. assert( pRight->op==TK_DOT );
  52079. pDb = &pExpr->pLeft->token;
  52080. pTable = &pRight->pLeft->token;
  52081. pColumn = &pRight->pRight->token;
  52082. }
  52083. lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
  52084. return WRC_Prune;
  52085. }
  52086. /* Resolve function names
  52087. */
  52088. case TK_CONST_FUNC:
  52089. case TK_FUNCTION: {
  52090. ExprList *pList = pExpr->pList; /* The argument list */
  52091. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  52092. int no_such_func = 0; /* True if no such function exists */
  52093. int wrong_num_args = 0; /* True if wrong number of arguments */
  52094. int is_agg = 0; /* True if is an aggregate function */
  52095. int auth; /* Authorization to use the function */
  52096. int nId; /* Number of characters in function name */
  52097. const char *zId; /* The function name. */
  52098. FuncDef *pDef; /* Information about the function */
  52099. u8 enc = ENC(pParse->db); /* The database encoding */
  52100. zId = (char*)pExpr->token.z;
  52101. nId = pExpr->token.n;
  52102. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  52103. if( pDef==0 ){
  52104. pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
  52105. if( pDef==0 ){
  52106. no_such_func = 1;
  52107. }else{
  52108. wrong_num_args = 1;
  52109. }
  52110. }else{
  52111. is_agg = pDef->xFunc==0;
  52112. }
  52113. #ifndef SQLITE_OMIT_AUTHORIZATION
  52114. if( pDef ){
  52115. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  52116. if( auth!=SQLITE_OK ){
  52117. if( auth==SQLITE_DENY ){
  52118. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  52119. pDef->zName);
  52120. pNC->nErr++;
  52121. }
  52122. pExpr->op = TK_NULL;
  52123. return WRC_Prune;
  52124. }
  52125. }
  52126. #endif
  52127. if( is_agg && !pNC->allowAgg ){
  52128. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  52129. pNC->nErr++;
  52130. is_agg = 0;
  52131. }else if( no_such_func ){
  52132. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  52133. pNC->nErr++;
  52134. }else if( wrong_num_args ){
  52135. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  52136. nId, zId);
  52137. pNC->nErr++;
  52138. }
  52139. if( is_agg ){
  52140. pExpr->op = TK_AGG_FUNCTION;
  52141. pNC->hasAgg = 1;
  52142. }
  52143. if( is_agg ) pNC->allowAgg = 0;
  52144. sqlite3WalkExprList(pWalker, pList);
  52145. if( is_agg ) pNC->allowAgg = 1;
  52146. /* FIX ME: Compute pExpr->affinity based on the expected return
  52147. ** type of the function
  52148. */
  52149. return WRC_Prune;
  52150. }
  52151. #ifndef SQLITE_OMIT_SUBQUERY
  52152. case TK_SELECT:
  52153. case TK_EXISTS:
  52154. #endif
  52155. case TK_IN: {
  52156. if( pExpr->pSelect ){
  52157. int nRef = pNC->nRef;
  52158. #ifndef SQLITE_OMIT_CHECK
  52159. if( pNC->isCheck ){
  52160. sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
  52161. }
  52162. #endif
  52163. sqlite3WalkSelect(pWalker, pExpr->pSelect);
  52164. assert( pNC->nRef>=nRef );
  52165. if( nRef!=pNC->nRef ){
  52166. ExprSetProperty(pExpr, EP_VarSelect);
  52167. }
  52168. }
  52169. break;
  52170. }
  52171. #ifndef SQLITE_OMIT_CHECK
  52172. case TK_VARIABLE: {
  52173. if( pNC->isCheck ){
  52174. sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
  52175. }
  52176. break;
  52177. }
  52178. #endif
  52179. }
  52180. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  52181. }
  52182. /*
  52183. ** pEList is a list of expressions which are really the result set of the
  52184. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  52185. ** This routine checks to see if pE is a simple identifier which corresponds
  52186. ** to the AS-name of one of the terms of the expression list. If it is,
  52187. ** this routine return an integer between 1 and N where N is the number of
  52188. ** elements in pEList, corresponding to the matching entry. If there is
  52189. ** no match, or if pE is not a simple identifier, then this routine
  52190. ** return 0.
  52191. **
  52192. ** pEList has been resolved. pE has not.
  52193. */
  52194. static int resolveAsName(
  52195. Parse *pParse, /* Parsing context for error messages */
  52196. ExprList *pEList, /* List of expressions to scan */
  52197. Expr *pE /* Expression we are trying to match */
  52198. ){
  52199. int i; /* Loop counter */
  52200. if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
  52201. sqlite3 *db = pParse->db;
  52202. char *zCol = sqlite3NameFromToken(db, &pE->token);
  52203. if( zCol==0 ){
  52204. return -1;
  52205. }
  52206. for(i=0; i<pEList->nExpr; i++){
  52207. char *zAs = pEList->a[i].zName;
  52208. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  52209. sqlite3DbFree(db, zCol);
  52210. return i+1;
  52211. }
  52212. }
  52213. sqlite3DbFree(db, zCol);
  52214. }
  52215. return 0;
  52216. }
  52217. /*
  52218. ** pE is a pointer to an expression which is a single term in the
  52219. ** ORDER BY of a compound SELECT. The expression has not been
  52220. ** name resolved.
  52221. **
  52222. ** At the point this routine is called, we already know that the
  52223. ** ORDER BY term is not an integer index into the result set. That
  52224. ** case is handled by the calling routine.
  52225. **
  52226. ** Attempt to match pE against result set columns in the left-most
  52227. ** SELECT statement. Return the index i of the matching column,
  52228. ** as an indication to the caller that it should sort by the i-th column.
  52229. ** The left-most column is 1. In other words, the value returned is the
  52230. ** same integer value that would be used in the SQL statement to indicate
  52231. ** the column.
  52232. **
  52233. ** If there is no match, return 0. Return -1 if an error occurs.
  52234. */
  52235. static int resolveOrderByTermToExprList(
  52236. Parse *pParse, /* Parsing context for error messages */
  52237. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  52238. Expr *pE /* The specific ORDER BY term */
  52239. ){
  52240. int i; /* Loop counter */
  52241. ExprList *pEList; /* The columns of the result set */
  52242. NameContext nc; /* Name context for resolving pE */
  52243. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  52244. pEList = pSelect->pEList;
  52245. /* Resolve all names in the ORDER BY term expression
  52246. */
  52247. memset(&nc, 0, sizeof(nc));
  52248. nc.pParse = pParse;
  52249. nc.pSrcList = pSelect->pSrc;
  52250. nc.pEList = pEList;
  52251. nc.allowAgg = 1;
  52252. nc.nErr = 0;
  52253. if( sqlite3ResolveExprNames(&nc, pE) ){
  52254. sqlite3ErrorClear(pParse);
  52255. return 0;
  52256. }
  52257. /* Try to match the ORDER BY expression against an expression
  52258. ** in the result set. Return an 1-based index of the matching
  52259. ** result-set entry.
  52260. */
  52261. for(i=0; i<pEList->nExpr; i++){
  52262. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
  52263. return i+1;
  52264. }
  52265. }
  52266. /* If no match, return 0. */
  52267. return 0;
  52268. }
  52269. /*
  52270. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  52271. */
  52272. static void resolveOutOfRangeError(
  52273. Parse *pParse, /* The error context into which to write the error */
  52274. const char *zType, /* "ORDER" or "GROUP" */
  52275. int i, /* The index (1-based) of the term out of range */
  52276. int mx /* Largest permissible value of i */
  52277. ){
  52278. sqlite3ErrorMsg(pParse,
  52279. "%r %s BY term out of range - should be "
  52280. "between 1 and %d", i, zType, mx);
  52281. }
  52282. /*
  52283. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  52284. ** each term of the ORDER BY clause is a constant integer between 1
  52285. ** and N where N is the number of columns in the compound SELECT.
  52286. **
  52287. ** ORDER BY terms that are already an integer between 1 and N are
  52288. ** unmodified. ORDER BY terms that are integers outside the range of
  52289. ** 1 through N generate an error. ORDER BY terms that are expressions
  52290. ** are matched against result set expressions of compound SELECT
  52291. ** beginning with the left-most SELECT and working toward the right.
  52292. ** At the first match, the ORDER BY expression is transformed into
  52293. ** the integer column number.
  52294. **
  52295. ** Return the number of errors seen.
  52296. */
  52297. static int resolveCompoundOrderBy(
  52298. Parse *pParse, /* Parsing context. Leave error messages here */
  52299. Select *pSelect /* The SELECT statement containing the ORDER BY */
  52300. ){
  52301. int i;
  52302. ExprList *pOrderBy;
  52303. ExprList *pEList;
  52304. sqlite3 *db;
  52305. int moreToDo = 1;
  52306. pOrderBy = pSelect->pOrderBy;
  52307. if( pOrderBy==0 ) return 0;
  52308. db = pParse->db;
  52309. #if SQLITE_MAX_COLUMN
  52310. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  52311. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  52312. return 1;
  52313. }
  52314. #endif
  52315. for(i=0; i<pOrderBy->nExpr; i++){
  52316. pOrderBy->a[i].done = 0;
  52317. }
  52318. pSelect->pNext = 0;
  52319. while( pSelect->pPrior ){
  52320. pSelect->pPrior->pNext = pSelect;
  52321. pSelect = pSelect->pPrior;
  52322. }
  52323. while( pSelect && moreToDo ){
  52324. struct ExprList_item *pItem;
  52325. moreToDo = 0;
  52326. pEList = pSelect->pEList;
  52327. assert( pEList!=0 );
  52328. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  52329. int iCol = -1;
  52330. Expr *pE, *pDup;
  52331. if( pItem->done ) continue;
  52332. pE = pItem->pExpr;
  52333. if( sqlite3ExprIsInteger(pE, &iCol) ){
  52334. if( iCol<0 || iCol>pEList->nExpr ){
  52335. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  52336. return 1;
  52337. }
  52338. }else{
  52339. iCol = resolveAsName(pParse, pEList, pE);
  52340. if( iCol==0 ){
  52341. pDup = sqlite3ExprDup(db, pE);
  52342. if( !db->mallocFailed ){
  52343. assert(pDup);
  52344. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  52345. }
  52346. sqlite3ExprDelete(db, pDup);
  52347. }
  52348. if( iCol<0 ){
  52349. return 1;
  52350. }
  52351. }
  52352. if( iCol>0 ){
  52353. CollSeq *pColl = pE->pColl;
  52354. int flags = pE->flags & EP_ExpCollate;
  52355. sqlite3ExprDelete(db, pE);
  52356. pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0, 0, 0);
  52357. if( pE==0 ) return 1;
  52358. pE->pColl = pColl;
  52359. pE->flags |= EP_IntValue | flags;
  52360. pE->iTable = iCol;
  52361. pItem->iCol = (u16)iCol;
  52362. pItem->done = 1;
  52363. }else{
  52364. moreToDo = 1;
  52365. }
  52366. }
  52367. pSelect = pSelect->pNext;
  52368. }
  52369. for(i=0; i<pOrderBy->nExpr; i++){
  52370. if( pOrderBy->a[i].done==0 ){
  52371. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  52372. "column in the result set", i+1);
  52373. return 1;
  52374. }
  52375. }
  52376. return 0;
  52377. }
  52378. /*
  52379. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  52380. ** the SELECT statement pSelect. If any term is reference to a
  52381. ** result set expression (as determined by the ExprList.a.iCol field)
  52382. ** then convert that term into a copy of the corresponding result set
  52383. ** column.
  52384. **
  52385. ** If any errors are detected, add an error message to pParse and
  52386. ** return non-zero. Return zero if no errors are seen.
  52387. */
  52388. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  52389. Parse *pParse, /* Parsing context. Leave error messages here */
  52390. Select *pSelect, /* The SELECT statement containing the clause */
  52391. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  52392. const char *zType /* "ORDER" or "GROUP" */
  52393. ){
  52394. int i;
  52395. sqlite3 *db = pParse->db;
  52396. ExprList *pEList;
  52397. struct ExprList_item *pItem;
  52398. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  52399. #if SQLITE_MAX_COLUMN
  52400. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  52401. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  52402. return 1;
  52403. }
  52404. #endif
  52405. pEList = pSelect->pEList;
  52406. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  52407. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  52408. if( pItem->iCol ){
  52409. if( pItem->iCol>pEList->nExpr ){
  52410. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  52411. return 1;
  52412. }
  52413. resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
  52414. }
  52415. }
  52416. return 0;
  52417. }
  52418. /*
  52419. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  52420. ** The Name context of the SELECT statement is pNC. zType is either
  52421. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  52422. **
  52423. ** This routine resolves each term of the clause into an expression.
  52424. ** If the order-by term is an integer I between 1 and N (where N is the
  52425. ** number of columns in the result set of the SELECT) then the expression
  52426. ** in the resolution is a copy of the I-th result-set expression. If
  52427. ** the order-by term is an identify that corresponds to the AS-name of
  52428. ** a result-set expression, then the term resolves to a copy of the
  52429. ** result-set expression. Otherwise, the expression is resolved in
  52430. ** the usual way - using sqlite3ResolveExprNames().
  52431. **
  52432. ** This routine returns the number of errors. If errors occur, then
  52433. ** an appropriate error message might be left in pParse. (OOM errors
  52434. ** excepted.)
  52435. */
  52436. static int resolveOrderGroupBy(
  52437. NameContext *pNC, /* The name context of the SELECT statement */
  52438. Select *pSelect, /* The SELECT statement holding pOrderBy */
  52439. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  52440. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  52441. ){
  52442. int i; /* Loop counter */
  52443. int iCol; /* Column number */
  52444. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  52445. Parse *pParse; /* Parsing context */
  52446. int nResult; /* Number of terms in the result set */
  52447. if( pOrderBy==0 ) return 0;
  52448. nResult = pSelect->pEList->nExpr;
  52449. pParse = pNC->pParse;
  52450. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  52451. Expr *pE = pItem->pExpr;
  52452. iCol = resolveAsName(pParse, pSelect->pEList, pE);
  52453. if( iCol<0 ){
  52454. return 1; /* OOM error */
  52455. }
  52456. if( iCol>0 ){
  52457. /* If an AS-name match is found, mark this ORDER BY column as being
  52458. ** a copy of the iCol-th result-set column. The subsequent call to
  52459. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  52460. ** copy of the iCol-th result-set expression. */
  52461. pItem->iCol = (u16)iCol;
  52462. continue;
  52463. }
  52464. if( sqlite3ExprIsInteger(pE, &iCol) ){
  52465. /* The ORDER BY term is an integer constant. Again, set the column
  52466. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  52467. ** order-by term to a copy of the result-set expression */
  52468. if( iCol<1 ){
  52469. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  52470. return 1;
  52471. }
  52472. pItem->iCol = (u16)iCol;
  52473. continue;
  52474. }
  52475. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  52476. pItem->iCol = 0;
  52477. if( sqlite3ResolveExprNames(pNC, pE) ){
  52478. return 1;
  52479. }
  52480. }
  52481. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  52482. }
  52483. /*
  52484. ** Resolve names in the SELECT statement p and all of its descendents.
  52485. */
  52486. static int resolveSelectStep(Walker *pWalker, Select *p){
  52487. NameContext *pOuterNC; /* Context that contains this SELECT */
  52488. NameContext sNC; /* Name context of this SELECT */
  52489. int isCompound; /* True if p is a compound select */
  52490. int nCompound; /* Number of compound terms processed so far */
  52491. Parse *pParse; /* Parsing context */
  52492. ExprList *pEList; /* Result set expression list */
  52493. int i; /* Loop counter */
  52494. ExprList *pGroupBy; /* The GROUP BY clause */
  52495. Select *pLeftmost; /* Left-most of SELECT of a compound */
  52496. sqlite3 *db; /* Database connection */
  52497. assert( p!=0 );
  52498. if( p->selFlags & SF_Resolved ){
  52499. return WRC_Prune;
  52500. }
  52501. pOuterNC = pWalker->u.pNC;
  52502. pParse = pWalker->pParse;
  52503. db = pParse->db;
  52504. /* Normally sqlite3SelectExpand() will be called first and will have
  52505. ** already expanded this SELECT. However, if this is a subquery within
  52506. ** an expression, sqlite3ResolveExprNames() will be called without a
  52507. ** prior call to sqlite3SelectExpand(). When that happens, let
  52508. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  52509. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  52510. ** this routine in the correct order.
  52511. */
  52512. if( (p->selFlags & SF_Expanded)==0 ){
  52513. sqlite3SelectPrep(pParse, p, pOuterNC);
  52514. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  52515. }
  52516. isCompound = p->pPrior!=0;
  52517. nCompound = 0;
  52518. pLeftmost = p;
  52519. while( p ){
  52520. assert( (p->selFlags & SF_Expanded)!=0 );
  52521. assert( (p->selFlags & SF_Resolved)==0 );
  52522. p->selFlags |= SF_Resolved;
  52523. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  52524. ** are not allowed to refer to any names, so pass an empty NameContext.
  52525. */
  52526. memset(&sNC, 0, sizeof(sNC));
  52527. sNC.pParse = pParse;
  52528. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  52529. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  52530. return WRC_Abort;
  52531. }
  52532. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  52533. ** resolve the result-set expression list.
  52534. */
  52535. sNC.allowAgg = 1;
  52536. sNC.pSrcList = p->pSrc;
  52537. sNC.pNext = pOuterNC;
  52538. /* Resolve names in the result set. */
  52539. pEList = p->pEList;
  52540. assert( pEList!=0 );
  52541. for(i=0; i<pEList->nExpr; i++){
  52542. Expr *pX = pEList->a[i].pExpr;
  52543. if( sqlite3ResolveExprNames(&sNC, pX) ){
  52544. return WRC_Abort;
  52545. }
  52546. }
  52547. /* Recursively resolve names in all subqueries
  52548. */
  52549. for(i=0; i<p->pSrc->nSrc; i++){
  52550. struct SrcList_item *pItem = &p->pSrc->a[i];
  52551. if( pItem->pSelect ){
  52552. const char *zSavedContext = pParse->zAuthContext;
  52553. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  52554. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  52555. pParse->zAuthContext = zSavedContext;
  52556. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  52557. }
  52558. }
  52559. /* If there are no aggregate functions in the result-set, and no GROUP BY
  52560. ** expression, do not allow aggregates in any of the other expressions.
  52561. */
  52562. assert( (p->selFlags & SF_Aggregate)==0 );
  52563. pGroupBy = p->pGroupBy;
  52564. if( pGroupBy || sNC.hasAgg ){
  52565. p->selFlags |= SF_Aggregate;
  52566. }else{
  52567. sNC.allowAgg = 0;
  52568. }
  52569. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  52570. */
  52571. if( p->pHaving && !pGroupBy ){
  52572. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  52573. return WRC_Abort;
  52574. }
  52575. /* Add the expression list to the name-context before parsing the
  52576. ** other expressions in the SELECT statement. This is so that
  52577. ** expressions in the WHERE clause (etc.) can refer to expressions by
  52578. ** aliases in the result set.
  52579. **
  52580. ** Minor point: If this is the case, then the expression will be
  52581. ** re-evaluated for each reference to it.
  52582. */
  52583. sNC.pEList = p->pEList;
  52584. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
  52585. sqlite3ResolveExprNames(&sNC, p->pHaving)
  52586. ){
  52587. return WRC_Abort;
  52588. }
  52589. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  52590. ** outer queries
  52591. */
  52592. sNC.pNext = 0;
  52593. sNC.allowAgg = 1;
  52594. /* Process the ORDER BY clause for singleton SELECT statements.
  52595. ** The ORDER BY clause for compounds SELECT statements is handled
  52596. ** below, after all of the result-sets for all of the elements of
  52597. ** the compound have been resolved.
  52598. */
  52599. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  52600. return WRC_Abort;
  52601. }
  52602. if( db->mallocFailed ){
  52603. return WRC_Abort;
  52604. }
  52605. /* Resolve the GROUP BY clause. At the same time, make sure
  52606. ** the GROUP BY clause does not contain aggregate functions.
  52607. */
  52608. if( pGroupBy ){
  52609. struct ExprList_item *pItem;
  52610. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  52611. return WRC_Abort;
  52612. }
  52613. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  52614. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  52615. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  52616. "the GROUP BY clause");
  52617. return WRC_Abort;
  52618. }
  52619. }
  52620. }
  52621. /* Advance to the next term of the compound
  52622. */
  52623. p = p->pPrior;
  52624. nCompound++;
  52625. }
  52626. /* Resolve the ORDER BY on a compound SELECT after all terms of
  52627. ** the compound have been resolved.
  52628. */
  52629. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  52630. return WRC_Abort;
  52631. }
  52632. return WRC_Prune;
  52633. }
  52634. /*
  52635. ** This routine walks an expression tree and resolves references to
  52636. ** table columns and result-set columns. At the same time, do error
  52637. ** checking on function usage and set a flag if any aggregate functions
  52638. ** are seen.
  52639. **
  52640. ** To resolve table columns references we look for nodes (or subtrees) of the
  52641. ** form X.Y.Z or Y.Z or just Z where
  52642. **
  52643. ** X: The name of a database. Ex: "main" or "temp" or
  52644. ** the symbolic name assigned to an ATTACH-ed database.
  52645. **
  52646. ** Y: The name of a table in a FROM clause. Or in a trigger
  52647. ** one of the special names "old" or "new".
  52648. **
  52649. ** Z: The name of a column in table Y.
  52650. **
  52651. ** The node at the root of the subtree is modified as follows:
  52652. **
  52653. ** Expr.op Changed to TK_COLUMN
  52654. ** Expr.pTab Points to the Table object for X.Y
  52655. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  52656. ** Expr.iTable The VDBE cursor number for X.Y
  52657. **
  52658. **
  52659. ** To resolve result-set references, look for expression nodes of the
  52660. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  52661. ** size of an AS clause in the result-set of a SELECT. The Z expression
  52662. ** is replaced by a copy of the left-hand side of the result-set expression.
  52663. ** Table-name and function resolution occurs on the substituted expression
  52664. ** tree. For example, in:
  52665. **
  52666. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  52667. **
  52668. ** The "x" term of the order by is replaced by "a+b" to render:
  52669. **
  52670. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  52671. **
  52672. ** Function calls are checked to make sure that the function is
  52673. ** defined and that the correct number of arguments are specified.
  52674. ** If the function is an aggregate function, then the pNC->hasAgg is
  52675. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  52676. ** If an expression contains aggregate functions then the EP_Agg
  52677. ** property on the expression is set.
  52678. **
  52679. ** An error message is left in pParse if anything is amiss. The number
  52680. ** if errors is returned.
  52681. */
  52682. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  52683. NameContext *pNC, /* Namespace to resolve expressions in. */
  52684. Expr *pExpr /* The expression to be analyzed. */
  52685. ){
  52686. int savedHasAgg;
  52687. Walker w;
  52688. if( pExpr==0 ) return 0;
  52689. #if SQLITE_MAX_EXPR_DEPTH>0
  52690. {
  52691. Parse *pParse = pNC->pParse;
  52692. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  52693. return 1;
  52694. }
  52695. pParse->nHeight += pExpr->nHeight;
  52696. }
  52697. #endif
  52698. savedHasAgg = pNC->hasAgg;
  52699. pNC->hasAgg = 0;
  52700. w.xExprCallback = resolveExprStep;
  52701. w.xSelectCallback = resolveSelectStep;
  52702. w.pParse = pNC->pParse;
  52703. w.u.pNC = pNC;
  52704. sqlite3WalkExpr(&w, pExpr);
  52705. #if SQLITE_MAX_EXPR_DEPTH>0
  52706. pNC->pParse->nHeight -= pExpr->nHeight;
  52707. #endif
  52708. if( pNC->nErr>0 ){
  52709. ExprSetProperty(pExpr, EP_Error);
  52710. }
  52711. if( pNC->hasAgg ){
  52712. ExprSetProperty(pExpr, EP_Agg);
  52713. }else if( savedHasAgg ){
  52714. pNC->hasAgg = 1;
  52715. }
  52716. return ExprHasProperty(pExpr, EP_Error);
  52717. }
  52718. /*
  52719. ** Resolve all names in all expressions of a SELECT and in all
  52720. ** decendents of the SELECT, including compounds off of p->pPrior,
  52721. ** subqueries in expressions, and subqueries used as FROM clause
  52722. ** terms.
  52723. **
  52724. ** See sqlite3ResolveExprNames() for a description of the kinds of
  52725. ** transformations that occur.
  52726. **
  52727. ** All SELECT statements should have been expanded using
  52728. ** sqlite3SelectExpand() prior to invoking this routine.
  52729. */
  52730. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  52731. Parse *pParse, /* The parser context */
  52732. Select *p, /* The SELECT statement being coded. */
  52733. NameContext *pOuterNC /* Name context for parent SELECT statement */
  52734. ){
  52735. Walker w;
  52736. assert( p!=0 );
  52737. w.xExprCallback = resolveExprStep;
  52738. w.xSelectCallback = resolveSelectStep;
  52739. w.pParse = pParse;
  52740. w.u.pNC = pOuterNC;
  52741. sqlite3WalkSelect(&w, p);
  52742. }
  52743. /************** End of resolve.c *********************************************/
  52744. /************** Begin file expr.c ********************************************/
  52745. /*
  52746. ** 2001 September 15
  52747. **
  52748. ** The author disclaims copyright to this source code. In place of
  52749. ** a legal notice, here is a blessing:
  52750. **
  52751. ** May you do good and not evil.
  52752. ** May you find forgiveness for yourself and forgive others.
  52753. ** May you share freely, never taking more than you give.
  52754. **
  52755. *************************************************************************
  52756. ** This file contains routines used for analyzing expressions and
  52757. ** for generating VDBE code that evaluates expressions in SQLite.
  52758. **
  52759. ** $Id: expr.c,v 1.409 2009/01/10 13:24:51 drh Exp $
  52760. */
  52761. /*
  52762. ** Return the 'affinity' of the expression pExpr if any.
  52763. **
  52764. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  52765. ** or a sub-select with a column as the return value, then the
  52766. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  52767. ** indicating no affinity for the expression.
  52768. **
  52769. ** i.e. the WHERE clause expresssions in the following statements all
  52770. ** have an affinity:
  52771. **
  52772. ** CREATE TABLE t1(a);
  52773. ** SELECT * FROM t1 WHERE a;
  52774. ** SELECT a AS b FROM t1 WHERE b;
  52775. ** SELECT * FROM t1 WHERE (select a from t1);
  52776. */
  52777. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  52778. int op = pExpr->op;
  52779. if( op==TK_SELECT ){
  52780. return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
  52781. }
  52782. #ifndef SQLITE_OMIT_CAST
  52783. if( op==TK_CAST ){
  52784. return sqlite3AffinityType(&pExpr->token);
  52785. }
  52786. #endif
  52787. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  52788. && pExpr->pTab!=0
  52789. ){
  52790. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  52791. ** a TK_COLUMN but was previously evaluated and cached in a register */
  52792. int j = pExpr->iColumn;
  52793. if( j<0 ) return SQLITE_AFF_INTEGER;
  52794. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  52795. return pExpr->pTab->aCol[j].affinity;
  52796. }
  52797. return pExpr->affinity;
  52798. }
  52799. /*
  52800. ** Set the collating sequence for expression pExpr to be the collating
  52801. ** sequence named by pToken. Return a pointer to the revised expression.
  52802. ** The collating sequence is marked as "explicit" using the EP_ExpCollate
  52803. ** flag. An explicit collating sequence will override implicit
  52804. ** collating sequences.
  52805. */
  52806. SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
  52807. char *zColl = 0; /* Dequoted name of collation sequence */
  52808. CollSeq *pColl;
  52809. sqlite3 *db = pParse->db;
  52810. zColl = sqlite3NameFromToken(db, pCollName);
  52811. if( pExpr && zColl ){
  52812. pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
  52813. if( pColl ){
  52814. pExpr->pColl = pColl;
  52815. pExpr->flags |= EP_ExpCollate;
  52816. }
  52817. }
  52818. sqlite3DbFree(db, zColl);
  52819. return pExpr;
  52820. }
  52821. /*
  52822. ** Return the default collation sequence for the expression pExpr. If
  52823. ** there is no default collation type, return 0.
  52824. */
  52825. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  52826. CollSeq *pColl = 0;
  52827. Expr *p = pExpr;
  52828. while( p ){
  52829. int op;
  52830. pColl = p->pColl;
  52831. if( pColl ) break;
  52832. op = p->op;
  52833. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) && p->pTab!=0 ){
  52834. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  52835. ** a TK_COLUMN but was previously evaluated and cached in a register */
  52836. const char *zColl;
  52837. int j = p->iColumn;
  52838. if( j>=0 ){
  52839. sqlite3 *db = pParse->db;
  52840. zColl = p->pTab->aCol[j].zColl;
  52841. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
  52842. pExpr->pColl = pColl;
  52843. }
  52844. break;
  52845. }
  52846. if( op!=TK_CAST && op!=TK_UPLUS ){
  52847. break;
  52848. }
  52849. p = p->pLeft;
  52850. }
  52851. if( sqlite3CheckCollSeq(pParse, pColl) ){
  52852. pColl = 0;
  52853. }
  52854. return pColl;
  52855. }
  52856. /*
  52857. ** pExpr is an operand of a comparison operator. aff2 is the
  52858. ** type affinity of the other operand. This routine returns the
  52859. ** type affinity that should be used for the comparison operator.
  52860. */
  52861. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  52862. char aff1 = sqlite3ExprAffinity(pExpr);
  52863. if( aff1 && aff2 ){
  52864. /* Both sides of the comparison are columns. If one has numeric
  52865. ** affinity, use that. Otherwise use no affinity.
  52866. */
  52867. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  52868. return SQLITE_AFF_NUMERIC;
  52869. }else{
  52870. return SQLITE_AFF_NONE;
  52871. }
  52872. }else if( !aff1 && !aff2 ){
  52873. /* Neither side of the comparison is a column. Compare the
  52874. ** results directly.
  52875. */
  52876. return SQLITE_AFF_NONE;
  52877. }else{
  52878. /* One side is a column, the other is not. Use the columns affinity. */
  52879. assert( aff1==0 || aff2==0 );
  52880. return (aff1 + aff2);
  52881. }
  52882. }
  52883. /*
  52884. ** pExpr is a comparison operator. Return the type affinity that should
  52885. ** be applied to both operands prior to doing the comparison.
  52886. */
  52887. static char comparisonAffinity(Expr *pExpr){
  52888. char aff;
  52889. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  52890. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  52891. pExpr->op==TK_NE );
  52892. assert( pExpr->pLeft );
  52893. aff = sqlite3ExprAffinity(pExpr->pLeft);
  52894. if( pExpr->pRight ){
  52895. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  52896. }
  52897. else if( pExpr->pSelect ){
  52898. aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
  52899. }
  52900. else if( !aff ){
  52901. aff = SQLITE_AFF_NONE;
  52902. }
  52903. return aff;
  52904. }
  52905. /*
  52906. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  52907. ** idx_affinity is the affinity of an indexed column. Return true
  52908. ** if the index with affinity idx_affinity may be used to implement
  52909. ** the comparison in pExpr.
  52910. */
  52911. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  52912. char aff = comparisonAffinity(pExpr);
  52913. switch( aff ){
  52914. case SQLITE_AFF_NONE:
  52915. return 1;
  52916. case SQLITE_AFF_TEXT:
  52917. return idx_affinity==SQLITE_AFF_TEXT;
  52918. default:
  52919. return sqlite3IsNumericAffinity(idx_affinity);
  52920. }
  52921. }
  52922. /*
  52923. ** Return the P5 value that should be used for a binary comparison
  52924. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  52925. */
  52926. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  52927. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  52928. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  52929. return aff;
  52930. }
  52931. /*
  52932. ** Return a pointer to the collation sequence that should be used by
  52933. ** a binary comparison operator comparing pLeft and pRight.
  52934. **
  52935. ** If the left hand expression has a collating sequence type, then it is
  52936. ** used. Otherwise the collation sequence for the right hand expression
  52937. ** is used, or the default (BINARY) if neither expression has a collating
  52938. ** type.
  52939. **
  52940. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  52941. ** it is not considered.
  52942. */
  52943. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  52944. Parse *pParse,
  52945. Expr *pLeft,
  52946. Expr *pRight
  52947. ){
  52948. CollSeq *pColl;
  52949. assert( pLeft );
  52950. if( pLeft->flags & EP_ExpCollate ){
  52951. assert( pLeft->pColl );
  52952. pColl = pLeft->pColl;
  52953. }else if( pRight && pRight->flags & EP_ExpCollate ){
  52954. assert( pRight->pColl );
  52955. pColl = pRight->pColl;
  52956. }else{
  52957. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  52958. if( !pColl ){
  52959. pColl = sqlite3ExprCollSeq(pParse, pRight);
  52960. }
  52961. }
  52962. return pColl;
  52963. }
  52964. /*
  52965. ** Generate the operands for a comparison operation. Before
  52966. ** generating the code for each operand, set the EP_AnyAff
  52967. ** flag on the expression so that it will be able to used a
  52968. ** cached column value that has previously undergone an
  52969. ** affinity change.
  52970. */
  52971. static void codeCompareOperands(
  52972. Parse *pParse, /* Parsing and code generating context */
  52973. Expr *pLeft, /* The left operand */
  52974. int *pRegLeft, /* Register where left operand is stored */
  52975. int *pFreeLeft, /* Free this register when done */
  52976. Expr *pRight, /* The right operand */
  52977. int *pRegRight, /* Register where right operand is stored */
  52978. int *pFreeRight /* Write temp register for right operand there */
  52979. ){
  52980. while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
  52981. pLeft->flags |= EP_AnyAff;
  52982. *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
  52983. while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
  52984. pRight->flags |= EP_AnyAff;
  52985. *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
  52986. }
  52987. /*
  52988. ** Generate code for a comparison operator.
  52989. */
  52990. static int codeCompare(
  52991. Parse *pParse, /* The parsing (and code generating) context */
  52992. Expr *pLeft, /* The left operand */
  52993. Expr *pRight, /* The right operand */
  52994. int opcode, /* The comparison opcode */
  52995. int in1, int in2, /* Register holding operands */
  52996. int dest, /* Jump here if true. */
  52997. int jumpIfNull /* If true, jump if either operand is NULL */
  52998. ){
  52999. int p5;
  53000. int addr;
  53001. CollSeq *p4;
  53002. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  53003. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  53004. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  53005. (void*)p4, P4_COLLSEQ);
  53006. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  53007. if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
  53008. sqlite3ExprCacheAffinityChange(pParse, in1, 1);
  53009. sqlite3ExprCacheAffinityChange(pParse, in2, 1);
  53010. }
  53011. return addr;
  53012. }
  53013. #if SQLITE_MAX_EXPR_DEPTH>0
  53014. /*
  53015. ** Check that argument nHeight is less than or equal to the maximum
  53016. ** expression depth allowed. If it is not, leave an error message in
  53017. ** pParse.
  53018. */
  53019. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  53020. int rc = SQLITE_OK;
  53021. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  53022. if( nHeight>mxHeight ){
  53023. sqlite3ErrorMsg(pParse,
  53024. "Expression tree is too large (maximum depth %d)", mxHeight
  53025. );
  53026. rc = SQLITE_ERROR;
  53027. }
  53028. return rc;
  53029. }
  53030. /* The following three functions, heightOfExpr(), heightOfExprList()
  53031. ** and heightOfSelect(), are used to determine the maximum height
  53032. ** of any expression tree referenced by the structure passed as the
  53033. ** first argument.
  53034. **
  53035. ** If this maximum height is greater than the current value pointed
  53036. ** to by pnHeight, the second parameter, then set *pnHeight to that
  53037. ** value.
  53038. */
  53039. static void heightOfExpr(Expr *p, int *pnHeight){
  53040. if( p ){
  53041. if( p->nHeight>*pnHeight ){
  53042. *pnHeight = p->nHeight;
  53043. }
  53044. }
  53045. }
  53046. static void heightOfExprList(ExprList *p, int *pnHeight){
  53047. if( p ){
  53048. int i;
  53049. for(i=0; i<p->nExpr; i++){
  53050. heightOfExpr(p->a[i].pExpr, pnHeight);
  53051. }
  53052. }
  53053. }
  53054. static void heightOfSelect(Select *p, int *pnHeight){
  53055. if( p ){
  53056. heightOfExpr(p->pWhere, pnHeight);
  53057. heightOfExpr(p->pHaving, pnHeight);
  53058. heightOfExpr(p->pLimit, pnHeight);
  53059. heightOfExpr(p->pOffset, pnHeight);
  53060. heightOfExprList(p->pEList, pnHeight);
  53061. heightOfExprList(p->pGroupBy, pnHeight);
  53062. heightOfExprList(p->pOrderBy, pnHeight);
  53063. heightOfSelect(p->pPrior, pnHeight);
  53064. }
  53065. }
  53066. /*
  53067. ** Set the Expr.nHeight variable in the structure passed as an
  53068. ** argument. An expression with no children, Expr.pList or
  53069. ** Expr.pSelect member has a height of 1. Any other expression
  53070. ** has a height equal to the maximum height of any other
  53071. ** referenced Expr plus one.
  53072. */
  53073. static void exprSetHeight(Expr *p){
  53074. int nHeight = 0;
  53075. heightOfExpr(p->pLeft, &nHeight);
  53076. heightOfExpr(p->pRight, &nHeight);
  53077. heightOfExprList(p->pList, &nHeight);
  53078. heightOfSelect(p->pSelect, &nHeight);
  53079. p->nHeight = nHeight + 1;
  53080. }
  53081. /*
  53082. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  53083. ** the height is greater than the maximum allowed expression depth,
  53084. ** leave an error in pParse.
  53085. */
  53086. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  53087. exprSetHeight(p);
  53088. sqlite3ExprCheckHeight(pParse, p->nHeight);
  53089. }
  53090. /*
  53091. ** Return the maximum height of any expression tree referenced
  53092. ** by the select statement passed as an argument.
  53093. */
  53094. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  53095. int nHeight = 0;
  53096. heightOfSelect(p, &nHeight);
  53097. return nHeight;
  53098. }
  53099. #else
  53100. #define exprSetHeight(y)
  53101. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  53102. /*
  53103. ** Construct a new expression node and return a pointer to it. Memory
  53104. ** for this node is obtained from sqlite3_malloc(). The calling function
  53105. ** is responsible for making sure the node eventually gets freed.
  53106. */
  53107. SQLITE_PRIVATE Expr *sqlite3Expr(
  53108. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  53109. int op, /* Expression opcode */
  53110. Expr *pLeft, /* Left operand */
  53111. Expr *pRight, /* Right operand */
  53112. const Token *pToken /* Argument token */
  53113. ){
  53114. Expr *pNew;
  53115. pNew = sqlite3DbMallocZero(db, sizeof(Expr));
  53116. if( pNew==0 ){
  53117. /* When malloc fails, delete pLeft and pRight. Expressions passed to
  53118. ** this function must always be allocated with sqlite3Expr() for this
  53119. ** reason.
  53120. */
  53121. sqlite3ExprDelete(db, pLeft);
  53122. sqlite3ExprDelete(db, pRight);
  53123. return 0;
  53124. }
  53125. pNew->op = (u8)op;
  53126. pNew->pLeft = pLeft;
  53127. pNew->pRight = pRight;
  53128. pNew->iAgg = -1;
  53129. pNew->span.z = (u8*)"";
  53130. if( pToken ){
  53131. assert( pToken->dyn==0 );
  53132. pNew->span = pNew->token = *pToken;
  53133. }else if( pLeft ){
  53134. if( pRight ){
  53135. if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
  53136. sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
  53137. }
  53138. if( pRight->flags & EP_ExpCollate ){
  53139. pNew->flags |= EP_ExpCollate;
  53140. pNew->pColl = pRight->pColl;
  53141. }
  53142. }
  53143. if( pLeft->flags & EP_ExpCollate ){
  53144. pNew->flags |= EP_ExpCollate;
  53145. pNew->pColl = pLeft->pColl;
  53146. }
  53147. }
  53148. exprSetHeight(pNew);
  53149. return pNew;
  53150. }
  53151. /*
  53152. ** Works like sqlite3Expr() except that it takes an extra Parse*
  53153. ** argument and notifies the associated connection object if malloc fails.
  53154. */
  53155. SQLITE_PRIVATE Expr *sqlite3PExpr(
  53156. Parse *pParse, /* Parsing context */
  53157. int op, /* Expression opcode */
  53158. Expr *pLeft, /* Left operand */
  53159. Expr *pRight, /* Right operand */
  53160. const Token *pToken /* Argument token */
  53161. ){
  53162. Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
  53163. if( p ){
  53164. sqlite3ExprCheckHeight(pParse, p->nHeight);
  53165. }
  53166. return p;
  53167. }
  53168. /*
  53169. ** When doing a nested parse, you can include terms in an expression
  53170. ** that look like this: #1 #2 ... These terms refer to registers
  53171. ** in the virtual machine. #N is the N-th register.
  53172. **
  53173. ** This routine is called by the parser to deal with on of those terms.
  53174. ** It immediately generates code to store the value in a memory location.
  53175. ** The returns an expression that will code to extract the value from
  53176. ** that memory location as needed.
  53177. */
  53178. SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
  53179. Vdbe *v = pParse->pVdbe;
  53180. Expr *p;
  53181. if( pParse->nested==0 ){
  53182. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
  53183. return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  53184. }
  53185. if( v==0 ) return 0;
  53186. p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
  53187. if( p==0 ){
  53188. return 0; /* Malloc failed */
  53189. }
  53190. p->iTable = atoi((char*)&pToken->z[1]);
  53191. return p;
  53192. }
  53193. /*
  53194. ** Join two expressions using an AND operator. If either expression is
  53195. ** NULL, then just return the other expression.
  53196. */
  53197. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  53198. if( pLeft==0 ){
  53199. return pRight;
  53200. }else if( pRight==0 ){
  53201. return pLeft;
  53202. }else{
  53203. return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
  53204. }
  53205. }
  53206. /*
  53207. ** Set the Expr.span field of the given expression to span all
  53208. ** text between the two given tokens. Both tokens must be pointing
  53209. ** at the same string.
  53210. */
  53211. SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
  53212. assert( pRight!=0 );
  53213. assert( pLeft!=0 );
  53214. if( pExpr ){
  53215. pExpr->span.z = pLeft->z;
  53216. pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
  53217. }
  53218. }
  53219. /*
  53220. ** Construct a new expression node for a function with multiple
  53221. ** arguments.
  53222. */
  53223. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  53224. Expr *pNew;
  53225. sqlite3 *db = pParse->db;
  53226. assert( pToken );
  53227. pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
  53228. if( pNew==0 ){
  53229. sqlite3ExprListDelete(db, pList); /* Avoid leaking memory when malloc fails */
  53230. return 0;
  53231. }
  53232. pNew->op = TK_FUNCTION;
  53233. pNew->pList = pList;
  53234. assert( pToken->dyn==0 );
  53235. pNew->token = *pToken;
  53236. pNew->span = pNew->token;
  53237. sqlite3ExprSetHeight(pParse, pNew);
  53238. return pNew;
  53239. }
  53240. /*
  53241. ** Assign a variable number to an expression that encodes a wildcard
  53242. ** in the original SQL statement.
  53243. **
  53244. ** Wildcards consisting of a single "?" are assigned the next sequential
  53245. ** variable number.
  53246. **
  53247. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  53248. ** sure "nnn" is not too be to avoid a denial of service attack when
  53249. ** the SQL statement comes from an external source.
  53250. **
  53251. ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
  53252. ** as the previous instance of the same wildcard. Or if this is the first
  53253. ** instance of the wildcard, the next sequenial variable number is
  53254. ** assigned.
  53255. */
  53256. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  53257. Token *pToken;
  53258. sqlite3 *db = pParse->db;
  53259. if( pExpr==0 ) return;
  53260. pToken = &pExpr->token;
  53261. assert( pToken->n>=1 );
  53262. assert( pToken->z!=0 );
  53263. assert( pToken->z[0]!=0 );
  53264. if( pToken->n==1 ){
  53265. /* Wildcard of the form "?". Assign the next variable number */
  53266. pExpr->iTable = ++pParse->nVar;
  53267. }else if( pToken->z[0]=='?' ){
  53268. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  53269. ** use it as the variable number */
  53270. int i;
  53271. pExpr->iTable = i = atoi((char*)&pToken->z[1]);
  53272. testcase( i==0 );
  53273. testcase( i==1 );
  53274. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  53275. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  53276. if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  53277. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  53278. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  53279. }
  53280. if( i>pParse->nVar ){
  53281. pParse->nVar = i;
  53282. }
  53283. }else{
  53284. /* Wildcards of the form ":aaa" or "$aaa". Reuse the same variable
  53285. ** number as the prior appearance of the same name, or if the name
  53286. ** has never appeared before, reuse the same variable number
  53287. */
  53288. int i;
  53289. u32 n;
  53290. n = pToken->n;
  53291. for(i=0; i<pParse->nVarExpr; i++){
  53292. Expr *pE;
  53293. if( (pE = pParse->apVarExpr[i])!=0
  53294. && pE->token.n==n
  53295. && memcmp(pE->token.z, pToken->z, n)==0 ){
  53296. pExpr->iTable = pE->iTable;
  53297. break;
  53298. }
  53299. }
  53300. if( i>=pParse->nVarExpr ){
  53301. pExpr->iTable = ++pParse->nVar;
  53302. if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
  53303. pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
  53304. pParse->apVarExpr =
  53305. sqlite3DbReallocOrFree(
  53306. db,
  53307. pParse->apVarExpr,
  53308. pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
  53309. );
  53310. }
  53311. if( !db->mallocFailed ){
  53312. assert( pParse->apVarExpr!=0 );
  53313. pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
  53314. }
  53315. }
  53316. }
  53317. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  53318. sqlite3ErrorMsg(pParse, "too many SQL variables");
  53319. }
  53320. }
  53321. /*
  53322. ** Clear an expression structure without deleting the structure itself.
  53323. ** Substructure is deleted.
  53324. */
  53325. SQLITE_PRIVATE void sqlite3ExprClear(sqlite3 *db, Expr *p){
  53326. if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
  53327. if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
  53328. sqlite3ExprDelete(db, p->pLeft);
  53329. sqlite3ExprDelete(db, p->pRight);
  53330. sqlite3ExprListDelete(db, p->pList);
  53331. sqlite3SelectDelete(db, p->pSelect);
  53332. }
  53333. /*
  53334. ** Recursively delete an expression tree.
  53335. */
  53336. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  53337. if( p==0 ) return;
  53338. sqlite3ExprClear(db, p);
  53339. sqlite3DbFree(db, p);
  53340. }
  53341. /*
  53342. ** The Expr.token field might be a string literal that is quoted.
  53343. ** If so, remove the quotation marks.
  53344. */
  53345. SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
  53346. if( ExprHasAnyProperty(p, EP_Dequoted) ){
  53347. return;
  53348. }
  53349. ExprSetProperty(p, EP_Dequoted);
  53350. if( p->token.dyn==0 ){
  53351. sqlite3TokenCopy(db, &p->token, &p->token);
  53352. }
  53353. sqlite3Dequote((char*)p->token.z);
  53354. }
  53355. /*
  53356. ** The following group of routines make deep copies of expressions,
  53357. ** expression lists, ID lists, and select statements. The copies can
  53358. ** be deleted (by being passed to their respective ...Delete() routines)
  53359. ** without effecting the originals.
  53360. **
  53361. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  53362. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  53363. ** by subsequent calls to sqlite*ListAppend() routines.
  53364. **
  53365. ** Any tables that the SrcList might point to are not duplicated.
  53366. */
  53367. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
  53368. Expr *pNew;
  53369. if( p==0 ) return 0;
  53370. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  53371. if( pNew==0 ) return 0;
  53372. memcpy(pNew, p, sizeof(*pNew));
  53373. if( p->token.z!=0 ){
  53374. pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
  53375. pNew->token.dyn = 1;
  53376. }else{
  53377. assert( pNew->token.z==0 );
  53378. }
  53379. pNew->span.z = 0;
  53380. pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
  53381. pNew->pRight = sqlite3ExprDup(db, p->pRight);
  53382. pNew->pList = sqlite3ExprListDup(db, p->pList);
  53383. pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
  53384. return pNew;
  53385. }
  53386. SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
  53387. if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
  53388. if( pFrom->z ){
  53389. pTo->n = pFrom->n;
  53390. pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
  53391. pTo->dyn = 1;
  53392. }else{
  53393. pTo->z = 0;
  53394. }
  53395. }
  53396. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
  53397. ExprList *pNew;
  53398. struct ExprList_item *pItem, *pOldItem;
  53399. int i;
  53400. if( p==0 ) return 0;
  53401. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  53402. if( pNew==0 ) return 0;
  53403. pNew->iECursor = 0;
  53404. pNew->nExpr = pNew->nAlloc = p->nExpr;
  53405. pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) );
  53406. if( pItem==0 ){
  53407. sqlite3DbFree(db, pNew);
  53408. return 0;
  53409. }
  53410. pOldItem = p->a;
  53411. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  53412. Expr *pNewExpr, *pOldExpr;
  53413. pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
  53414. if( pOldExpr->span.z!=0 && pNewExpr ){
  53415. /* Always make a copy of the span for top-level expressions in the
  53416. ** expression list. The logic in SELECT processing that determines
  53417. ** the names of columns in the result set needs this information */
  53418. sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
  53419. }
  53420. assert( pNewExpr==0 || pNewExpr->span.z!=0
  53421. || pOldExpr->span.z==0
  53422. || db->mallocFailed );
  53423. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  53424. pItem->sortOrder = pOldItem->sortOrder;
  53425. pItem->done = 0;
  53426. pItem->iCol = pOldItem->iCol;
  53427. pItem->iAlias = pOldItem->iAlias;
  53428. }
  53429. return pNew;
  53430. }
  53431. /*
  53432. ** If cursors, triggers, views and subqueries are all omitted from
  53433. ** the build, then none of the following routines, except for
  53434. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  53435. ** called with a NULL argument.
  53436. */
  53437. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  53438. || !defined(SQLITE_OMIT_SUBQUERY)
  53439. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
  53440. SrcList *pNew;
  53441. int i;
  53442. int nByte;
  53443. if( p==0 ) return 0;
  53444. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  53445. pNew = sqlite3DbMallocRaw(db, nByte );
  53446. if( pNew==0 ) return 0;
  53447. pNew->nSrc = pNew->nAlloc = p->nSrc;
  53448. for(i=0; i<p->nSrc; i++){
  53449. struct SrcList_item *pNewItem = &pNew->a[i];
  53450. struct SrcList_item *pOldItem = &p->a[i];
  53451. Table *pTab;
  53452. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  53453. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  53454. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  53455. pNewItem->jointype = pOldItem->jointype;
  53456. pNewItem->iCursor = pOldItem->iCursor;
  53457. pNewItem->isPopulated = pOldItem->isPopulated;
  53458. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  53459. pNewItem->notIndexed = pOldItem->notIndexed;
  53460. pNewItem->pIndex = pOldItem->pIndex;
  53461. pTab = pNewItem->pTab = pOldItem->pTab;
  53462. if( pTab ){
  53463. pTab->nRef++;
  53464. }
  53465. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
  53466. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
  53467. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  53468. pNewItem->colUsed = pOldItem->colUsed;
  53469. }
  53470. return pNew;
  53471. }
  53472. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  53473. IdList *pNew;
  53474. int i;
  53475. if( p==0 ) return 0;
  53476. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  53477. if( pNew==0 ) return 0;
  53478. pNew->nId = pNew->nAlloc = p->nId;
  53479. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  53480. if( pNew->a==0 ){
  53481. sqlite3DbFree(db, pNew);
  53482. return 0;
  53483. }
  53484. for(i=0; i<p->nId; i++){
  53485. struct IdList_item *pNewItem = &pNew->a[i];
  53486. struct IdList_item *pOldItem = &p->a[i];
  53487. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  53488. pNewItem->idx = pOldItem->idx;
  53489. }
  53490. return pNew;
  53491. }
  53492. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
  53493. Select *pNew;
  53494. if( p==0 ) return 0;
  53495. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  53496. if( pNew==0 ) return 0;
  53497. pNew->pEList = sqlite3ExprListDup(db, p->pEList);
  53498. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
  53499. pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
  53500. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
  53501. pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
  53502. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
  53503. pNew->op = p->op;
  53504. pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
  53505. pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
  53506. pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
  53507. pNew->iLimit = 0;
  53508. pNew->iOffset = 0;
  53509. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  53510. pNew->pRightmost = 0;
  53511. pNew->addrOpenEphm[0] = -1;
  53512. pNew->addrOpenEphm[1] = -1;
  53513. pNew->addrOpenEphm[2] = -1;
  53514. return pNew;
  53515. }
  53516. #else
  53517. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
  53518. assert( p==0 );
  53519. return 0;
  53520. }
  53521. #endif
  53522. /*
  53523. ** Add a new element to the end of an expression list. If pList is
  53524. ** initially NULL, then create a new expression list.
  53525. */
  53526. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  53527. Parse *pParse, /* Parsing context */
  53528. ExprList *pList, /* List to which to append. Might be NULL */
  53529. Expr *pExpr, /* Expression to be appended */
  53530. Token *pName /* AS keyword for the expression */
  53531. ){
  53532. sqlite3 *db = pParse->db;
  53533. if( pList==0 ){
  53534. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  53535. if( pList==0 ){
  53536. goto no_mem;
  53537. }
  53538. assert( pList->nAlloc==0 );
  53539. }
  53540. if( pList->nAlloc<=pList->nExpr ){
  53541. struct ExprList_item *a;
  53542. int n = pList->nAlloc*2 + 4;
  53543. a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
  53544. if( a==0 ){
  53545. goto no_mem;
  53546. }
  53547. pList->a = a;
  53548. pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
  53549. }
  53550. assert( pList->a!=0 );
  53551. if( pExpr || pName ){
  53552. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  53553. memset(pItem, 0, sizeof(*pItem));
  53554. pItem->zName = sqlite3NameFromToken(db, pName);
  53555. pItem->pExpr = pExpr;
  53556. pItem->iAlias = 0;
  53557. }
  53558. return pList;
  53559. no_mem:
  53560. /* Avoid leaking memory if malloc has failed. */
  53561. sqlite3ExprDelete(db, pExpr);
  53562. sqlite3ExprListDelete(db, pList);
  53563. return 0;
  53564. }
  53565. /*
  53566. ** If the expression list pEList contains more than iLimit elements,
  53567. ** leave an error message in pParse.
  53568. */
  53569. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  53570. Parse *pParse,
  53571. ExprList *pEList,
  53572. const char *zObject
  53573. ){
  53574. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  53575. testcase( pEList && pEList->nExpr==mx );
  53576. testcase( pEList && pEList->nExpr==mx+1 );
  53577. if( pEList && pEList->nExpr>mx ){
  53578. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  53579. }
  53580. }
  53581. /*
  53582. ** Delete an entire expression list.
  53583. */
  53584. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  53585. int i;
  53586. struct ExprList_item *pItem;
  53587. if( pList==0 ) return;
  53588. assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
  53589. assert( pList->nExpr<=pList->nAlloc );
  53590. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  53591. sqlite3ExprDelete(db, pItem->pExpr);
  53592. sqlite3DbFree(db, pItem->zName);
  53593. }
  53594. sqlite3DbFree(db, pList->a);
  53595. sqlite3DbFree(db, pList);
  53596. }
  53597. /*
  53598. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  53599. ** to an integer. These routines are checking an expression to see
  53600. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  53601. ** not constant.
  53602. **
  53603. ** These callback routines are used to implement the following:
  53604. **
  53605. ** sqlite3ExprIsConstant()
  53606. ** sqlite3ExprIsConstantNotJoin()
  53607. ** sqlite3ExprIsConstantOrFunction()
  53608. **
  53609. */
  53610. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  53611. /* If pWalker->u.i is 3 then any term of the expression that comes from
  53612. ** the ON or USING clauses of a join disqualifies the expression
  53613. ** from being considered constant. */
  53614. if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
  53615. pWalker->u.i = 0;
  53616. return WRC_Abort;
  53617. }
  53618. switch( pExpr->op ){
  53619. /* Consider functions to be constant if all their arguments are constant
  53620. ** and pWalker->u.i==2 */
  53621. case TK_FUNCTION:
  53622. if( pWalker->u.i==2 ) return 0;
  53623. /* Fall through */
  53624. case TK_ID:
  53625. case TK_COLUMN:
  53626. case TK_AGG_FUNCTION:
  53627. case TK_AGG_COLUMN:
  53628. #ifndef SQLITE_OMIT_SUBQUERY
  53629. case TK_SELECT:
  53630. case TK_EXISTS:
  53631. testcase( pExpr->op==TK_SELECT );
  53632. testcase( pExpr->op==TK_EXISTS );
  53633. #endif
  53634. testcase( pExpr->op==TK_ID );
  53635. testcase( pExpr->op==TK_COLUMN );
  53636. testcase( pExpr->op==TK_AGG_FUNCTION );
  53637. testcase( pExpr->op==TK_AGG_COLUMN );
  53638. pWalker->u.i = 0;
  53639. return WRC_Abort;
  53640. default:
  53641. return WRC_Continue;
  53642. }
  53643. }
  53644. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  53645. UNUSED_PARAMETER(NotUsed);
  53646. pWalker->u.i = 0;
  53647. return WRC_Abort;
  53648. }
  53649. static int exprIsConst(Expr *p, int initFlag){
  53650. Walker w;
  53651. w.u.i = initFlag;
  53652. w.xExprCallback = exprNodeIsConstant;
  53653. w.xSelectCallback = selectNodeIsConstant;
  53654. sqlite3WalkExpr(&w, p);
  53655. return w.u.i;
  53656. }
  53657. /*
  53658. ** Walk an expression tree. Return 1 if the expression is constant
  53659. ** and 0 if it involves variables or function calls.
  53660. **
  53661. ** For the purposes of this function, a double-quoted string (ex: "abc")
  53662. ** is considered a variable but a single-quoted string (ex: 'abc') is
  53663. ** a constant.
  53664. */
  53665. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  53666. return exprIsConst(p, 1);
  53667. }
  53668. /*
  53669. ** Walk an expression tree. Return 1 if the expression is constant
  53670. ** that does no originate from the ON or USING clauses of a join.
  53671. ** Return 0 if it involves variables or function calls or terms from
  53672. ** an ON or USING clause.
  53673. */
  53674. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  53675. return exprIsConst(p, 3);
  53676. }
  53677. /*
  53678. ** Walk an expression tree. Return 1 if the expression is constant
  53679. ** or a function call with constant arguments. Return and 0 if there
  53680. ** are any variables.
  53681. **
  53682. ** For the purposes of this function, a double-quoted string (ex: "abc")
  53683. ** is considered a variable but a single-quoted string (ex: 'abc') is
  53684. ** a constant.
  53685. */
  53686. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  53687. return exprIsConst(p, 2);
  53688. }
  53689. /*
  53690. ** If the expression p codes a constant integer that is small enough
  53691. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  53692. ** in *pValue. If the expression is not an integer or if it is too big
  53693. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  53694. */
  53695. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  53696. int rc = 0;
  53697. if( p->flags & EP_IntValue ){
  53698. *pValue = p->iTable;
  53699. return 1;
  53700. }
  53701. switch( p->op ){
  53702. case TK_INTEGER: {
  53703. rc = sqlite3GetInt32((char*)p->token.z, pValue);
  53704. break;
  53705. }
  53706. case TK_UPLUS: {
  53707. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  53708. break;
  53709. }
  53710. case TK_UMINUS: {
  53711. int v;
  53712. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  53713. *pValue = -v;
  53714. rc = 1;
  53715. }
  53716. break;
  53717. }
  53718. default: break;
  53719. }
  53720. if( rc ){
  53721. p->op = TK_INTEGER;
  53722. p->flags |= EP_IntValue;
  53723. p->iTable = *pValue;
  53724. }
  53725. return rc;
  53726. }
  53727. /*
  53728. ** Return TRUE if the given string is a row-id column name.
  53729. */
  53730. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  53731. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  53732. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  53733. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  53734. return 0;
  53735. }
  53736. /*
  53737. ** Return true if the IN operator optimization is enabled and
  53738. ** the SELECT statement p exists and is of the
  53739. ** simple form:
  53740. **
  53741. ** SELECT <column> FROM <table>
  53742. **
  53743. ** If this is the case, it may be possible to use an existing table
  53744. ** or index instead of generating an epheremal table.
  53745. */
  53746. #ifndef SQLITE_OMIT_SUBQUERY
  53747. static int isCandidateForInOpt(Select *p){
  53748. SrcList *pSrc;
  53749. ExprList *pEList;
  53750. Table *pTab;
  53751. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  53752. if( p->pPrior ) return 0; /* Not a compound SELECT */
  53753. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  53754. return 0; /* No DISTINCT keyword and no aggregate functions */
  53755. }
  53756. if( p->pGroupBy ) return 0; /* Has no GROUP BY clause */
  53757. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  53758. if( p->pOffset ) return 0;
  53759. if( p->pWhere ) return 0; /* Has no WHERE clause */
  53760. pSrc = p->pSrc;
  53761. assert( pSrc!=0 );
  53762. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  53763. if( pSrc->a[0].pSelect ) return 0; /* FROM clause is not a subquery */
  53764. pTab = pSrc->a[0].pTab;
  53765. if( pTab==0 ) return 0;
  53766. if( pTab->pSelect ) return 0; /* FROM clause is not a view */
  53767. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  53768. pEList = p->pEList;
  53769. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  53770. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  53771. return 1;
  53772. }
  53773. #endif /* SQLITE_OMIT_SUBQUERY */
  53774. /*
  53775. ** This function is used by the implementation of the IN (...) operator.
  53776. ** It's job is to find or create a b-tree structure that may be used
  53777. ** either to test for membership of the (...) set or to iterate through
  53778. ** its members, skipping duplicates.
  53779. **
  53780. ** The cursor opened on the structure (database table, database index
  53781. ** or ephermal table) is stored in pX->iTable before this function returns.
  53782. ** The returned value indicates the structure type, as follows:
  53783. **
  53784. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  53785. ** IN_INDEX_INDEX - The cursor was opened on a database index.
  53786. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  53787. ** populated epheremal table.
  53788. **
  53789. ** An existing structure may only be used if the SELECT is of the simple
  53790. ** form:
  53791. **
  53792. ** SELECT <column> FROM <table>
  53793. **
  53794. ** If prNotFound parameter is 0, then the structure will be used to iterate
  53795. ** through the set members, skipping any duplicates. In this case an
  53796. ** epheremal table must be used unless the selected <column> is guaranteed
  53797. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  53798. ** is unique by virtue of a constraint or implicit index.
  53799. **
  53800. ** If the prNotFound parameter is not 0, then the structure will be used
  53801. ** for fast set membership tests. In this case an epheremal table must
  53802. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  53803. ** be found with <column> as its left-most column.
  53804. **
  53805. ** When the structure is being used for set membership tests, the user
  53806. ** needs to know whether or not the structure contains an SQL NULL
  53807. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  53808. ** If there is a chance that the structure may contain a NULL value at
  53809. ** runtime, then a register is allocated and the register number written
  53810. ** to *prNotFound. If there is no chance that the structure contains a
  53811. ** NULL value, then *prNotFound is left unchanged.
  53812. **
  53813. ** If a register is allocated and its location stored in *prNotFound, then
  53814. ** its initial value is NULL. If the structure does not remain constant
  53815. ** for the duration of the query (i.e. the set is a correlated sub-select),
  53816. ** the value of the allocated register is reset to NULL each time the
  53817. ** structure is repopulated. This allows the caller to use vdbe code
  53818. ** equivalent to the following:
  53819. **
  53820. ** if( register==NULL ){
  53821. ** has_null = <test if data structure contains null>
  53822. ** register = 1
  53823. ** }
  53824. **
  53825. ** in order to avoid running the <test if data structure contains null>
  53826. ** test more often than is necessary.
  53827. */
  53828. #ifndef SQLITE_OMIT_SUBQUERY
  53829. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  53830. Select *p;
  53831. int eType = 0;
  53832. int iTab = pParse->nTab++;
  53833. int mustBeUnique = !prNotFound;
  53834. /* The follwing if(...) expression is true if the SELECT is of the
  53835. ** simple form:
  53836. **
  53837. ** SELECT <column> FROM <table>
  53838. **
  53839. ** If this is the case, it may be possible to use an existing table
  53840. ** or index instead of generating an epheremal table.
  53841. */
  53842. p = pX->pSelect;
  53843. if( isCandidateForInOpt(p) ){
  53844. sqlite3 *db = pParse->db;
  53845. Index *pIdx;
  53846. Expr *pExpr = p->pEList->a[0].pExpr;
  53847. int iCol = pExpr->iColumn;
  53848. Vdbe *v = sqlite3GetVdbe(pParse);
  53849. /* This function is only called from two places. In both cases the vdbe
  53850. ** has already been allocated. So assume sqlite3GetVdbe() is always
  53851. ** successful here.
  53852. */
  53853. assert(v);
  53854. if( iCol<0 ){
  53855. int iMem = ++pParse->nMem;
  53856. int iAddr;
  53857. Table *pTab = p->pSrc->a[0].pTab;
  53858. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  53859. sqlite3VdbeUsesBtree(v, iDb);
  53860. iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
  53861. sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  53862. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  53863. eType = IN_INDEX_ROWID;
  53864. sqlite3VdbeJumpHere(v, iAddr);
  53865. }else{
  53866. /* The collation sequence used by the comparison. If an index is to
  53867. ** be used in place of a temp-table, it must be ordered according
  53868. ** to this collation sequence.
  53869. */
  53870. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  53871. /* Check that the affinity that will be used to perform the
  53872. ** comparison is the same as the affinity of the column. If
  53873. ** it is not, it is not possible to use any index.
  53874. */
  53875. Table *pTab = p->pSrc->a[0].pTab;
  53876. char aff = comparisonAffinity(pX);
  53877. int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
  53878. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  53879. if( (pIdx->aiColumn[0]==iCol)
  53880. && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
  53881. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  53882. ){
  53883. int iDb;
  53884. int iMem = ++pParse->nMem;
  53885. int iAddr;
  53886. char *pKey;
  53887. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  53888. iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
  53889. sqlite3VdbeUsesBtree(v, iDb);
  53890. iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
  53891. sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  53892. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
  53893. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  53894. pKey,P4_KEYINFO_HANDOFF);
  53895. VdbeComment((v, "%s", pIdx->zName));
  53896. eType = IN_INDEX_INDEX;
  53897. sqlite3VdbeJumpHere(v, iAddr);
  53898. if( prNotFound && !pTab->aCol[iCol].notNull ){
  53899. *prNotFound = ++pParse->nMem;
  53900. }
  53901. }
  53902. }
  53903. }
  53904. }
  53905. if( eType==0 ){
  53906. int rMayHaveNull = 0;
  53907. eType = IN_INDEX_EPH;
  53908. if( prNotFound ){
  53909. *prNotFound = rMayHaveNull = ++pParse->nMem;
  53910. }else if( pX->pLeft->iColumn<0 && pX->pSelect==0 ){
  53911. eType = IN_INDEX_ROWID;
  53912. }
  53913. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  53914. }else{
  53915. pX->iTable = iTab;
  53916. }
  53917. return eType;
  53918. }
  53919. #endif
  53920. /*
  53921. ** Generate code for scalar subqueries used as an expression
  53922. ** and IN operators. Examples:
  53923. **
  53924. ** (SELECT a FROM b) -- subquery
  53925. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  53926. ** x IN (4,5,11) -- IN operator with list on right-hand side
  53927. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  53928. **
  53929. ** The pExpr parameter describes the expression that contains the IN
  53930. ** operator or subquery.
  53931. **
  53932. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  53933. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  53934. ** to some integer key column of a table B-Tree. In this case, use an
  53935. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  53936. ** (slower) variable length keys B-Tree.
  53937. */
  53938. #ifndef SQLITE_OMIT_SUBQUERY
  53939. SQLITE_PRIVATE void sqlite3CodeSubselect(
  53940. Parse *pParse,
  53941. Expr *pExpr,
  53942. int rMayHaveNull,
  53943. int isRowid
  53944. ){
  53945. int testAddr = 0; /* One-time test address */
  53946. Vdbe *v = sqlite3GetVdbe(pParse);
  53947. if( v==0 ) return;
  53948. /* This code must be run in its entirety every time it is encountered
  53949. ** if any of the following is true:
  53950. **
  53951. ** * The right-hand side is a correlated subquery
  53952. ** * The right-hand side is an expression list containing variables
  53953. ** * We are inside a trigger
  53954. **
  53955. ** If all of the above are false, then we can run this code just once
  53956. ** save the results, and reuse the same result on subsequent invocations.
  53957. */
  53958. if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
  53959. int mem = ++pParse->nMem;
  53960. sqlite3VdbeAddOp1(v, OP_If, mem);
  53961. testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
  53962. assert( testAddr>0 || pParse->db->mallocFailed );
  53963. }
  53964. switch( pExpr->op ){
  53965. case TK_IN: {
  53966. char affinity;
  53967. KeyInfo keyInfo;
  53968. int addr; /* Address of OP_OpenEphemeral instruction */
  53969. Expr *pLeft = pExpr->pLeft;
  53970. if( rMayHaveNull ){
  53971. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  53972. }
  53973. affinity = sqlite3ExprAffinity(pLeft);
  53974. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  53975. ** expression it is handled the same way. A virtual table is
  53976. ** filled with single-field index keys representing the results
  53977. ** from the SELECT or the <exprlist>.
  53978. **
  53979. ** If the 'x' expression is a column value, or the SELECT...
  53980. ** statement returns a column value, then the affinity of that
  53981. ** column is used to build the index keys. If both 'x' and the
  53982. ** SELECT... statement are columns, then numeric affinity is used
  53983. ** if either column has NUMERIC or INTEGER affinity. If neither
  53984. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  53985. ** is used.
  53986. */
  53987. pExpr->iTable = pParse->nTab++;
  53988. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  53989. memset(&keyInfo, 0, sizeof(keyInfo));
  53990. keyInfo.nField = 1;
  53991. if( pExpr->pSelect ){
  53992. /* Case 1: expr IN (SELECT ...)
  53993. **
  53994. ** Generate code to write the results of the select into the temporary
  53995. ** table allocated and opened above.
  53996. */
  53997. SelectDest dest;
  53998. ExprList *pEList;
  53999. assert( !isRowid );
  54000. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  54001. dest.affinity = (u8)affinity;
  54002. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  54003. if( sqlite3Select(pParse, pExpr->pSelect, &dest) ){
  54004. return;
  54005. }
  54006. pEList = pExpr->pSelect->pEList;
  54007. if( pEList && pEList->nExpr>0 ){
  54008. keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  54009. pEList->a[0].pExpr);
  54010. }
  54011. }else if( pExpr->pList ){
  54012. /* Case 2: expr IN (exprlist)
  54013. **
  54014. ** For each expression, build an index key from the evaluation and
  54015. ** store it in the temporary table. If <expr> is a column, then use
  54016. ** that columns affinity when building index keys. If <expr> is not
  54017. ** a column, use numeric affinity.
  54018. */
  54019. int i;
  54020. ExprList *pList = pExpr->pList;
  54021. struct ExprList_item *pItem;
  54022. int r1, r2, r3;
  54023. if( !affinity ){
  54024. affinity = SQLITE_AFF_NONE;
  54025. }
  54026. keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  54027. /* Loop through each expression in <exprlist>. */
  54028. r1 = sqlite3GetTempReg(pParse);
  54029. r2 = sqlite3GetTempReg(pParse);
  54030. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  54031. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  54032. Expr *pE2 = pItem->pExpr;
  54033. /* If the expression is not constant then we will need to
  54034. ** disable the test that was generated above that makes sure
  54035. ** this code only executes once. Because for a non-constant
  54036. ** expression we need to rerun this code each time.
  54037. */
  54038. if( testAddr && !sqlite3ExprIsConstant(pE2) ){
  54039. sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
  54040. testAddr = 0;
  54041. }
  54042. /* Evaluate the expression and insert it into the temp table */
  54043. pParse->disableColCache++;
  54044. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  54045. assert( pParse->disableColCache>0 );
  54046. pParse->disableColCache--;
  54047. if( isRowid ){
  54048. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
  54049. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  54050. }else{
  54051. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  54052. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  54053. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  54054. }
  54055. }
  54056. sqlite3ReleaseTempReg(pParse, r1);
  54057. sqlite3ReleaseTempReg(pParse, r2);
  54058. }
  54059. if( !isRowid ){
  54060. sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
  54061. }
  54062. break;
  54063. }
  54064. case TK_EXISTS:
  54065. case TK_SELECT: {
  54066. /* This has to be a scalar SELECT. Generate code to put the
  54067. ** value of this select in a memory cell and record the number
  54068. ** of the memory cell in iColumn.
  54069. */
  54070. static const Token one = { (u8*)"1", 0, 1 };
  54071. Select *pSel;
  54072. SelectDest dest;
  54073. pSel = pExpr->pSelect;
  54074. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  54075. if( pExpr->op==TK_SELECT ){
  54076. dest.eDest = SRT_Mem;
  54077. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
  54078. VdbeComment((v, "Init subquery result"));
  54079. }else{
  54080. dest.eDest = SRT_Exists;
  54081. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
  54082. VdbeComment((v, "Init EXISTS result"));
  54083. }
  54084. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  54085. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
  54086. if( sqlite3Select(pParse, pSel, &dest) ){
  54087. return;
  54088. }
  54089. pExpr->iColumn = dest.iParm;
  54090. break;
  54091. }
  54092. }
  54093. if( testAddr ){
  54094. sqlite3VdbeJumpHere(v, testAddr-1);
  54095. }
  54096. return;
  54097. }
  54098. #endif /* SQLITE_OMIT_SUBQUERY */
  54099. /*
  54100. ** Duplicate an 8-byte value
  54101. */
  54102. static char *dup8bytes(Vdbe *v, const char *in){
  54103. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  54104. if( out ){
  54105. memcpy(out, in, 8);
  54106. }
  54107. return out;
  54108. }
  54109. /*
  54110. ** Generate an instruction that will put the floating point
  54111. ** value described by z[0..n-1] into register iMem.
  54112. **
  54113. ** The z[] string will probably not be zero-terminated. But the
  54114. ** z[n] character is guaranteed to be something that does not look
  54115. ** like the continuation of the number.
  54116. */
  54117. static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
  54118. assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
  54119. assert( !z || !isdigit(z[n]) );
  54120. UNUSED_PARAMETER(n);
  54121. if( z ){
  54122. double value;
  54123. char *zV;
  54124. sqlite3AtoF(z, &value);
  54125. if( sqlite3IsNaN(value) ){
  54126. sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
  54127. }else{
  54128. if( negateFlag ) value = -value;
  54129. zV = dup8bytes(v, (char*)&value);
  54130. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  54131. }
  54132. }
  54133. }
  54134. /*
  54135. ** Generate an instruction that will put the integer describe by
  54136. ** text z[0..n-1] into register iMem.
  54137. **
  54138. ** The z[] string will probably not be zero-terminated. But the
  54139. ** z[n] character is guaranteed to be something that does not look
  54140. ** like the continuation of the number.
  54141. */
  54142. static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
  54143. const char *z;
  54144. if( pExpr->flags & EP_IntValue ){
  54145. int i = pExpr->iTable;
  54146. if( negFlag ) i = -i;
  54147. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  54148. }else if( (z = (char*)pExpr->token.z)!=0 ){
  54149. int i;
  54150. int n = pExpr->token.n;
  54151. assert( !isdigit(z[n]) );
  54152. if( sqlite3GetInt32(z, &i) ){
  54153. if( negFlag ) i = -i;
  54154. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  54155. }else if( sqlite3FitsIn64Bits(z, negFlag) ){
  54156. i64 value;
  54157. char *zV;
  54158. sqlite3Atoi64(z, &value);
  54159. if( negFlag ) value = -value;
  54160. zV = dup8bytes(v, (char*)&value);
  54161. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  54162. }else{
  54163. codeReal(v, z, n, negFlag, iMem);
  54164. }
  54165. }
  54166. }
  54167. /*
  54168. ** Generate code that will extract the iColumn-th column from
  54169. ** table pTab and store the column value in a register. An effort
  54170. ** is made to store the column value in register iReg, but this is
  54171. ** not guaranteed. The location of the column value is returned.
  54172. **
  54173. ** There must be an open cursor to pTab in iTable when this routine
  54174. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  54175. **
  54176. ** This routine might attempt to reuse the value of the column that
  54177. ** has already been loaded into a register. The value will always
  54178. ** be used if it has not undergone any affinity changes. But if
  54179. ** an affinity change has occurred, then the cached value will only be
  54180. ** used if allowAffChng is true.
  54181. */
  54182. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  54183. Parse *pParse, /* Parsing and code generating context */
  54184. Table *pTab, /* Description of the table we are reading from */
  54185. int iColumn, /* Index of the table column */
  54186. int iTable, /* The cursor pointing to the table */
  54187. int iReg, /* Store results here */
  54188. int allowAffChng /* True if prior affinity changes are OK */
  54189. ){
  54190. Vdbe *v = pParse->pVdbe;
  54191. int i;
  54192. struct yColCache *p;
  54193. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  54194. if( p->iTable==iTable && p->iColumn==iColumn
  54195. && (!p->affChange || allowAffChng) ){
  54196. #if 0
  54197. sqlite3VdbeAddOp0(v, OP_Noop);
  54198. VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
  54199. #endif
  54200. return p->iReg;
  54201. }
  54202. }
  54203. assert( v!=0 );
  54204. if( iColumn<0 ){
  54205. int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
  54206. sqlite3VdbeAddOp2(v, op, iTable, iReg);
  54207. }else if( pTab==0 ){
  54208. sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
  54209. }else{
  54210. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  54211. sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
  54212. sqlite3ColumnDefault(v, pTab, iColumn);
  54213. #ifndef SQLITE_OMIT_FLOATING_POINT
  54214. if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
  54215. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  54216. }
  54217. #endif
  54218. }
  54219. if( pParse->disableColCache==0 ){
  54220. i = pParse->iColCache;
  54221. p = &pParse->aColCache[i];
  54222. p->iTable = iTable;
  54223. p->iColumn = iColumn;
  54224. p->iReg = iReg;
  54225. p->affChange = 0;
  54226. i++;
  54227. if( i>=ArraySize(pParse->aColCache) ) i = 0;
  54228. if( i>pParse->nColCache ) pParse->nColCache = i;
  54229. pParse->iColCache = i;
  54230. }
  54231. return iReg;
  54232. }
  54233. /*
  54234. ** Clear all column cache entries associated with the vdbe
  54235. ** cursor with cursor number iTable.
  54236. */
  54237. SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
  54238. if( iTable<0 ){
  54239. pParse->nColCache = 0;
  54240. pParse->iColCache = 0;
  54241. }else{
  54242. int i;
  54243. for(i=0; i<pParse->nColCache; i++){
  54244. if( pParse->aColCache[i].iTable==iTable ){
  54245. testcase( i==pParse->nColCache-1 );
  54246. pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
  54247. pParse->iColCache = pParse->nColCache;
  54248. }
  54249. }
  54250. }
  54251. }
  54252. /*
  54253. ** Record the fact that an affinity change has occurred on iCount
  54254. ** registers starting with iStart.
  54255. */
  54256. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  54257. int iEnd = iStart + iCount - 1;
  54258. int i;
  54259. for(i=0; i<pParse->nColCache; i++){
  54260. int r = pParse->aColCache[i].iReg;
  54261. if( r>=iStart && r<=iEnd ){
  54262. pParse->aColCache[i].affChange = 1;
  54263. }
  54264. }
  54265. }
  54266. /*
  54267. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  54268. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  54269. */
  54270. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  54271. int i;
  54272. if( iFrom==iTo ) return;
  54273. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  54274. for(i=0; i<pParse->nColCache; i++){
  54275. int x = pParse->aColCache[i].iReg;
  54276. if( x>=iFrom && x<iFrom+nReg ){
  54277. pParse->aColCache[i].iReg += iTo-iFrom;
  54278. }
  54279. }
  54280. }
  54281. /*
  54282. ** Generate code to copy content from registers iFrom...iFrom+nReg-1
  54283. ** over to iTo..iTo+nReg-1.
  54284. */
  54285. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
  54286. int i;
  54287. if( iFrom==iTo ) return;
  54288. for(i=0; i<nReg; i++){
  54289. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
  54290. }
  54291. }
  54292. /*
  54293. ** Return true if any register in the range iFrom..iTo (inclusive)
  54294. ** is used as part of the column cache.
  54295. */
  54296. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  54297. int i;
  54298. for(i=0; i<pParse->nColCache; i++){
  54299. int r = pParse->aColCache[i].iReg;
  54300. if( r>=iFrom && r<=iTo ) return 1;
  54301. }
  54302. return 0;
  54303. }
  54304. /*
  54305. ** There is a value in register iReg.
  54306. **
  54307. ** We are going to modify the value, so we need to make sure it
  54308. ** is not a cached register. If iReg is a cached register,
  54309. ** then clear the corresponding cache line.
  54310. */
  54311. SQLITE_PRIVATE void sqlite3ExprWritableRegister(Parse *pParse, int iReg){
  54312. int i;
  54313. if( usedAsColumnCache(pParse, iReg, iReg) ){
  54314. for(i=0; i<pParse->nColCache; i++){
  54315. if( pParse->aColCache[i].iReg==iReg ){
  54316. pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
  54317. pParse->iColCache = pParse->nColCache;
  54318. }
  54319. }
  54320. }
  54321. }
  54322. /*
  54323. ** If the last instruction coded is an ephemeral copy of any of
  54324. ** the registers in the nReg registers beginning with iReg, then
  54325. ** convert the last instruction from OP_SCopy to OP_Copy.
  54326. */
  54327. SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
  54328. int addr;
  54329. VdbeOp *pOp;
  54330. Vdbe *v;
  54331. v = pParse->pVdbe;
  54332. addr = sqlite3VdbeCurrentAddr(v);
  54333. pOp = sqlite3VdbeGetOp(v, addr-1);
  54334. assert( pOp || pParse->db->mallocFailed );
  54335. if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
  54336. pOp->opcode = OP_Copy;
  54337. }
  54338. }
  54339. /*
  54340. ** Generate code to store the value of the iAlias-th alias in register
  54341. ** target. The first time this is called, pExpr is evaluated to compute
  54342. ** the value of the alias. The value is stored in an auxiliary register
  54343. ** and the number of that register is returned. On subsequent calls,
  54344. ** the register number is returned without generating any code.
  54345. **
  54346. ** Note that in order for this to work, code must be generated in the
  54347. ** same order that it is executed.
  54348. **
  54349. ** Aliases are numbered starting with 1. So iAlias is in the range
  54350. ** of 1 to pParse->nAlias inclusive.
  54351. **
  54352. ** pParse->aAlias[iAlias-1] records the register number where the value
  54353. ** of the iAlias-th alias is stored. If zero, that means that the
  54354. ** alias has not yet been computed.
  54355. */
  54356. static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
  54357. sqlite3 *db = pParse->db;
  54358. int iReg;
  54359. if( pParse->nAliasAlloc<pParse->nAlias ){
  54360. pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
  54361. sizeof(pParse->aAlias[0])*pParse->nAlias );
  54362. testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
  54363. if( db->mallocFailed ) return 0;
  54364. memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
  54365. (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
  54366. pParse->nAliasAlloc = pParse->nAlias;
  54367. }
  54368. assert( iAlias>0 && iAlias<=pParse->nAlias );
  54369. iReg = pParse->aAlias[iAlias-1];
  54370. if( iReg==0 ){
  54371. if( pParse->disableColCache ){
  54372. iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  54373. }else{
  54374. iReg = ++pParse->nMem;
  54375. sqlite3ExprCode(pParse, pExpr, iReg);
  54376. pParse->aAlias[iAlias-1] = iReg;
  54377. }
  54378. }
  54379. return iReg;
  54380. }
  54381. /*
  54382. ** Generate code into the current Vdbe to evaluate the given
  54383. ** expression. Attempt to store the results in register "target".
  54384. ** Return the register where results are stored.
  54385. **
  54386. ** With this routine, there is no guarantee that results will
  54387. ** be stored in target. The result might be stored in some other
  54388. ** register if it is convenient to do so. The calling function
  54389. ** must check the return code and move the results to the desired
  54390. ** register.
  54391. */
  54392. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  54393. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  54394. int op; /* The opcode being coded */
  54395. int inReg = target; /* Results stored in register inReg */
  54396. int regFree1 = 0; /* If non-zero free this temporary register */
  54397. int regFree2 = 0; /* If non-zero free this temporary register */
  54398. int r1, r2, r3, r4; /* Various register numbers */
  54399. sqlite3 *db;
  54400. db = pParse->db;
  54401. assert( v!=0 || db->mallocFailed );
  54402. assert( target>0 && target<=pParse->nMem );
  54403. if( v==0 ) return 0;
  54404. if( pExpr==0 ){
  54405. op = TK_NULL;
  54406. }else{
  54407. op = pExpr->op;
  54408. }
  54409. switch( op ){
  54410. case TK_AGG_COLUMN: {
  54411. AggInfo *pAggInfo = pExpr->pAggInfo;
  54412. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  54413. if( !pAggInfo->directMode ){
  54414. assert( pCol->iMem>0 );
  54415. inReg = pCol->iMem;
  54416. break;
  54417. }else if( pAggInfo->useSortingIdx ){
  54418. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
  54419. pCol->iSorterColumn, target);
  54420. break;
  54421. }
  54422. /* Otherwise, fall thru into the TK_COLUMN case */
  54423. }
  54424. case TK_COLUMN: {
  54425. if( pExpr->iTable<0 ){
  54426. /* This only happens when coding check constraints */
  54427. assert( pParse->ckBase>0 );
  54428. inReg = pExpr->iColumn + pParse->ckBase;
  54429. }else{
  54430. testcase( (pExpr->flags & EP_AnyAff)!=0 );
  54431. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  54432. pExpr->iColumn, pExpr->iTable, target,
  54433. pExpr->flags & EP_AnyAff);
  54434. }
  54435. break;
  54436. }
  54437. case TK_INTEGER: {
  54438. codeInteger(v, pExpr, 0, target);
  54439. break;
  54440. }
  54441. case TK_FLOAT: {
  54442. codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
  54443. break;
  54444. }
  54445. case TK_STRING: {
  54446. sqlite3DequoteExpr(db, pExpr);
  54447. sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
  54448. (char*)pExpr->token.z, pExpr->token.n);
  54449. break;
  54450. }
  54451. case TK_NULL: {
  54452. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  54453. break;
  54454. }
  54455. #ifndef SQLITE_OMIT_BLOB_LITERAL
  54456. case TK_BLOB: {
  54457. int n;
  54458. const char *z;
  54459. char *zBlob;
  54460. assert( pExpr->token.n>=3 );
  54461. assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
  54462. assert( pExpr->token.z[1]=='\'' );
  54463. assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
  54464. n = pExpr->token.n - 3;
  54465. z = (char*)pExpr->token.z + 2;
  54466. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  54467. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  54468. break;
  54469. }
  54470. #endif
  54471. case TK_VARIABLE: {
  54472. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
  54473. if( pExpr->token.n>1 ){
  54474. sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
  54475. }
  54476. break;
  54477. }
  54478. case TK_REGISTER: {
  54479. inReg = pExpr->iTable;
  54480. break;
  54481. }
  54482. case TK_AS: {
  54483. inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
  54484. break;
  54485. }
  54486. #ifndef SQLITE_OMIT_CAST
  54487. case TK_CAST: {
  54488. /* Expressions of the form: CAST(pLeft AS token) */
  54489. int aff, to_op;
  54490. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  54491. aff = sqlite3AffinityType(&pExpr->token);
  54492. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  54493. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  54494. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  54495. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  54496. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  54497. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  54498. testcase( to_op==OP_ToText );
  54499. testcase( to_op==OP_ToBlob );
  54500. testcase( to_op==OP_ToNumeric );
  54501. testcase( to_op==OP_ToInt );
  54502. testcase( to_op==OP_ToReal );
  54503. if( inReg!=target ){
  54504. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  54505. inReg = target;
  54506. }
  54507. sqlite3VdbeAddOp1(v, to_op, inReg);
  54508. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  54509. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  54510. break;
  54511. }
  54512. #endif /* SQLITE_OMIT_CAST */
  54513. case TK_LT:
  54514. case TK_LE:
  54515. case TK_GT:
  54516. case TK_GE:
  54517. case TK_NE:
  54518. case TK_EQ: {
  54519. assert( TK_LT==OP_Lt );
  54520. assert( TK_LE==OP_Le );
  54521. assert( TK_GT==OP_Gt );
  54522. assert( TK_GE==OP_Ge );
  54523. assert( TK_EQ==OP_Eq );
  54524. assert( TK_NE==OP_Ne );
  54525. testcase( op==TK_LT );
  54526. testcase( op==TK_LE );
  54527. testcase( op==TK_GT );
  54528. testcase( op==TK_GE );
  54529. testcase( op==TK_EQ );
  54530. testcase( op==TK_NE );
  54531. codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
  54532. pExpr->pRight, &r2, &regFree2);
  54533. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  54534. r1, r2, inReg, SQLITE_STOREP2);
  54535. testcase( regFree1==0 );
  54536. testcase( regFree2==0 );
  54537. break;
  54538. }
  54539. case TK_AND:
  54540. case TK_OR:
  54541. case TK_PLUS:
  54542. case TK_STAR:
  54543. case TK_MINUS:
  54544. case TK_REM:
  54545. case TK_BITAND:
  54546. case TK_BITOR:
  54547. case TK_SLASH:
  54548. case TK_LSHIFT:
  54549. case TK_RSHIFT:
  54550. case TK_CONCAT: {
  54551. assert( TK_AND==OP_And );
  54552. assert( TK_OR==OP_Or );
  54553. assert( TK_PLUS==OP_Add );
  54554. assert( TK_MINUS==OP_Subtract );
  54555. assert( TK_REM==OP_Remainder );
  54556. assert( TK_BITAND==OP_BitAnd );
  54557. assert( TK_BITOR==OP_BitOr );
  54558. assert( TK_SLASH==OP_Divide );
  54559. assert( TK_LSHIFT==OP_ShiftLeft );
  54560. assert( TK_RSHIFT==OP_ShiftRight );
  54561. assert( TK_CONCAT==OP_Concat );
  54562. testcase( op==TK_AND );
  54563. testcase( op==TK_OR );
  54564. testcase( op==TK_PLUS );
  54565. testcase( op==TK_MINUS );
  54566. testcase( op==TK_REM );
  54567. testcase( op==TK_BITAND );
  54568. testcase( op==TK_BITOR );
  54569. testcase( op==TK_SLASH );
  54570. testcase( op==TK_LSHIFT );
  54571. testcase( op==TK_RSHIFT );
  54572. testcase( op==TK_CONCAT );
  54573. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  54574. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  54575. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  54576. testcase( regFree1==0 );
  54577. testcase( regFree2==0 );
  54578. break;
  54579. }
  54580. case TK_UMINUS: {
  54581. Expr *pLeft = pExpr->pLeft;
  54582. assert( pLeft );
  54583. if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
  54584. if( pLeft->op==TK_FLOAT ){
  54585. codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
  54586. }else{
  54587. codeInteger(v, pLeft, 1, target);
  54588. }
  54589. }else{
  54590. regFree1 = r1 = sqlite3GetTempReg(pParse);
  54591. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  54592. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  54593. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  54594. testcase( regFree2==0 );
  54595. }
  54596. inReg = target;
  54597. break;
  54598. }
  54599. case TK_BITNOT:
  54600. case TK_NOT: {
  54601. assert( TK_BITNOT==OP_BitNot );
  54602. assert( TK_NOT==OP_Not );
  54603. testcase( op==TK_BITNOT );
  54604. testcase( op==TK_NOT );
  54605. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  54606. testcase( regFree1==0 );
  54607. inReg = target;
  54608. sqlite3VdbeAddOp2(v, op, r1, inReg);
  54609. break;
  54610. }
  54611. case TK_ISNULL:
  54612. case TK_NOTNULL: {
  54613. int addr;
  54614. assert( TK_ISNULL==OP_IsNull );
  54615. assert( TK_NOTNULL==OP_NotNull );
  54616. testcase( op==TK_ISNULL );
  54617. testcase( op==TK_NOTNULL );
  54618. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  54619. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  54620. testcase( regFree1==0 );
  54621. addr = sqlite3VdbeAddOp1(v, op, r1);
  54622. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  54623. sqlite3VdbeJumpHere(v, addr);
  54624. break;
  54625. }
  54626. case TK_AGG_FUNCTION: {
  54627. AggInfo *pInfo = pExpr->pAggInfo;
  54628. if( pInfo==0 ){
  54629. sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
  54630. &pExpr->span);
  54631. }else{
  54632. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  54633. }
  54634. break;
  54635. }
  54636. case TK_CONST_FUNC:
  54637. case TK_FUNCTION: {
  54638. ExprList *pList = pExpr->pList;
  54639. int nExpr = pList ? pList->nExpr : 0;
  54640. FuncDef *pDef;
  54641. int nId;
  54642. const char *zId;
  54643. int constMask = 0;
  54644. int i;
  54645. u8 enc = ENC(db);
  54646. CollSeq *pColl = 0;
  54647. testcase( op==TK_CONST_FUNC );
  54648. testcase( op==TK_FUNCTION );
  54649. zId = (char*)pExpr->token.z;
  54650. nId = pExpr->token.n;
  54651. pDef = sqlite3FindFunction(db, zId, nId, nExpr, enc, 0);
  54652. assert( pDef!=0 );
  54653. if( pList ){
  54654. nExpr = pList->nExpr;
  54655. r1 = sqlite3GetTempRange(pParse, nExpr);
  54656. sqlite3ExprCodeExprList(pParse, pList, r1, 1);
  54657. }else{
  54658. nExpr = r1 = 0;
  54659. }
  54660. #ifndef SQLITE_OMIT_VIRTUALTABLE
  54661. /* Possibly overload the function if the first argument is
  54662. ** a virtual table column.
  54663. **
  54664. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  54665. ** second argument, not the first, as the argument to test to
  54666. ** see if it is a column in a virtual table. This is done because
  54667. ** the left operand of infix functions (the operand we want to
  54668. ** control overloading) ends up as the second argument to the
  54669. ** function. The expression "A glob B" is equivalent to
  54670. ** "glob(B,A). We want to use the A in "A glob B" to test
  54671. ** for function overloading. But we use the B term in "glob(B,A)".
  54672. */
  54673. if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
  54674. pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
  54675. }else if( nExpr>0 ){
  54676. pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
  54677. }
  54678. #endif
  54679. for(i=0; i<nExpr && i<32; i++){
  54680. if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
  54681. constMask |= (1<<i);
  54682. }
  54683. if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  54684. pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  54685. }
  54686. }
  54687. if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
  54688. if( !pColl ) pColl = db->pDfltColl;
  54689. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  54690. }
  54691. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  54692. (char*)pDef, P4_FUNCDEF);
  54693. sqlite3VdbeChangeP5(v, (u8)nExpr);
  54694. if( nExpr ){
  54695. sqlite3ReleaseTempRange(pParse, r1, nExpr);
  54696. }
  54697. sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
  54698. break;
  54699. }
  54700. #ifndef SQLITE_OMIT_SUBQUERY
  54701. case TK_EXISTS:
  54702. case TK_SELECT: {
  54703. testcase( op==TK_EXISTS );
  54704. testcase( op==TK_SELECT );
  54705. if( pExpr->iColumn==0 ){
  54706. sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  54707. }
  54708. inReg = pExpr->iColumn;
  54709. break;
  54710. }
  54711. case TK_IN: {
  54712. int rNotFound = 0;
  54713. int rMayHaveNull = 0;
  54714. int j2, j3, j4, j5;
  54715. char affinity;
  54716. int eType;
  54717. VdbeNoopComment((v, "begin IN expr r%d", target));
  54718. eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
  54719. if( rMayHaveNull ){
  54720. rNotFound = ++pParse->nMem;
  54721. }
  54722. /* Figure out the affinity to use to create a key from the results
  54723. ** of the expression. affinityStr stores a static string suitable for
  54724. ** P4 of OP_MakeRecord.
  54725. */
  54726. affinity = comparisonAffinity(pExpr);
  54727. /* Code the <expr> from "<expr> IN (...)". The temporary table
  54728. ** pExpr->iTable contains the values that make up the (...) set.
  54729. */
  54730. pParse->disableColCache++;
  54731. sqlite3ExprCode(pParse, pExpr->pLeft, target);
  54732. pParse->disableColCache--;
  54733. j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
  54734. if( eType==IN_INDEX_ROWID ){
  54735. j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
  54736. j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
  54737. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  54738. j5 = sqlite3VdbeAddOp0(v, OP_Goto);
  54739. sqlite3VdbeJumpHere(v, j3);
  54740. sqlite3VdbeJumpHere(v, j4);
  54741. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  54742. }else{
  54743. r2 = regFree2 = sqlite3GetTempReg(pParse);
  54744. /* Create a record and test for set membership. If the set contains
  54745. ** the value, then jump to the end of the test code. The target
  54746. ** register still contains the true (1) value written to it earlier.
  54747. */
  54748. sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
  54749. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  54750. j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
  54751. /* If the set membership test fails, then the result of the
  54752. ** "x IN (...)" expression must be either 0 or NULL. If the set
  54753. ** contains no NULL values, then the result is 0. If the set
  54754. ** contains one or more NULL values, then the result of the
  54755. ** expression is also NULL.
  54756. */
  54757. if( rNotFound==0 ){
  54758. /* This branch runs if it is known at compile time (now) that
  54759. ** the set contains no NULL values. This happens as the result
  54760. ** of a "NOT NULL" constraint in the database schema. No need
  54761. ** to test the data structure at runtime in this case.
  54762. */
  54763. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  54764. }else{
  54765. /* This block populates the rNotFound register with either NULL
  54766. ** or 0 (an integer value). If the data structure contains one
  54767. ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
  54768. ** to 0. If register rMayHaveNull is already set to some value
  54769. ** other than NULL, then the test has already been run and
  54770. ** rNotFound is already populated.
  54771. */
  54772. static const char nullRecord[] = { 0x02, 0x00 };
  54773. j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
  54774. sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
  54775. sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0,
  54776. nullRecord, P4_STATIC);
  54777. j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
  54778. sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
  54779. sqlite3VdbeJumpHere(v, j4);
  54780. sqlite3VdbeJumpHere(v, j3);
  54781. /* Copy the value of register rNotFound (which is either NULL or 0)
  54782. ** into the target register. This will be the result of the
  54783. ** expression.
  54784. */
  54785. sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
  54786. }
  54787. }
  54788. sqlite3VdbeJumpHere(v, j2);
  54789. sqlite3VdbeJumpHere(v, j5);
  54790. VdbeComment((v, "end IN expr r%d", target));
  54791. break;
  54792. }
  54793. #endif
  54794. /*
  54795. ** x BETWEEN y AND z
  54796. **
  54797. ** This is equivalent to
  54798. **
  54799. ** x>=y AND x<=z
  54800. **
  54801. ** X is stored in pExpr->pLeft.
  54802. ** Y is stored in pExpr->pList->a[0].pExpr.
  54803. ** Z is stored in pExpr->pList->a[1].pExpr.
  54804. */
  54805. case TK_BETWEEN: {
  54806. Expr *pLeft = pExpr->pLeft;
  54807. struct ExprList_item *pLItem = pExpr->pList->a;
  54808. Expr *pRight = pLItem->pExpr;
  54809. codeCompareOperands(pParse, pLeft, &r1, &regFree1,
  54810. pRight, &r2, &regFree2);
  54811. testcase( regFree1==0 );
  54812. testcase( regFree2==0 );
  54813. r3 = sqlite3GetTempReg(pParse);
  54814. r4 = sqlite3GetTempReg(pParse);
  54815. codeCompare(pParse, pLeft, pRight, OP_Ge,
  54816. r1, r2, r3, SQLITE_STOREP2);
  54817. pLItem++;
  54818. pRight = pLItem->pExpr;
  54819. sqlite3ReleaseTempReg(pParse, regFree2);
  54820. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  54821. testcase( regFree2==0 );
  54822. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  54823. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  54824. sqlite3ReleaseTempReg(pParse, r3);
  54825. sqlite3ReleaseTempReg(pParse, r4);
  54826. break;
  54827. }
  54828. case TK_UPLUS: {
  54829. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  54830. break;
  54831. }
  54832. /*
  54833. ** Form A:
  54834. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  54835. **
  54836. ** Form B:
  54837. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  54838. **
  54839. ** Form A is can be transformed into the equivalent form B as follows:
  54840. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  54841. ** WHEN x=eN THEN rN ELSE y END
  54842. **
  54843. ** X (if it exists) is in pExpr->pLeft.
  54844. ** Y is in pExpr->pRight. The Y is also optional. If there is no
  54845. ** ELSE clause and no other term matches, then the result of the
  54846. ** exprssion is NULL.
  54847. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  54848. **
  54849. ** The result of the expression is the Ri for the first matching Ei,
  54850. ** or if there is no matching Ei, the ELSE term Y, or if there is
  54851. ** no ELSE term, NULL.
  54852. */
  54853. case TK_CASE: {
  54854. int endLabel; /* GOTO label for end of CASE stmt */
  54855. int nextCase; /* GOTO label for next WHEN clause */
  54856. int nExpr; /* 2x number of WHEN terms */
  54857. int i; /* Loop counter */
  54858. ExprList *pEList; /* List of WHEN terms */
  54859. struct ExprList_item *aListelem; /* Array of WHEN terms */
  54860. Expr opCompare; /* The X==Ei expression */
  54861. Expr cacheX; /* Cached expression X */
  54862. Expr *pX; /* The X expression */
  54863. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  54864. assert(pExpr->pList);
  54865. assert((pExpr->pList->nExpr % 2) == 0);
  54866. assert(pExpr->pList->nExpr > 0);
  54867. pEList = pExpr->pList;
  54868. aListelem = pEList->a;
  54869. nExpr = pEList->nExpr;
  54870. endLabel = sqlite3VdbeMakeLabel(v);
  54871. if( (pX = pExpr->pLeft)!=0 ){
  54872. cacheX = *pX;
  54873. testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
  54874. cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
  54875. testcase( regFree1==0 );
  54876. cacheX.op = TK_REGISTER;
  54877. opCompare.op = TK_EQ;
  54878. opCompare.pLeft = &cacheX;
  54879. pTest = &opCompare;
  54880. }
  54881. pParse->disableColCache++;
  54882. for(i=0; i<nExpr; i=i+2){
  54883. if( pX ){
  54884. assert( pTest!=0 );
  54885. opCompare.pRight = aListelem[i].pExpr;
  54886. }else{
  54887. pTest = aListelem[i].pExpr;
  54888. }
  54889. nextCase = sqlite3VdbeMakeLabel(v);
  54890. testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
  54891. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  54892. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  54893. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  54894. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  54895. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  54896. sqlite3VdbeResolveLabel(v, nextCase);
  54897. }
  54898. if( pExpr->pRight ){
  54899. sqlite3ExprCode(pParse, pExpr->pRight, target);
  54900. }else{
  54901. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  54902. }
  54903. sqlite3VdbeResolveLabel(v, endLabel);
  54904. assert( pParse->disableColCache>0 );
  54905. pParse->disableColCache--;
  54906. break;
  54907. }
  54908. #ifndef SQLITE_OMIT_TRIGGER
  54909. case TK_RAISE: {
  54910. if( !pParse->trigStack ){
  54911. sqlite3ErrorMsg(pParse,
  54912. "RAISE() may only be used within a trigger-program");
  54913. return 0;
  54914. }
  54915. if( pExpr->iColumn!=OE_Ignore ){
  54916. assert( pExpr->iColumn==OE_Rollback ||
  54917. pExpr->iColumn == OE_Abort ||
  54918. pExpr->iColumn == OE_Fail );
  54919. sqlite3DequoteExpr(db, pExpr);
  54920. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
  54921. (char*)pExpr->token.z, pExpr->token.n);
  54922. } else {
  54923. assert( pExpr->iColumn == OE_Ignore );
  54924. sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
  54925. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
  54926. VdbeComment((v, "raise(IGNORE)"));
  54927. }
  54928. break;
  54929. }
  54930. #endif
  54931. }
  54932. sqlite3ReleaseTempReg(pParse, regFree1);
  54933. sqlite3ReleaseTempReg(pParse, regFree2);
  54934. return inReg;
  54935. }
  54936. /*
  54937. ** Generate code to evaluate an expression and store the results
  54938. ** into a register. Return the register number where the results
  54939. ** are stored.
  54940. **
  54941. ** If the register is a temporary register that can be deallocated,
  54942. ** then write its number into *pReg. If the result register is not
  54943. ** a temporary, then set *pReg to zero.
  54944. */
  54945. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  54946. int r1 = sqlite3GetTempReg(pParse);
  54947. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  54948. if( r2==r1 ){
  54949. *pReg = r1;
  54950. }else{
  54951. sqlite3ReleaseTempReg(pParse, r1);
  54952. *pReg = 0;
  54953. }
  54954. return r2;
  54955. }
  54956. /*
  54957. ** Generate code that will evaluate expression pExpr and store the
  54958. ** results in register target. The results are guaranteed to appear
  54959. ** in register target.
  54960. */
  54961. SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  54962. int inReg;
  54963. assert( target>0 && target<=pParse->nMem );
  54964. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  54965. assert( pParse->pVdbe || pParse->db->mallocFailed );
  54966. if( inReg!=target && pParse->pVdbe ){
  54967. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  54968. }
  54969. return target;
  54970. }
  54971. /*
  54972. ** Generate code that evalutes the given expression and puts the result
  54973. ** in register target.
  54974. **
  54975. ** Also make a copy of the expression results into another "cache" register
  54976. ** and modify the expression so that the next time it is evaluated,
  54977. ** the result is a copy of the cache register.
  54978. **
  54979. ** This routine is used for expressions that are used multiple
  54980. ** times. They are evaluated once and the results of the expression
  54981. ** are reused.
  54982. */
  54983. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  54984. Vdbe *v = pParse->pVdbe;
  54985. int inReg;
  54986. inReg = sqlite3ExprCode(pParse, pExpr, target);
  54987. assert( target>0 );
  54988. if( pExpr->op!=TK_REGISTER ){
  54989. int iMem;
  54990. iMem = ++pParse->nMem;
  54991. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  54992. pExpr->iTable = iMem;
  54993. pExpr->op = TK_REGISTER;
  54994. }
  54995. return inReg;
  54996. }
  54997. /*
  54998. ** Return TRUE if pExpr is an constant expression that is appropriate
  54999. ** for factoring out of a loop. Appropriate expressions are:
  55000. **
  55001. ** * Any expression that evaluates to two or more opcodes.
  55002. **
  55003. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  55004. ** or OP_Variable that does not need to be placed in a
  55005. ** specific register.
  55006. **
  55007. ** There is no point in factoring out single-instruction constant
  55008. ** expressions that need to be placed in a particular register.
  55009. ** We could factor them out, but then we would end up adding an
  55010. ** OP_SCopy instruction to move the value into the correct register
  55011. ** later. We might as well just use the original instruction and
  55012. ** avoid the OP_SCopy.
  55013. */
  55014. static int isAppropriateForFactoring(Expr *p){
  55015. if( !sqlite3ExprIsConstantNotJoin(p) ){
  55016. return 0; /* Only constant expressions are appropriate for factoring */
  55017. }
  55018. if( (p->flags & EP_FixedDest)==0 ){
  55019. return 1; /* Any constant without a fixed destination is appropriate */
  55020. }
  55021. while( p->op==TK_UPLUS ) p = p->pLeft;
  55022. switch( p->op ){
  55023. #ifndef SQLITE_OMIT_BLOB_LITERAL
  55024. case TK_BLOB:
  55025. #endif
  55026. case TK_VARIABLE:
  55027. case TK_INTEGER:
  55028. case TK_FLOAT:
  55029. case TK_NULL:
  55030. case TK_STRING: {
  55031. testcase( p->op==TK_BLOB );
  55032. testcase( p->op==TK_VARIABLE );
  55033. testcase( p->op==TK_INTEGER );
  55034. testcase( p->op==TK_FLOAT );
  55035. testcase( p->op==TK_NULL );
  55036. testcase( p->op==TK_STRING );
  55037. /* Single-instruction constants with a fixed destination are
  55038. ** better done in-line. If we factor them, they will just end
  55039. ** up generating an OP_SCopy to move the value to the destination
  55040. ** register. */
  55041. return 0;
  55042. }
  55043. case TK_UMINUS: {
  55044. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  55045. return 0;
  55046. }
  55047. break;
  55048. }
  55049. default: {
  55050. break;
  55051. }
  55052. }
  55053. return 1;
  55054. }
  55055. /*
  55056. ** If pExpr is a constant expression that is appropriate for
  55057. ** factoring out of a loop, then evaluate the expression
  55058. ** into a register and convert the expression into a TK_REGISTER
  55059. ** expression.
  55060. */
  55061. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  55062. Parse *pParse = pWalker->pParse;
  55063. switch( pExpr->op ){
  55064. case TK_REGISTER: {
  55065. return 1;
  55066. }
  55067. case TK_FUNCTION:
  55068. case TK_AGG_FUNCTION:
  55069. case TK_CONST_FUNC: {
  55070. /* The arguments to a function have a fixed destination.
  55071. ** Mark them this way to avoid generated unneeded OP_SCopy
  55072. ** instructions.
  55073. */
  55074. ExprList *pList = pExpr->pList;
  55075. if( pList ){
  55076. int i = pList->nExpr;
  55077. struct ExprList_item *pItem = pList->a;
  55078. for(; i>0; i--, pItem++){
  55079. if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
  55080. }
  55081. }
  55082. break;
  55083. }
  55084. }
  55085. if( isAppropriateForFactoring(pExpr) ){
  55086. int r1 = ++pParse->nMem;
  55087. int r2;
  55088. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  55089. if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
  55090. pExpr->op = TK_REGISTER;
  55091. pExpr->iTable = r2;
  55092. return WRC_Prune;
  55093. }
  55094. return WRC_Continue;
  55095. }
  55096. /*
  55097. ** Preevaluate constant subexpressions within pExpr and store the
  55098. ** results in registers. Modify pExpr so that the constant subexpresions
  55099. ** are TK_REGISTER opcodes that refer to the precomputed values.
  55100. */
  55101. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  55102. Walker w;
  55103. w.xExprCallback = evalConstExpr;
  55104. w.xSelectCallback = 0;
  55105. w.pParse = pParse;
  55106. sqlite3WalkExpr(&w, pExpr);
  55107. }
  55108. /*
  55109. ** Generate code that pushes the value of every element of the given
  55110. ** expression list into a sequence of registers beginning at target.
  55111. **
  55112. ** Return the number of elements evaluated.
  55113. */
  55114. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  55115. Parse *pParse, /* Parsing context */
  55116. ExprList *pList, /* The expression list to be coded */
  55117. int target, /* Where to write results */
  55118. int doHardCopy /* Make a hard copy of every element */
  55119. ){
  55120. struct ExprList_item *pItem;
  55121. int i, n;
  55122. assert( pList!=0 );
  55123. assert( target>0 );
  55124. n = pList->nExpr;
  55125. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  55126. if( pItem->iAlias ){
  55127. int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
  55128. Vdbe *v = sqlite3GetVdbe(pParse);
  55129. if( iReg!=target+i ){
  55130. sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
  55131. }
  55132. }else{
  55133. sqlite3ExprCode(pParse, pItem->pExpr, target+i);
  55134. }
  55135. if( doHardCopy ){
  55136. sqlite3ExprHardCopy(pParse, target, n);
  55137. }
  55138. }
  55139. return n;
  55140. }
  55141. /*
  55142. ** Generate code for a boolean expression such that a jump is made
  55143. ** to the label "dest" if the expression is true but execution
  55144. ** continues straight thru if the expression is false.
  55145. **
  55146. ** If the expression evaluates to NULL (neither true nor false), then
  55147. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  55148. **
  55149. ** This code depends on the fact that certain token values (ex: TK_EQ)
  55150. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  55151. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  55152. ** the make process cause these values to align. Assert()s in the code
  55153. ** below verify that the numbers are aligned correctly.
  55154. */
  55155. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  55156. Vdbe *v = pParse->pVdbe;
  55157. int op = 0;
  55158. int regFree1 = 0;
  55159. int regFree2 = 0;
  55160. int r1, r2;
  55161. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  55162. if( v==0 || pExpr==0 ) return;
  55163. op = pExpr->op;
  55164. switch( op ){
  55165. case TK_AND: {
  55166. int d2 = sqlite3VdbeMakeLabel(v);
  55167. testcase( jumpIfNull==0 );
  55168. testcase( pParse->disableColCache==0 );
  55169. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  55170. pParse->disableColCache++;
  55171. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  55172. assert( pParse->disableColCache>0 );
  55173. pParse->disableColCache--;
  55174. sqlite3VdbeResolveLabel(v, d2);
  55175. break;
  55176. }
  55177. case TK_OR: {
  55178. testcase( jumpIfNull==0 );
  55179. testcase( pParse->disableColCache==0 );
  55180. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  55181. pParse->disableColCache++;
  55182. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  55183. assert( pParse->disableColCache>0 );
  55184. pParse->disableColCache--;
  55185. break;
  55186. }
  55187. case TK_NOT: {
  55188. testcase( jumpIfNull==0 );
  55189. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  55190. break;
  55191. }
  55192. case TK_LT:
  55193. case TK_LE:
  55194. case TK_GT:
  55195. case TK_GE:
  55196. case TK_NE:
  55197. case TK_EQ: {
  55198. assert( TK_LT==OP_Lt );
  55199. assert( TK_LE==OP_Le );
  55200. assert( TK_GT==OP_Gt );
  55201. assert( TK_GE==OP_Ge );
  55202. assert( TK_EQ==OP_Eq );
  55203. assert( TK_NE==OP_Ne );
  55204. testcase( op==TK_LT );
  55205. testcase( op==TK_LE );
  55206. testcase( op==TK_GT );
  55207. testcase( op==TK_GE );
  55208. testcase( op==TK_EQ );
  55209. testcase( op==TK_NE );
  55210. testcase( jumpIfNull==0 );
  55211. codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
  55212. pExpr->pRight, &r2, &regFree2);
  55213. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  55214. r1, r2, dest, jumpIfNull);
  55215. testcase( regFree1==0 );
  55216. testcase( regFree2==0 );
  55217. break;
  55218. }
  55219. case TK_ISNULL:
  55220. case TK_NOTNULL: {
  55221. assert( TK_ISNULL==OP_IsNull );
  55222. assert( TK_NOTNULL==OP_NotNull );
  55223. testcase( op==TK_ISNULL );
  55224. testcase( op==TK_NOTNULL );
  55225. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  55226. sqlite3VdbeAddOp2(v, op, r1, dest);
  55227. testcase( regFree1==0 );
  55228. break;
  55229. }
  55230. case TK_BETWEEN: {
  55231. /* x BETWEEN y AND z
  55232. **
  55233. ** Is equivalent to
  55234. **
  55235. ** x>=y AND x<=z
  55236. **
  55237. ** Code it as such, taking care to do the common subexpression
  55238. ** elementation of x.
  55239. */
  55240. Expr exprAnd;
  55241. Expr compLeft;
  55242. Expr compRight;
  55243. Expr exprX;
  55244. exprX = *pExpr->pLeft;
  55245. exprAnd.op = TK_AND;
  55246. exprAnd.pLeft = &compLeft;
  55247. exprAnd.pRight = &compRight;
  55248. compLeft.op = TK_GE;
  55249. compLeft.pLeft = &exprX;
  55250. compLeft.pRight = pExpr->pList->a[0].pExpr;
  55251. compRight.op = TK_LE;
  55252. compRight.pLeft = &exprX;
  55253. compRight.pRight = pExpr->pList->a[1].pExpr;
  55254. exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
  55255. testcase( regFree1==0 );
  55256. exprX.op = TK_REGISTER;
  55257. testcase( jumpIfNull==0 );
  55258. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  55259. break;
  55260. }
  55261. default: {
  55262. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  55263. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  55264. testcase( regFree1==0 );
  55265. testcase( jumpIfNull==0 );
  55266. break;
  55267. }
  55268. }
  55269. sqlite3ReleaseTempReg(pParse, regFree1);
  55270. sqlite3ReleaseTempReg(pParse, regFree2);
  55271. }
  55272. /*
  55273. ** Generate code for a boolean expression such that a jump is made
  55274. ** to the label "dest" if the expression is false but execution
  55275. ** continues straight thru if the expression is true.
  55276. **
  55277. ** If the expression evaluates to NULL (neither true nor false) then
  55278. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  55279. ** is 0.
  55280. */
  55281. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  55282. Vdbe *v = pParse->pVdbe;
  55283. int op = 0;
  55284. int regFree1 = 0;
  55285. int regFree2 = 0;
  55286. int r1, r2;
  55287. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  55288. if( v==0 || pExpr==0 ) return;
  55289. /* The value of pExpr->op and op are related as follows:
  55290. **
  55291. ** pExpr->op op
  55292. ** --------- ----------
  55293. ** TK_ISNULL OP_NotNull
  55294. ** TK_NOTNULL OP_IsNull
  55295. ** TK_NE OP_Eq
  55296. ** TK_EQ OP_Ne
  55297. ** TK_GT OP_Le
  55298. ** TK_LE OP_Gt
  55299. ** TK_GE OP_Lt
  55300. ** TK_LT OP_Ge
  55301. **
  55302. ** For other values of pExpr->op, op is undefined and unused.
  55303. ** The value of TK_ and OP_ constants are arranged such that we
  55304. ** can compute the mapping above using the following expression.
  55305. ** Assert()s verify that the computation is correct.
  55306. */
  55307. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  55308. /* Verify correct alignment of TK_ and OP_ constants
  55309. */
  55310. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  55311. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  55312. assert( pExpr->op!=TK_NE || op==OP_Eq );
  55313. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  55314. assert( pExpr->op!=TK_LT || op==OP_Ge );
  55315. assert( pExpr->op!=TK_LE || op==OP_Gt );
  55316. assert( pExpr->op!=TK_GT || op==OP_Le );
  55317. assert( pExpr->op!=TK_GE || op==OP_Lt );
  55318. switch( pExpr->op ){
  55319. case TK_AND: {
  55320. testcase( jumpIfNull==0 );
  55321. testcase( pParse->disableColCache==0 );
  55322. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  55323. pParse->disableColCache++;
  55324. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  55325. assert( pParse->disableColCache>0 );
  55326. pParse->disableColCache--;
  55327. break;
  55328. }
  55329. case TK_OR: {
  55330. int d2 = sqlite3VdbeMakeLabel(v);
  55331. testcase( jumpIfNull==0 );
  55332. testcase( pParse->disableColCache==0 );
  55333. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  55334. pParse->disableColCache++;
  55335. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  55336. assert( pParse->disableColCache>0 );
  55337. pParse->disableColCache--;
  55338. sqlite3VdbeResolveLabel(v, d2);
  55339. break;
  55340. }
  55341. case TK_NOT: {
  55342. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  55343. break;
  55344. }
  55345. case TK_LT:
  55346. case TK_LE:
  55347. case TK_GT:
  55348. case TK_GE:
  55349. case TK_NE:
  55350. case TK_EQ: {
  55351. testcase( op==TK_LT );
  55352. testcase( op==TK_LE );
  55353. testcase( op==TK_GT );
  55354. testcase( op==TK_GE );
  55355. testcase( op==TK_EQ );
  55356. testcase( op==TK_NE );
  55357. testcase( jumpIfNull==0 );
  55358. codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
  55359. pExpr->pRight, &r2, &regFree2);
  55360. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  55361. r1, r2, dest, jumpIfNull);
  55362. testcase( regFree1==0 );
  55363. testcase( regFree2==0 );
  55364. break;
  55365. }
  55366. case TK_ISNULL:
  55367. case TK_NOTNULL: {
  55368. testcase( op==TK_ISNULL );
  55369. testcase( op==TK_NOTNULL );
  55370. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  55371. sqlite3VdbeAddOp2(v, op, r1, dest);
  55372. testcase( regFree1==0 );
  55373. break;
  55374. }
  55375. case TK_BETWEEN: {
  55376. /* x BETWEEN y AND z
  55377. **
  55378. ** Is equivalent to
  55379. **
  55380. ** x>=y AND x<=z
  55381. **
  55382. ** Code it as such, taking care to do the common subexpression
  55383. ** elementation of x.
  55384. */
  55385. Expr exprAnd;
  55386. Expr compLeft;
  55387. Expr compRight;
  55388. Expr exprX;
  55389. exprX = *pExpr->pLeft;
  55390. exprAnd.op = TK_AND;
  55391. exprAnd.pLeft = &compLeft;
  55392. exprAnd.pRight = &compRight;
  55393. compLeft.op = TK_GE;
  55394. compLeft.pLeft = &exprX;
  55395. compLeft.pRight = pExpr->pList->a[0].pExpr;
  55396. compRight.op = TK_LE;
  55397. compRight.pLeft = &exprX;
  55398. compRight.pRight = pExpr->pList->a[1].pExpr;
  55399. exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
  55400. testcase( regFree1==0 );
  55401. exprX.op = TK_REGISTER;
  55402. testcase( jumpIfNull==0 );
  55403. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  55404. break;
  55405. }
  55406. default: {
  55407. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  55408. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  55409. testcase( regFree1==0 );
  55410. testcase( jumpIfNull==0 );
  55411. break;
  55412. }
  55413. }
  55414. sqlite3ReleaseTempReg(pParse, regFree1);
  55415. sqlite3ReleaseTempReg(pParse, regFree2);
  55416. }
  55417. /*
  55418. ** Do a deep comparison of two expression trees. Return TRUE (non-zero)
  55419. ** if they are identical and return FALSE if they differ in any way.
  55420. **
  55421. ** Sometimes this routine will return FALSE even if the two expressions
  55422. ** really are equivalent. If we cannot prove that the expressions are
  55423. ** identical, we return FALSE just to be safe. So if this routine
  55424. ** returns false, then you do not really know for certain if the two
  55425. ** expressions are the same. But if you get a TRUE return, then you
  55426. ** can be sure the expressions are the same. In the places where
  55427. ** this routine is used, it does not hurt to get an extra FALSE - that
  55428. ** just might result in some slightly slower code. But returning
  55429. ** an incorrect TRUE could lead to a malfunction.
  55430. */
  55431. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
  55432. int i;
  55433. if( pA==0||pB==0 ){
  55434. return pB==pA;
  55435. }
  55436. if( pA->op!=pB->op ) return 0;
  55437. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
  55438. if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
  55439. if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
  55440. if( pA->pList ){
  55441. if( pB->pList==0 ) return 0;
  55442. if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
  55443. for(i=0; i<pA->pList->nExpr; i++){
  55444. if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
  55445. return 0;
  55446. }
  55447. }
  55448. }else if( pB->pList ){
  55449. return 0;
  55450. }
  55451. if( pA->pSelect || pB->pSelect ) return 0;
  55452. if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
  55453. if( pA->op!=TK_COLUMN && pA->token.z ){
  55454. if( pB->token.z==0 ) return 0;
  55455. if( pB->token.n!=pA->token.n ) return 0;
  55456. if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
  55457. return 0;
  55458. }
  55459. }
  55460. return 1;
  55461. }
  55462. /*
  55463. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  55464. ** the new element. Return a negative number if malloc fails.
  55465. */
  55466. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  55467. int i;
  55468. pInfo->aCol = sqlite3ArrayAllocate(
  55469. db,
  55470. pInfo->aCol,
  55471. sizeof(pInfo->aCol[0]),
  55472. 3,
  55473. &pInfo->nColumn,
  55474. &pInfo->nColumnAlloc,
  55475. &i
  55476. );
  55477. return i;
  55478. }
  55479. /*
  55480. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  55481. ** the new element. Return a negative number if malloc fails.
  55482. */
  55483. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  55484. int i;
  55485. pInfo->aFunc = sqlite3ArrayAllocate(
  55486. db,
  55487. pInfo->aFunc,
  55488. sizeof(pInfo->aFunc[0]),
  55489. 3,
  55490. &pInfo->nFunc,
  55491. &pInfo->nFuncAlloc,
  55492. &i
  55493. );
  55494. return i;
  55495. }
  55496. /*
  55497. ** This is the xExprCallback for a tree walker. It is used to
  55498. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  55499. ** for additional information.
  55500. */
  55501. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  55502. int i;
  55503. NameContext *pNC = pWalker->u.pNC;
  55504. Parse *pParse = pNC->pParse;
  55505. SrcList *pSrcList = pNC->pSrcList;
  55506. AggInfo *pAggInfo = pNC->pAggInfo;
  55507. switch( pExpr->op ){
  55508. case TK_AGG_COLUMN:
  55509. case TK_COLUMN: {
  55510. testcase( pExpr->op==TK_AGG_COLUMN );
  55511. testcase( pExpr->op==TK_COLUMN );
  55512. /* Check to see if the column is in one of the tables in the FROM
  55513. ** clause of the aggregate query */
  55514. if( pSrcList ){
  55515. struct SrcList_item *pItem = pSrcList->a;
  55516. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  55517. struct AggInfo_col *pCol;
  55518. if( pExpr->iTable==pItem->iCursor ){
  55519. /* If we reach this point, it means that pExpr refers to a table
  55520. ** that is in the FROM clause of the aggregate query.
  55521. **
  55522. ** Make an entry for the column in pAggInfo->aCol[] if there
  55523. ** is not an entry there already.
  55524. */
  55525. int k;
  55526. pCol = pAggInfo->aCol;
  55527. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  55528. if( pCol->iTable==pExpr->iTable &&
  55529. pCol->iColumn==pExpr->iColumn ){
  55530. break;
  55531. }
  55532. }
  55533. if( (k>=pAggInfo->nColumn)
  55534. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  55535. ){
  55536. pCol = &pAggInfo->aCol[k];
  55537. pCol->pTab = pExpr->pTab;
  55538. pCol->iTable = pExpr->iTable;
  55539. pCol->iColumn = pExpr->iColumn;
  55540. pCol->iMem = ++pParse->nMem;
  55541. pCol->iSorterColumn = -1;
  55542. pCol->pExpr = pExpr;
  55543. if( pAggInfo->pGroupBy ){
  55544. int j, n;
  55545. ExprList *pGB = pAggInfo->pGroupBy;
  55546. struct ExprList_item *pTerm = pGB->a;
  55547. n = pGB->nExpr;
  55548. for(j=0; j<n; j++, pTerm++){
  55549. Expr *pE = pTerm->pExpr;
  55550. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  55551. pE->iColumn==pExpr->iColumn ){
  55552. pCol->iSorterColumn = j;
  55553. break;
  55554. }
  55555. }
  55556. }
  55557. if( pCol->iSorterColumn<0 ){
  55558. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  55559. }
  55560. }
  55561. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  55562. ** because it was there before or because we just created it).
  55563. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  55564. ** pAggInfo->aCol[] entry.
  55565. */
  55566. pExpr->pAggInfo = pAggInfo;
  55567. pExpr->op = TK_AGG_COLUMN;
  55568. pExpr->iAgg = k;
  55569. break;
  55570. } /* endif pExpr->iTable==pItem->iCursor */
  55571. } /* end loop over pSrcList */
  55572. }
  55573. return WRC_Prune;
  55574. }
  55575. case TK_AGG_FUNCTION: {
  55576. /* The pNC->nDepth==0 test causes aggregate functions in subqueries
  55577. ** to be ignored */
  55578. if( pNC->nDepth==0 ){
  55579. /* Check to see if pExpr is a duplicate of another aggregate
  55580. ** function that is already in the pAggInfo structure
  55581. */
  55582. struct AggInfo_func *pItem = pAggInfo->aFunc;
  55583. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  55584. if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
  55585. break;
  55586. }
  55587. }
  55588. if( i>=pAggInfo->nFunc ){
  55589. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  55590. */
  55591. u8 enc = ENC(pParse->db);
  55592. i = addAggInfoFunc(pParse->db, pAggInfo);
  55593. if( i>=0 ){
  55594. pItem = &pAggInfo->aFunc[i];
  55595. pItem->pExpr = pExpr;
  55596. pItem->iMem = ++pParse->nMem;
  55597. pItem->pFunc = sqlite3FindFunction(pParse->db,
  55598. (char*)pExpr->token.z, pExpr->token.n,
  55599. pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
  55600. if( pExpr->flags & EP_Distinct ){
  55601. pItem->iDistinct = pParse->nTab++;
  55602. }else{
  55603. pItem->iDistinct = -1;
  55604. }
  55605. }
  55606. }
  55607. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  55608. */
  55609. pExpr->iAgg = i;
  55610. pExpr->pAggInfo = pAggInfo;
  55611. return WRC_Prune;
  55612. }
  55613. }
  55614. }
  55615. return WRC_Continue;
  55616. }
  55617. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  55618. NameContext *pNC = pWalker->u.pNC;
  55619. if( pNC->nDepth==0 ){
  55620. pNC->nDepth++;
  55621. sqlite3WalkSelect(pWalker, pSelect);
  55622. pNC->nDepth--;
  55623. return WRC_Prune;
  55624. }else{
  55625. return WRC_Continue;
  55626. }
  55627. }
  55628. /*
  55629. ** Analyze the given expression looking for aggregate functions and
  55630. ** for variables that need to be added to the pParse->aAgg[] array.
  55631. ** Make additional entries to the pParse->aAgg[] array as necessary.
  55632. **
  55633. ** This routine should only be called after the expression has been
  55634. ** analyzed by sqlite3ResolveExprNames().
  55635. */
  55636. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  55637. Walker w;
  55638. w.xExprCallback = analyzeAggregate;
  55639. w.xSelectCallback = analyzeAggregatesInSelect;
  55640. w.u.pNC = pNC;
  55641. sqlite3WalkExpr(&w, pExpr);
  55642. }
  55643. /*
  55644. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  55645. ** expression list. Return the number of errors.
  55646. **
  55647. ** If an error is found, the analysis is cut short.
  55648. */
  55649. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  55650. struct ExprList_item *pItem;
  55651. int i;
  55652. if( pList ){
  55653. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  55654. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  55655. }
  55656. }
  55657. }
  55658. /*
  55659. ** Allocate or deallocate temporary use registers during code generation.
  55660. */
  55661. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  55662. if( pParse->nTempReg==0 ){
  55663. return ++pParse->nMem;
  55664. }
  55665. return pParse->aTempReg[--pParse->nTempReg];
  55666. }
  55667. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  55668. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  55669. sqlite3ExprWritableRegister(pParse, iReg);
  55670. pParse->aTempReg[pParse->nTempReg++] = iReg;
  55671. }
  55672. }
  55673. /*
  55674. ** Allocate or deallocate a block of nReg consecutive registers
  55675. */
  55676. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  55677. int i, n;
  55678. i = pParse->iRangeReg;
  55679. n = pParse->nRangeReg;
  55680. if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
  55681. pParse->iRangeReg += nReg;
  55682. pParse->nRangeReg -= nReg;
  55683. }else{
  55684. i = pParse->nMem+1;
  55685. pParse->nMem += nReg;
  55686. }
  55687. return i;
  55688. }
  55689. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  55690. if( nReg>pParse->nRangeReg ){
  55691. pParse->nRangeReg = nReg;
  55692. pParse->iRangeReg = iReg;
  55693. }
  55694. }
  55695. /************** End of expr.c ************************************************/
  55696. /************** Begin file alter.c *******************************************/
  55697. /*
  55698. ** 2005 February 15
  55699. **
  55700. ** The author disclaims copyright to this source code. In place of
  55701. ** a legal notice, here is a blessing:
  55702. **
  55703. ** May you do good and not evil.
  55704. ** May you find forgiveness for yourself and forgive others.
  55705. ** May you share freely, never taking more than you give.
  55706. **
  55707. *************************************************************************
  55708. ** This file contains C code routines that used to generate VDBE code
  55709. ** that implements the ALTER TABLE command.
  55710. **
  55711. ** $Id: alter.c,v 1.51 2008/12/10 19:26:22 drh Exp $
  55712. */
  55713. /*
  55714. ** The code in this file only exists if we are not omitting the
  55715. ** ALTER TABLE logic from the build.
  55716. */
  55717. #ifndef SQLITE_OMIT_ALTERTABLE
  55718. /*
  55719. ** This function is used by SQL generated to implement the
  55720. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  55721. ** CREATE INDEX command. The second is a table name. The table name in
  55722. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  55723. ** argument and the result returned. Examples:
  55724. **
  55725. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  55726. ** -> 'CREATE TABLE def(a, b, c)'
  55727. **
  55728. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  55729. ** -> 'CREATE INDEX i ON def(a, b, c)'
  55730. */
  55731. static void renameTableFunc(
  55732. sqlite3_context *context,
  55733. int NotUsed,
  55734. sqlite3_value **argv
  55735. ){
  55736. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  55737. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  55738. int token;
  55739. Token tname;
  55740. unsigned char const *zCsr = zSql;
  55741. int len = 0;
  55742. char *zRet;
  55743. sqlite3 *db = sqlite3_context_db_handle(context);
  55744. UNUSED_PARAMETER(NotUsed);
  55745. /* The principle used to locate the table name in the CREATE TABLE
  55746. ** statement is that the table name is the first non-space token that
  55747. ** is immediately followed by a TK_LP or TK_USING token.
  55748. */
  55749. if( zSql ){
  55750. do {
  55751. if( !*zCsr ){
  55752. /* Ran out of input before finding an opening bracket. Return NULL. */
  55753. return;
  55754. }
  55755. /* Store the token that zCsr points to in tname. */
  55756. tname.z = zCsr;
  55757. tname.n = len;
  55758. /* Advance zCsr to the next token. Store that token type in 'token',
  55759. ** and its length in 'len' (to be used next iteration of this loop).
  55760. */
  55761. do {
  55762. zCsr += len;
  55763. len = sqlite3GetToken(zCsr, &token);
  55764. } while( token==TK_SPACE );
  55765. assert( len>0 );
  55766. } while( token!=TK_LP && token!=TK_USING );
  55767. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql,
  55768. zTableName, tname.z+tname.n);
  55769. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  55770. }
  55771. }
  55772. #ifndef SQLITE_OMIT_TRIGGER
  55773. /* This function is used by SQL generated to implement the
  55774. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  55775. ** statement. The second is a table name. The table name in the CREATE
  55776. ** TRIGGER statement is replaced with the third argument and the result
  55777. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  55778. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  55779. */
  55780. static void renameTriggerFunc(
  55781. sqlite3_context *context,
  55782. int NotUsed,
  55783. sqlite3_value **argv
  55784. ){
  55785. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  55786. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  55787. int token;
  55788. Token tname;
  55789. int dist = 3;
  55790. unsigned char const *zCsr = zSql;
  55791. int len = 0;
  55792. char *zRet;
  55793. sqlite3 *db = sqlite3_context_db_handle(context);
  55794. UNUSED_PARAMETER(NotUsed);
  55795. /* The principle used to locate the table name in the CREATE TRIGGER
  55796. ** statement is that the table name is the first token that is immediatedly
  55797. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  55798. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  55799. */
  55800. if( zSql ){
  55801. do {
  55802. if( !*zCsr ){
  55803. /* Ran out of input before finding the table name. Return NULL. */
  55804. return;
  55805. }
  55806. /* Store the token that zCsr points to in tname. */
  55807. tname.z = zCsr;
  55808. tname.n = len;
  55809. /* Advance zCsr to the next token. Store that token type in 'token',
  55810. ** and its length in 'len' (to be used next iteration of this loop).
  55811. */
  55812. do {
  55813. zCsr += len;
  55814. len = sqlite3GetToken(zCsr, &token);
  55815. }while( token==TK_SPACE );
  55816. assert( len>0 );
  55817. /* Variable 'dist' stores the number of tokens read since the most
  55818. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  55819. ** token is read and 'dist' equals 2, the condition stated above
  55820. ** to be met.
  55821. **
  55822. ** Note that ON cannot be a database, table or column name, so
  55823. ** there is no need to worry about syntax like
  55824. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  55825. */
  55826. dist++;
  55827. if( token==TK_DOT || token==TK_ON ){
  55828. dist = 0;
  55829. }
  55830. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  55831. /* Variable tname now contains the token that is the old table-name
  55832. ** in the CREATE TRIGGER statement.
  55833. */
  55834. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql,
  55835. zTableName, tname.z+tname.n);
  55836. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  55837. }
  55838. }
  55839. #endif /* !SQLITE_OMIT_TRIGGER */
  55840. /*
  55841. ** Register built-in functions used to help implement ALTER TABLE
  55842. */
  55843. SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
  55844. sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
  55845. renameTableFunc, 0, 0);
  55846. #ifndef SQLITE_OMIT_TRIGGER
  55847. sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
  55848. renameTriggerFunc, 0, 0);
  55849. #endif
  55850. }
  55851. /*
  55852. ** Generate the text of a WHERE expression which can be used to select all
  55853. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  55854. ** table pTab has no temporary triggers, or is itself stored in the
  55855. ** temporary database, NULL is returned.
  55856. */
  55857. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  55858. Trigger *pTrig;
  55859. char *zWhere = 0;
  55860. char *tmp = 0;
  55861. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  55862. /* If the table is not located in the temp-db (in which case NULL is
  55863. ** returned, loop through the tables list of triggers. For each trigger
  55864. ** that is not part of the temp-db schema, add a clause to the WHERE
  55865. ** expression being built up in zWhere.
  55866. */
  55867. if( pTab->pSchema!=pTempSchema ){
  55868. sqlite3 *db = pParse->db;
  55869. for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
  55870. if( pTrig->pSchema==pTempSchema ){
  55871. if( !zWhere ){
  55872. zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
  55873. }else{
  55874. tmp = zWhere;
  55875. zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
  55876. sqlite3DbFree(db, tmp);
  55877. }
  55878. }
  55879. }
  55880. }
  55881. return zWhere;
  55882. }
  55883. /*
  55884. ** Generate code to drop and reload the internal representation of table
  55885. ** pTab from the database, including triggers and temporary triggers.
  55886. ** Argument zName is the name of the table in the database schema at
  55887. ** the time the generated code is executed. This can be different from
  55888. ** pTab->zName if this function is being called to code part of an
  55889. ** "ALTER TABLE RENAME TO" statement.
  55890. */
  55891. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  55892. Vdbe *v;
  55893. char *zWhere;
  55894. int iDb; /* Index of database containing pTab */
  55895. #ifndef SQLITE_OMIT_TRIGGER
  55896. Trigger *pTrig;
  55897. #endif
  55898. v = sqlite3GetVdbe(pParse);
  55899. if( !v ) return;
  55900. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  55901. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  55902. assert( iDb>=0 );
  55903. #ifndef SQLITE_OMIT_TRIGGER
  55904. /* Drop any table triggers from the internal schema. */
  55905. for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
  55906. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  55907. assert( iTrigDb==iDb || iTrigDb==1 );
  55908. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
  55909. }
  55910. #endif
  55911. /* Drop the table and index from the internal schema */
  55912. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  55913. /* Reload the table, index and permanent trigger schemas. */
  55914. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  55915. if( !zWhere ) return;
  55916. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  55917. #ifndef SQLITE_OMIT_TRIGGER
  55918. /* Now, if the table is not stored in the temp database, reload any temp
  55919. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  55920. */
  55921. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  55922. sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
  55923. }
  55924. #endif
  55925. }
  55926. /*
  55927. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  55928. ** command.
  55929. */
  55930. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  55931. Parse *pParse, /* Parser context. */
  55932. SrcList *pSrc, /* The table to rename. */
  55933. Token *pName /* The new table name. */
  55934. ){
  55935. int iDb; /* Database that contains the table */
  55936. char *zDb; /* Name of database iDb */
  55937. Table *pTab; /* Table being renamed */
  55938. char *zName = 0; /* NULL-terminated version of pName */
  55939. sqlite3 *db = pParse->db; /* Database connection */
  55940. int nTabName; /* Number of UTF-8 characters in zTabName */
  55941. const char *zTabName; /* Original name of the table */
  55942. Vdbe *v;
  55943. #ifndef SQLITE_OMIT_TRIGGER
  55944. char *zWhere = 0; /* Where clause to locate temp triggers */
  55945. #endif
  55946. int isVirtualRename = 0; /* True if this is a v-table with an xRename() */
  55947. if( db->mallocFailed ) goto exit_rename_table;
  55948. assert( pSrc->nSrc==1 );
  55949. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  55950. pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  55951. if( !pTab ) goto exit_rename_table;
  55952. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  55953. zDb = db->aDb[iDb].zName;
  55954. /* Get a NULL terminated version of the new table name. */
  55955. zName = sqlite3NameFromToken(db, pName);
  55956. if( !zName ) goto exit_rename_table;
  55957. /* Check that a table or index named 'zName' does not already exist
  55958. ** in database iDb. If so, this is an error.
  55959. */
  55960. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  55961. sqlite3ErrorMsg(pParse,
  55962. "there is already another table or index with this name: %s", zName);
  55963. goto exit_rename_table;
  55964. }
  55965. /* Make sure it is not a system table being altered, or a reserved name
  55966. ** that the table is being renamed to.
  55967. */
  55968. if( sqlite3Strlen30(pTab->zName)>6
  55969. && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
  55970. ){
  55971. sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
  55972. goto exit_rename_table;
  55973. }
  55974. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  55975. goto exit_rename_table;
  55976. }
  55977. #ifndef SQLITE_OMIT_VIEW
  55978. if( pTab->pSelect ){
  55979. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  55980. goto exit_rename_table;
  55981. }
  55982. #endif
  55983. #ifndef SQLITE_OMIT_AUTHORIZATION
  55984. /* Invoke the authorization callback. */
  55985. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  55986. goto exit_rename_table;
  55987. }
  55988. #endif
  55989. #ifndef SQLITE_OMIT_VIRTUALTABLE
  55990. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  55991. goto exit_rename_table;
  55992. }
  55993. if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
  55994. isVirtualRename = 1;
  55995. }
  55996. #endif
  55997. /* Begin a transaction and code the VerifyCookie for database iDb.
  55998. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  55999. ** schema). Open a statement transaction if the table is a virtual
  56000. ** table.
  56001. */
  56002. v = sqlite3GetVdbe(pParse);
  56003. if( v==0 ){
  56004. goto exit_rename_table;
  56005. }
  56006. sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
  56007. sqlite3ChangeCookie(pParse, iDb);
  56008. /* If this is a virtual table, invoke the xRename() function if
  56009. ** one is defined. The xRename() callback will modify the names
  56010. ** of any resources used by the v-table implementation (including other
  56011. ** SQLite tables) that are identified by the name of the virtual table.
  56012. */
  56013. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56014. if( isVirtualRename ){
  56015. int i = ++pParse->nMem;
  56016. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  56017. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB);
  56018. }
  56019. #endif
  56020. /* figure out how many UTF-8 characters are in zName */
  56021. zTabName = pTab->zName;
  56022. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  56023. /* Modify the sqlite_master table to use the new table name. */
  56024. sqlite3NestedParse(pParse,
  56025. "UPDATE %Q.%s SET "
  56026. #ifdef SQLITE_OMIT_TRIGGER
  56027. "sql = sqlite_rename_table(sql, %Q), "
  56028. #else
  56029. "sql = CASE "
  56030. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  56031. "ELSE sqlite_rename_table(sql, %Q) END, "
  56032. #endif
  56033. "tbl_name = %Q, "
  56034. "name = CASE "
  56035. "WHEN type='table' THEN %Q "
  56036. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  56037. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  56038. "ELSE name END "
  56039. "WHERE tbl_name=%Q AND "
  56040. "(type='table' OR type='index' OR type='trigger');",
  56041. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  56042. #ifndef SQLITE_OMIT_TRIGGER
  56043. zName,
  56044. #endif
  56045. zName, nTabName, zTabName
  56046. );
  56047. #ifndef SQLITE_OMIT_AUTOINCREMENT
  56048. /* If the sqlite_sequence table exists in this database, then update
  56049. ** it with the new table name.
  56050. */
  56051. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  56052. sqlite3NestedParse(pParse,
  56053. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  56054. zDb, zName, pTab->zName);
  56055. }
  56056. #endif
  56057. #ifndef SQLITE_OMIT_TRIGGER
  56058. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  56059. ** table. Don't do this if the table being ALTERed is itself located in
  56060. ** the temp database.
  56061. */
  56062. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  56063. sqlite3NestedParse(pParse,
  56064. "UPDATE sqlite_temp_master SET "
  56065. "sql = sqlite_rename_trigger(sql, %Q), "
  56066. "tbl_name = %Q "
  56067. "WHERE %s;", zName, zName, zWhere);
  56068. sqlite3DbFree(db, zWhere);
  56069. }
  56070. #endif
  56071. /* Drop and reload the internal table schema. */
  56072. reloadTableSchema(pParse, pTab, zName);
  56073. exit_rename_table:
  56074. sqlite3SrcListDelete(db, pSrc);
  56075. sqlite3DbFree(db, zName);
  56076. }
  56077. /*
  56078. ** This function is called after an "ALTER TABLE ... ADD" statement
  56079. ** has been parsed. Argument pColDef contains the text of the new
  56080. ** column definition.
  56081. **
  56082. ** The Table structure pParse->pNewTable was extended to include
  56083. ** the new column during parsing.
  56084. */
  56085. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  56086. Table *pNew; /* Copy of pParse->pNewTable */
  56087. Table *pTab; /* Table being altered */
  56088. int iDb; /* Database number */
  56089. const char *zDb; /* Database name */
  56090. const char *zTab; /* Table name */
  56091. char *zCol; /* Null-terminated column definition */
  56092. Column *pCol; /* The new column */
  56093. Expr *pDflt; /* Default value for the new column */
  56094. sqlite3 *db; /* The database connection; */
  56095. db = pParse->db;
  56096. if( pParse->nErr || db->mallocFailed ) return;
  56097. pNew = pParse->pNewTable;
  56098. assert( pNew );
  56099. assert( sqlite3BtreeHoldsAllMutexes(db) );
  56100. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  56101. zDb = db->aDb[iDb].zName;
  56102. zTab = pNew->zName;
  56103. pCol = &pNew->aCol[pNew->nCol-1];
  56104. pDflt = pCol->pDflt;
  56105. pTab = sqlite3FindTable(db, zTab, zDb);
  56106. assert( pTab );
  56107. #ifndef SQLITE_OMIT_AUTHORIZATION
  56108. /* Invoke the authorization callback. */
  56109. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  56110. return;
  56111. }
  56112. #endif
  56113. /* If the default value for the new column was specified with a
  56114. ** literal NULL, then set pDflt to 0. This simplifies checking
  56115. ** for an SQL NULL default below.
  56116. */
  56117. if( pDflt && pDflt->op==TK_NULL ){
  56118. pDflt = 0;
  56119. }
  56120. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  56121. ** If there is a NOT NULL constraint, then the default value for the
  56122. ** column must not be NULL.
  56123. */
  56124. if( pCol->isPrimKey ){
  56125. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  56126. return;
  56127. }
  56128. if( pNew->pIndex ){
  56129. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  56130. return;
  56131. }
  56132. if( pCol->notNull && !pDflt ){
  56133. sqlite3ErrorMsg(pParse,
  56134. "Cannot add a NOT NULL column with default value NULL");
  56135. return;
  56136. }
  56137. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  56138. ** can handle (i.e. not CURRENT_TIME etc.)
  56139. */
  56140. if( pDflt ){
  56141. sqlite3_value *pVal;
  56142. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  56143. db->mallocFailed = 1;
  56144. return;
  56145. }
  56146. if( !pVal ){
  56147. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  56148. return;
  56149. }
  56150. sqlite3ValueFree(pVal);
  56151. }
  56152. /* Modify the CREATE TABLE statement. */
  56153. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  56154. if( zCol ){
  56155. char *zEnd = &zCol[pColDef->n-1];
  56156. while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
  56157. *zEnd-- = '\0';
  56158. }
  56159. sqlite3NestedParse(pParse,
  56160. "UPDATE \"%w\".%s SET "
  56161. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  56162. "WHERE type = 'table' AND name = %Q",
  56163. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  56164. zTab
  56165. );
  56166. sqlite3DbFree(db, zCol);
  56167. }
  56168. /* If the default value of the new column is NULL, then set the file
  56169. ** format to 2. If the default value of the new column is not NULL,
  56170. ** the file format becomes 3.
  56171. */
  56172. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  56173. /* Reload the schema of the modified table. */
  56174. reloadTableSchema(pParse, pTab, pTab->zName);
  56175. }
  56176. /*
  56177. ** This function is called by the parser after the table-name in
  56178. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  56179. ** pSrc is the full-name of the table being altered.
  56180. **
  56181. ** This routine makes a (partial) copy of the Table structure
  56182. ** for the table being altered and sets Parse.pNewTable to point
  56183. ** to it. Routines called by the parser as the column definition
  56184. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  56185. ** the copy. The copy of the Table structure is deleted by tokenize.c
  56186. ** after parsing is finished.
  56187. **
  56188. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  56189. ** coding the "ALTER TABLE ... ADD" statement.
  56190. */
  56191. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  56192. Table *pNew;
  56193. Table *pTab;
  56194. Vdbe *v;
  56195. int iDb;
  56196. int i;
  56197. int nAlloc;
  56198. sqlite3 *db = pParse->db;
  56199. /* Look up the table being altered. */
  56200. assert( pParse->pNewTable==0 );
  56201. assert( sqlite3BtreeHoldsAllMutexes(db) );
  56202. if( db->mallocFailed ) goto exit_begin_add_column;
  56203. pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  56204. if( !pTab ) goto exit_begin_add_column;
  56205. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56206. if( IsVirtual(pTab) ){
  56207. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  56208. goto exit_begin_add_column;
  56209. }
  56210. #endif
  56211. /* Make sure this is not an attempt to ALTER a view. */
  56212. if( pTab->pSelect ){
  56213. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  56214. goto exit_begin_add_column;
  56215. }
  56216. assert( pTab->addColOffset>0 );
  56217. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  56218. /* Put a copy of the Table struct in Parse.pNewTable for the
  56219. ** sqlite3AddColumn() function and friends to modify.
  56220. */
  56221. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  56222. if( !pNew ) goto exit_begin_add_column;
  56223. pParse->pNewTable = pNew;
  56224. pNew->nRef = 1;
  56225. pNew->db = db;
  56226. pNew->nCol = pTab->nCol;
  56227. assert( pNew->nCol>0 );
  56228. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  56229. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  56230. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  56231. pNew->zName = sqlite3DbStrDup(db, pTab->zName);
  56232. if( !pNew->aCol || !pNew->zName ){
  56233. db->mallocFailed = 1;
  56234. goto exit_begin_add_column;
  56235. }
  56236. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  56237. for(i=0; i<pNew->nCol; i++){
  56238. Column *pCol = &pNew->aCol[i];
  56239. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  56240. pCol->zColl = 0;
  56241. pCol->zType = 0;
  56242. pCol->pDflt = 0;
  56243. }
  56244. pNew->pSchema = db->aDb[iDb].pSchema;
  56245. pNew->addColOffset = pTab->addColOffset;
  56246. pNew->nRef = 1;
  56247. /* Begin a transaction and increment the schema cookie. */
  56248. sqlite3BeginWriteOperation(pParse, 0, iDb);
  56249. v = sqlite3GetVdbe(pParse);
  56250. if( !v ) goto exit_begin_add_column;
  56251. sqlite3ChangeCookie(pParse, iDb);
  56252. exit_begin_add_column:
  56253. sqlite3SrcListDelete(db, pSrc);
  56254. return;
  56255. }
  56256. #endif /* SQLITE_ALTER_TABLE */
  56257. /************** End of alter.c ***********************************************/
  56258. /************** Begin file analyze.c *****************************************/
  56259. /*
  56260. ** 2005 July 8
  56261. **
  56262. ** The author disclaims copyright to this source code. In place of
  56263. ** a legal notice, here is a blessing:
  56264. **
  56265. ** May you do good and not evil.
  56266. ** May you find forgiveness for yourself and forgive others.
  56267. ** May you share freely, never taking more than you give.
  56268. **
  56269. *************************************************************************
  56270. ** This file contains code associated with the ANALYZE command.
  56271. **
  56272. ** @(#) $Id: analyze.c,v 1.47 2008/12/10 16:45:51 drh Exp $
  56273. */
  56274. #ifndef SQLITE_OMIT_ANALYZE
  56275. /*
  56276. ** This routine generates code that opens the sqlite_stat1 table on cursor
  56277. ** iStatCur.
  56278. **
  56279. ** If the sqlite_stat1 tables does not previously exist, it is created.
  56280. ** If it does previously exist, all entires associated with table zWhere
  56281. ** are removed. If zWhere==0 then all entries are removed.
  56282. */
  56283. static void openStatTable(
  56284. Parse *pParse, /* Parsing context */
  56285. int iDb, /* The database we are looking in */
  56286. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  56287. const char *zWhere /* Delete entries associated with this table */
  56288. ){
  56289. sqlite3 *db = pParse->db;
  56290. Db *pDb;
  56291. int iRootPage;
  56292. u8 createStat1 = 0;
  56293. Table *pStat;
  56294. Vdbe *v = sqlite3GetVdbe(pParse);
  56295. if( v==0 ) return;
  56296. assert( sqlite3BtreeHoldsAllMutexes(db) );
  56297. assert( sqlite3VdbeDb(v)==db );
  56298. pDb = &db->aDb[iDb];
  56299. if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
  56300. /* The sqlite_stat1 tables does not exist. Create it.
  56301. ** Note that a side-effect of the CREATE TABLE statement is to leave
  56302. ** the rootpage of the new table in register pParse->regRoot. This is
  56303. ** important because the OpenWrite opcode below will be needing it. */
  56304. sqlite3NestedParse(pParse,
  56305. "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
  56306. pDb->zName
  56307. );
  56308. iRootPage = pParse->regRoot;
  56309. createStat1 = 1; /* Cause rootpage to be taken from top of stack */
  56310. }else if( zWhere ){
  56311. /* The sqlite_stat1 table exists. Delete all entries associated with
  56312. ** the table zWhere. */
  56313. sqlite3NestedParse(pParse,
  56314. "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
  56315. pDb->zName, zWhere
  56316. );
  56317. iRootPage = pStat->tnum;
  56318. }else{
  56319. /* The sqlite_stat1 table already exists. Delete all rows. */
  56320. iRootPage = pStat->tnum;
  56321. sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb);
  56322. }
  56323. /* Open the sqlite_stat1 table for writing. Unless it was created
  56324. ** by this vdbe program, lock it for writing at the shared-cache level.
  56325. ** If this vdbe did create the sqlite_stat1 table, then it must have
  56326. ** already obtained a schema-lock, making the write-lock redundant.
  56327. */
  56328. if( !createStat1 ){
  56329. sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
  56330. }
  56331. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 3);
  56332. sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb);
  56333. sqlite3VdbeChangeP5(v, createStat1);
  56334. }
  56335. /*
  56336. ** Generate code to do an analysis of all indices associated with
  56337. ** a single table.
  56338. */
  56339. static void analyzeOneTable(
  56340. Parse *pParse, /* Parser context */
  56341. Table *pTab, /* Table whose indices are to be analyzed */
  56342. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  56343. int iMem /* Available memory locations begin here */
  56344. ){
  56345. Index *pIdx; /* An index to being analyzed */
  56346. int iIdxCur; /* Index of VdbeCursor for index being analyzed */
  56347. int nCol; /* Number of columns in the index */
  56348. Vdbe *v; /* The virtual machine being built up */
  56349. int i; /* Loop counter */
  56350. int topOfLoop; /* The top of the loop */
  56351. int endOfLoop; /* The end of the loop */
  56352. int addr; /* The address of an instruction */
  56353. int iDb; /* Index of database containing pTab */
  56354. v = sqlite3GetVdbe(pParse);
  56355. if( v==0 || pTab==0 || pTab->pIndex==0 ){
  56356. /* Do no analysis for tables that have no indices */
  56357. return;
  56358. }
  56359. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  56360. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  56361. assert( iDb>=0 );
  56362. #ifndef SQLITE_OMIT_AUTHORIZATION
  56363. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  56364. pParse->db->aDb[iDb].zName ) ){
  56365. return;
  56366. }
  56367. #endif
  56368. /* Establish a read-lock on the table at the shared-cache level. */
  56369. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  56370. iIdxCur = pParse->nTab;
  56371. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  56372. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  56373. int regFields; /* Register block for building records */
  56374. int regRec; /* Register holding completed record */
  56375. int regTemp; /* Temporary use register */
  56376. int regCol; /* Content of a column from the table being analyzed */
  56377. int regRowid; /* Rowid for the inserted record */
  56378. int regF2;
  56379. /* Open a cursor to the index to be analyzed
  56380. */
  56381. assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
  56382. nCol = pIdx->nColumn;
  56383. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nCol+1);
  56384. sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
  56385. (char *)pKey, P4_KEYINFO_HANDOFF);
  56386. VdbeComment((v, "%s", pIdx->zName));
  56387. regFields = iMem+nCol*2;
  56388. regTemp = regRowid = regCol = regFields+3;
  56389. regRec = regCol+1;
  56390. if( regRec>pParse->nMem ){
  56391. pParse->nMem = regRec;
  56392. }
  56393. /* Memory cells are used as follows:
  56394. **
  56395. ** mem[iMem]: The total number of rows in the table.
  56396. ** mem[iMem+1]: Number of distinct values in column 1
  56397. ** ...
  56398. ** mem[iMem+nCol]: Number of distinct values in column N
  56399. ** mem[iMem+nCol+1] Last observed value of column 1
  56400. ** ...
  56401. ** mem[iMem+nCol+nCol]: Last observed value of column N
  56402. **
  56403. ** Cells iMem through iMem+nCol are initialized to 0. The others
  56404. ** are initialized to NULL.
  56405. */
  56406. for(i=0; i<=nCol; i++){
  56407. sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
  56408. }
  56409. for(i=0; i<nCol; i++){
  56410. sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
  56411. }
  56412. /* Do the analysis.
  56413. */
  56414. endOfLoop = sqlite3VdbeMakeLabel(v);
  56415. sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
  56416. topOfLoop = sqlite3VdbeCurrentAddr(v);
  56417. sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
  56418. for(i=0; i<nCol; i++){
  56419. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
  56420. sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
  56421. /**** TODO: add collating sequence *****/
  56422. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  56423. }
  56424. sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
  56425. for(i=0; i<nCol; i++){
  56426. sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1));
  56427. sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
  56428. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
  56429. }
  56430. sqlite3VdbeResolveLabel(v, endOfLoop);
  56431. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
  56432. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
  56433. /* Store the results.
  56434. **
  56435. ** The result is a single row of the sqlite_stat1 table. The first
  56436. ** two columns are the names of the table and index. The third column
  56437. ** is a string composed of a list of integer statistics about the
  56438. ** index. The first integer in the list is the total number of entires
  56439. ** in the index. There is one additional integer in the list for each
  56440. ** column of the table. This additional integer is a guess of how many
  56441. ** rows of the table the index will select. If D is the count of distinct
  56442. ** values and K is the total number of rows, then the integer is computed
  56443. ** as:
  56444. **
  56445. ** I = (K+D-1)/D
  56446. **
  56447. ** If K==0 then no entry is made into the sqlite_stat1 table.
  56448. ** If K>0 then it is always the case the D>0 so division by zero
  56449. ** is never possible.
  56450. */
  56451. addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
  56452. sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0);
  56453. sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0);
  56454. regF2 = regFields+2;
  56455. sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
  56456. for(i=0; i<nCol; i++){
  56457. sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
  56458. sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
  56459. sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
  56460. sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
  56461. sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
  56462. sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
  56463. sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
  56464. }
  56465. sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0);
  56466. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
  56467. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
  56468. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  56469. sqlite3VdbeJumpHere(v, addr);
  56470. }
  56471. }
  56472. /*
  56473. ** Generate code that will cause the most recent index analysis to
  56474. ** be laoded into internal hash tables where is can be used.
  56475. */
  56476. static void loadAnalysis(Parse *pParse, int iDb){
  56477. Vdbe *v = sqlite3GetVdbe(pParse);
  56478. if( v ){
  56479. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  56480. }
  56481. }
  56482. /*
  56483. ** Generate code that will do an analysis of an entire database
  56484. */
  56485. static void analyzeDatabase(Parse *pParse, int iDb){
  56486. sqlite3 *db = pParse->db;
  56487. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  56488. HashElem *k;
  56489. int iStatCur;
  56490. int iMem;
  56491. sqlite3BeginWriteOperation(pParse, 0, iDb);
  56492. iStatCur = pParse->nTab++;
  56493. openStatTable(pParse, iDb, iStatCur, 0);
  56494. iMem = pParse->nMem+1;
  56495. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  56496. Table *pTab = (Table*)sqliteHashData(k);
  56497. analyzeOneTable(pParse, pTab, iStatCur, iMem);
  56498. }
  56499. loadAnalysis(pParse, iDb);
  56500. }
  56501. /*
  56502. ** Generate code that will do an analysis of a single table in
  56503. ** a database.
  56504. */
  56505. static void analyzeTable(Parse *pParse, Table *pTab){
  56506. int iDb;
  56507. int iStatCur;
  56508. assert( pTab!=0 );
  56509. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  56510. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  56511. sqlite3BeginWriteOperation(pParse, 0, iDb);
  56512. iStatCur = pParse->nTab++;
  56513. openStatTable(pParse, iDb, iStatCur, pTab->zName);
  56514. analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
  56515. loadAnalysis(pParse, iDb);
  56516. }
  56517. /*
  56518. ** Generate code for the ANALYZE command. The parser calls this routine
  56519. ** when it recognizes an ANALYZE command.
  56520. **
  56521. ** ANALYZE -- 1
  56522. ** ANALYZE <database> -- 2
  56523. ** ANALYZE ?<database>.?<tablename> -- 3
  56524. **
  56525. ** Form 1 causes all indices in all attached databases to be analyzed.
  56526. ** Form 2 analyzes all indices the single database named.
  56527. ** Form 3 analyzes all indices associated with the named table.
  56528. */
  56529. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  56530. sqlite3 *db = pParse->db;
  56531. int iDb;
  56532. int i;
  56533. char *z, *zDb;
  56534. Table *pTab;
  56535. Token *pTableName;
  56536. /* Read the database schema. If an error occurs, leave an error message
  56537. ** and code in pParse and return NULL. */
  56538. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  56539. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  56540. return;
  56541. }
  56542. if( pName1==0 ){
  56543. /* Form 1: Analyze everything */
  56544. for(i=0; i<db->nDb; i++){
  56545. if( i==1 ) continue; /* Do not analyze the TEMP database */
  56546. analyzeDatabase(pParse, i);
  56547. }
  56548. }else if( pName2==0 || pName2->n==0 ){
  56549. /* Form 2: Analyze the database or table named */
  56550. iDb = sqlite3FindDb(db, pName1);
  56551. if( iDb>=0 ){
  56552. analyzeDatabase(pParse, iDb);
  56553. }else{
  56554. z = sqlite3NameFromToken(db, pName1);
  56555. if( z ){
  56556. pTab = sqlite3LocateTable(pParse, 0, z, 0);
  56557. sqlite3DbFree(db, z);
  56558. if( pTab ){
  56559. analyzeTable(pParse, pTab);
  56560. }
  56561. }
  56562. }
  56563. }else{
  56564. /* Form 3: Analyze the fully qualified table name */
  56565. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  56566. if( iDb>=0 ){
  56567. zDb = db->aDb[iDb].zName;
  56568. z = sqlite3NameFromToken(db, pTableName);
  56569. if( z ){
  56570. pTab = sqlite3LocateTable(pParse, 0, z, zDb);
  56571. sqlite3DbFree(db, z);
  56572. if( pTab ){
  56573. analyzeTable(pParse, pTab);
  56574. }
  56575. }
  56576. }
  56577. }
  56578. }
  56579. /*
  56580. ** Used to pass information from the analyzer reader through to the
  56581. ** callback routine.
  56582. */
  56583. typedef struct analysisInfo analysisInfo;
  56584. struct analysisInfo {
  56585. sqlite3 *db;
  56586. const char *zDatabase;
  56587. };
  56588. /*
  56589. ** This callback is invoked once for each index when reading the
  56590. ** sqlite_stat1 table.
  56591. **
  56592. ** argv[0] = name of the index
  56593. ** argv[1] = results of analysis - on integer for each column
  56594. */
  56595. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  56596. analysisInfo *pInfo = (analysisInfo*)pData;
  56597. Index *pIndex;
  56598. int i, c;
  56599. unsigned int v;
  56600. const char *z;
  56601. assert( argc==2 );
  56602. UNUSED_PARAMETER2(NotUsed, argc);
  56603. if( argv==0 || argv[0]==0 || argv[1]==0 ){
  56604. return 0;
  56605. }
  56606. pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
  56607. if( pIndex==0 ){
  56608. return 0;
  56609. }
  56610. z = argv[1];
  56611. for(i=0; *z && i<=pIndex->nColumn; i++){
  56612. v = 0;
  56613. while( (c=z[0])>='0' && c<='9' ){
  56614. v = v*10 + c - '0';
  56615. z++;
  56616. }
  56617. pIndex->aiRowEst[i] = v;
  56618. if( *z==' ' ) z++;
  56619. }
  56620. return 0;
  56621. }
  56622. /*
  56623. ** Load the content of the sqlite_stat1 table into the index hash tables.
  56624. */
  56625. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  56626. analysisInfo sInfo;
  56627. HashElem *i;
  56628. char *zSql;
  56629. int rc;
  56630. assert( iDb>=0 && iDb<db->nDb );
  56631. assert( db->aDb[iDb].pBt!=0 );
  56632. assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  56633. /* Clear any prior statistics */
  56634. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  56635. Index *pIdx = sqliteHashData(i);
  56636. sqlite3DefaultRowEst(pIdx);
  56637. }
  56638. /* Check to make sure the sqlite_stat1 table existss */
  56639. sInfo.db = db;
  56640. sInfo.zDatabase = db->aDb[iDb].zName;
  56641. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  56642. return SQLITE_ERROR;
  56643. }
  56644. /* Load new statistics out of the sqlite_stat1 table */
  56645. zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
  56646. sInfo.zDatabase);
  56647. (void)sqlite3SafetyOff(db);
  56648. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  56649. (void)sqlite3SafetyOn(db);
  56650. sqlite3DbFree(db, zSql);
  56651. return rc;
  56652. }
  56653. #endif /* SQLITE_OMIT_ANALYZE */
  56654. /************** End of analyze.c *********************************************/
  56655. /************** Begin file attach.c ******************************************/
  56656. /*
  56657. ** 2003 April 6
  56658. **
  56659. ** The author disclaims copyright to this source code. In place of
  56660. ** a legal notice, here is a blessing:
  56661. **
  56662. ** May you do good and not evil.
  56663. ** May you find forgiveness for yourself and forgive others.
  56664. ** May you share freely, never taking more than you give.
  56665. **
  56666. *************************************************************************
  56667. ** This file contains code used to implement the ATTACH and DETACH commands.
  56668. **
  56669. ** $Id: attach.c,v 1.81 2008/12/10 16:45:51 drh Exp $
  56670. */
  56671. #ifndef SQLITE_OMIT_ATTACH
  56672. /*
  56673. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  56674. ** is slightly different from resolving a normal SQL expression, because simple
  56675. ** identifiers are treated as strings, not possible column names or aliases.
  56676. **
  56677. ** i.e. if the parser sees:
  56678. **
  56679. ** ATTACH DATABASE abc AS def
  56680. **
  56681. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  56682. ** looking for columns of the same name.
  56683. **
  56684. ** This only applies to the root node of pExpr, so the statement:
  56685. **
  56686. ** ATTACH DATABASE abc||def AS 'db2'
  56687. **
  56688. ** will fail because neither abc or def can be resolved.
  56689. */
  56690. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  56691. {
  56692. int rc = SQLITE_OK;
  56693. if( pExpr ){
  56694. if( pExpr->op!=TK_ID ){
  56695. rc = sqlite3ResolveExprNames(pName, pExpr);
  56696. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  56697. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
  56698. return SQLITE_ERROR;
  56699. }
  56700. }else{
  56701. pExpr->op = TK_STRING;
  56702. }
  56703. }
  56704. return rc;
  56705. }
  56706. /*
  56707. ** An SQL user-function registered to do the work of an ATTACH statement. The
  56708. ** three arguments to the function come directly from an attach statement:
  56709. **
  56710. ** ATTACH DATABASE x AS y KEY z
  56711. **
  56712. ** SELECT sqlite_attach(x, y, z)
  56713. **
  56714. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  56715. ** third argument.
  56716. */
  56717. static void attachFunc(
  56718. sqlite3_context *context,
  56719. int NotUsed,
  56720. sqlite3_value **argv
  56721. ){
  56722. int i;
  56723. int rc = 0;
  56724. sqlite3 *db = sqlite3_context_db_handle(context);
  56725. const char *zName;
  56726. const char *zFile;
  56727. Db *aNew;
  56728. char *zErrDyn = 0;
  56729. char zErr[128];
  56730. UNUSED_PARAMETER(NotUsed);
  56731. zFile = (const char *)sqlite3_value_text(argv[0]);
  56732. zName = (const char *)sqlite3_value_text(argv[1]);
  56733. if( zFile==0 ) zFile = "";
  56734. if( zName==0 ) zName = "";
  56735. /* Check for the following errors:
  56736. **
  56737. ** * Too many attached databases,
  56738. ** * Transaction currently open
  56739. ** * Specified database name already being used.
  56740. */
  56741. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  56742. sqlite3_snprintf(
  56743. sizeof(zErr), zErr, "too many attached databases - max %d",
  56744. db->aLimit[SQLITE_LIMIT_ATTACHED]
  56745. );
  56746. goto attach_error;
  56747. }
  56748. if( !db->autoCommit ){
  56749. sqlite3_snprintf(sizeof(zErr), zErr,
  56750. "cannot ATTACH database within transaction");
  56751. goto attach_error;
  56752. }
  56753. for(i=0; i<db->nDb; i++){
  56754. char *z = db->aDb[i].zName;
  56755. if( z && zName && sqlite3StrICmp(z, zName)==0 ){
  56756. sqlite3_snprintf(sizeof(zErr), zErr,
  56757. "database %s is already in use", zName);
  56758. goto attach_error;
  56759. }
  56760. }
  56761. /* Allocate the new entry in the db->aDb[] array and initialise the schema
  56762. ** hash tables.
  56763. */
  56764. if( db->aDb==db->aDbStatic ){
  56765. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  56766. if( aNew==0 ) return;
  56767. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  56768. }else{
  56769. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  56770. if( aNew==0 ) return;
  56771. }
  56772. db->aDb = aNew;
  56773. aNew = &db->aDb[db->nDb++];
  56774. memset(aNew, 0, sizeof(*aNew));
  56775. /* Open the database file. If the btree is successfully opened, use
  56776. ** it to obtain the database schema. At this point the schema may
  56777. ** or may not be initialised.
  56778. */
  56779. rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
  56780. db->openFlags | SQLITE_OPEN_MAIN_DB,
  56781. &aNew->pBt);
  56782. if( rc==SQLITE_OK ){
  56783. Pager *pPager;
  56784. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  56785. if( !aNew->pSchema ){
  56786. rc = SQLITE_NOMEM;
  56787. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  56788. sqlite3_snprintf(sizeof(zErr), zErr,
  56789. "attached databases must use the same text encoding as main database");
  56790. goto attach_error;
  56791. }
  56792. pPager = sqlite3BtreePager(aNew->pBt);
  56793. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  56794. sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
  56795. }
  56796. aNew->zName = sqlite3DbStrDup(db, zName);
  56797. aNew->safety_level = 3;
  56798. #if SQLITE_HAS_CODEC
  56799. {
  56800. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  56801. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  56802. int nKey;
  56803. char *zKey;
  56804. int t = sqlite3_value_type(argv[2]);
  56805. switch( t ){
  56806. case SQLITE_INTEGER:
  56807. case SQLITE_FLOAT:
  56808. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  56809. rc = SQLITE_ERROR;
  56810. break;
  56811. case SQLITE_TEXT:
  56812. case SQLITE_BLOB:
  56813. nKey = sqlite3_value_bytes(argv[2]);
  56814. zKey = (char *)sqlite3_value_blob(argv[2]);
  56815. sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  56816. break;
  56817. case SQLITE_NULL:
  56818. /* No key specified. Use the key from the main database */
  56819. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  56820. sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  56821. break;
  56822. }
  56823. }
  56824. #endif
  56825. /* If the file was opened successfully, read the schema for the new database.
  56826. ** If this fails, or if opening the file failed, then close the file and
  56827. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  56828. ** we found it.
  56829. */
  56830. if( rc==SQLITE_OK ){
  56831. (void)sqlite3SafetyOn(db);
  56832. sqlite3BtreeEnterAll(db);
  56833. rc = sqlite3Init(db, &zErrDyn);
  56834. sqlite3BtreeLeaveAll(db);
  56835. (void)sqlite3SafetyOff(db);
  56836. }
  56837. if( rc ){
  56838. int iDb = db->nDb - 1;
  56839. assert( iDb>=2 );
  56840. if( db->aDb[iDb].pBt ){
  56841. sqlite3BtreeClose(db->aDb[iDb].pBt);
  56842. db->aDb[iDb].pBt = 0;
  56843. db->aDb[iDb].pSchema = 0;
  56844. }
  56845. sqlite3ResetInternalSchema(db, 0);
  56846. db->nDb = iDb;
  56847. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  56848. db->mallocFailed = 1;
  56849. sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
  56850. }else{
  56851. sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
  56852. }
  56853. goto attach_error;
  56854. }
  56855. return;
  56856. attach_error:
  56857. /* Return an error if we get here */
  56858. if( zErrDyn ){
  56859. sqlite3_result_error(context, zErrDyn, -1);
  56860. sqlite3DbFree(db, zErrDyn);
  56861. }else{
  56862. zErr[sizeof(zErr)-1] = 0;
  56863. sqlite3_result_error(context, zErr, -1);
  56864. }
  56865. if( rc ) sqlite3_result_error_code(context, rc);
  56866. }
  56867. /*
  56868. ** An SQL user-function registered to do the work of an DETACH statement. The
  56869. ** three arguments to the function come directly from a detach statement:
  56870. **
  56871. ** DETACH DATABASE x
  56872. **
  56873. ** SELECT sqlite_detach(x)
  56874. */
  56875. static void detachFunc(
  56876. sqlite3_context *context,
  56877. int NotUsed,
  56878. sqlite3_value **argv
  56879. ){
  56880. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  56881. sqlite3 *db = sqlite3_context_db_handle(context);
  56882. int i;
  56883. Db *pDb = 0;
  56884. char zErr[128];
  56885. UNUSED_PARAMETER(NotUsed);
  56886. if( zName==0 ) zName = "";
  56887. for(i=0; i<db->nDb; i++){
  56888. pDb = &db->aDb[i];
  56889. if( pDb->pBt==0 ) continue;
  56890. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  56891. }
  56892. if( i>=db->nDb ){
  56893. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  56894. goto detach_error;
  56895. }
  56896. if( i<2 ){
  56897. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  56898. goto detach_error;
  56899. }
  56900. if( !db->autoCommit ){
  56901. sqlite3_snprintf(sizeof(zErr), zErr,
  56902. "cannot DETACH database within transaction");
  56903. goto detach_error;
  56904. }
  56905. if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  56906. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  56907. goto detach_error;
  56908. }
  56909. sqlite3BtreeClose(pDb->pBt);
  56910. pDb->pBt = 0;
  56911. pDb->pSchema = 0;
  56912. sqlite3ResetInternalSchema(db, 0);
  56913. return;
  56914. detach_error:
  56915. sqlite3_result_error(context, zErr, -1);
  56916. }
  56917. /*
  56918. ** This procedure generates VDBE code for a single invocation of either the
  56919. ** sqlite_detach() or sqlite_attach() SQL user functions.
  56920. */
  56921. static void codeAttach(
  56922. Parse *pParse, /* The parser context */
  56923. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  56924. FuncDef *pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */
  56925. Expr *pAuthArg, /* Expression to pass to authorization callback */
  56926. Expr *pFilename, /* Name of database file */
  56927. Expr *pDbname, /* Name of the database to use internally */
  56928. Expr *pKey /* Database key for encryption extension */
  56929. ){
  56930. int rc;
  56931. NameContext sName;
  56932. Vdbe *v;
  56933. sqlite3* db = pParse->db;
  56934. int regArgs;
  56935. #ifndef SQLITE_OMIT_AUTHORIZATION
  56936. assert( db->mallocFailed || pAuthArg );
  56937. if( pAuthArg ){
  56938. char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
  56939. if( !zAuthArg ){
  56940. goto attach_end;
  56941. }
  56942. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  56943. sqlite3DbFree(db, zAuthArg);
  56944. if(rc!=SQLITE_OK ){
  56945. goto attach_end;
  56946. }
  56947. }
  56948. #endif /* SQLITE_OMIT_AUTHORIZATION */
  56949. memset(&sName, 0, sizeof(NameContext));
  56950. sName.pParse = pParse;
  56951. if(
  56952. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  56953. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  56954. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  56955. ){
  56956. pParse->nErr++;
  56957. goto attach_end;
  56958. }
  56959. v = sqlite3GetVdbe(pParse);
  56960. regArgs = sqlite3GetTempRange(pParse, 4);
  56961. sqlite3ExprCode(pParse, pFilename, regArgs);
  56962. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  56963. sqlite3ExprCode(pParse, pKey, regArgs+2);
  56964. assert( v || db->mallocFailed );
  56965. if( v ){
  56966. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  56967. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  56968. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  56969. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  56970. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  56971. ** statement only). For DETACH, set it to false (expire all existing
  56972. ** statements).
  56973. */
  56974. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  56975. }
  56976. attach_end:
  56977. sqlite3ExprDelete(db, pFilename);
  56978. sqlite3ExprDelete(db, pDbname);
  56979. sqlite3ExprDelete(db, pKey);
  56980. }
  56981. /*
  56982. ** Called by the parser to compile a DETACH statement.
  56983. **
  56984. ** DETACH pDbname
  56985. */
  56986. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  56987. static FuncDef detach_func = {
  56988. 1, /* nArg */
  56989. SQLITE_UTF8, /* iPrefEnc */
  56990. 0, /* flags */
  56991. 0, /* pUserData */
  56992. 0, /* pNext */
  56993. detachFunc, /* xFunc */
  56994. 0, /* xStep */
  56995. 0, /* xFinalize */
  56996. "sqlite_detach", /* zName */
  56997. 0 /* pHash */
  56998. };
  56999. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  57000. }
  57001. /*
  57002. ** Called by the parser to compile an ATTACH statement.
  57003. **
  57004. ** ATTACH p AS pDbname KEY pKey
  57005. */
  57006. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  57007. static FuncDef attach_func = {
  57008. 3, /* nArg */
  57009. SQLITE_UTF8, /* iPrefEnc */
  57010. 0, /* flags */
  57011. 0, /* pUserData */
  57012. 0, /* pNext */
  57013. attachFunc, /* xFunc */
  57014. 0, /* xStep */
  57015. 0, /* xFinalize */
  57016. "sqlite_attach", /* zName */
  57017. 0 /* pHash */
  57018. };
  57019. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  57020. }
  57021. #endif /* SQLITE_OMIT_ATTACH */
  57022. /*
  57023. ** Initialize a DbFixer structure. This routine must be called prior
  57024. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  57025. **
  57026. ** The return value indicates whether or not fixation is required. TRUE
  57027. ** means we do need to fix the database references, FALSE means we do not.
  57028. */
  57029. SQLITE_PRIVATE int sqlite3FixInit(
  57030. DbFixer *pFix, /* The fixer to be initialized */
  57031. Parse *pParse, /* Error messages will be written here */
  57032. int iDb, /* This is the database that must be used */
  57033. const char *zType, /* "view", "trigger", or "index" */
  57034. const Token *pName /* Name of the view, trigger, or index */
  57035. ){
  57036. sqlite3 *db;
  57037. if( iDb<0 || iDb==1 ) return 0;
  57038. db = pParse->db;
  57039. assert( db->nDb>iDb );
  57040. pFix->pParse = pParse;
  57041. pFix->zDb = db->aDb[iDb].zName;
  57042. pFix->zType = zType;
  57043. pFix->pName = pName;
  57044. return 1;
  57045. }
  57046. /*
  57047. ** The following set of routines walk through the parse tree and assign
  57048. ** a specific database to all table references where the database name
  57049. ** was left unspecified in the original SQL statement. The pFix structure
  57050. ** must have been initialized by a prior call to sqlite3FixInit().
  57051. **
  57052. ** These routines are used to make sure that an index, trigger, or
  57053. ** view in one database does not refer to objects in a different database.
  57054. ** (Exception: indices, triggers, and views in the TEMP database are
  57055. ** allowed to refer to anything.) If a reference is explicitly made
  57056. ** to an object in a different database, an error message is added to
  57057. ** pParse->zErrMsg and these routines return non-zero. If everything
  57058. ** checks out, these routines return 0.
  57059. */
  57060. SQLITE_PRIVATE int sqlite3FixSrcList(
  57061. DbFixer *pFix, /* Context of the fixation */
  57062. SrcList *pList /* The Source list to check and modify */
  57063. ){
  57064. int i;
  57065. const char *zDb;
  57066. struct SrcList_item *pItem;
  57067. if( pList==0 ) return 0;
  57068. zDb = pFix->zDb;
  57069. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  57070. if( pItem->zDatabase==0 ){
  57071. pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
  57072. }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
  57073. sqlite3ErrorMsg(pFix->pParse,
  57074. "%s %T cannot reference objects in database %s",
  57075. pFix->zType, pFix->pName, pItem->zDatabase);
  57076. return 1;
  57077. }
  57078. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  57079. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  57080. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  57081. #endif
  57082. }
  57083. return 0;
  57084. }
  57085. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  57086. SQLITE_PRIVATE int sqlite3FixSelect(
  57087. DbFixer *pFix, /* Context of the fixation */
  57088. Select *pSelect /* The SELECT statement to be fixed to one database */
  57089. ){
  57090. while( pSelect ){
  57091. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  57092. return 1;
  57093. }
  57094. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  57095. return 1;
  57096. }
  57097. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  57098. return 1;
  57099. }
  57100. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  57101. return 1;
  57102. }
  57103. pSelect = pSelect->pPrior;
  57104. }
  57105. return 0;
  57106. }
  57107. SQLITE_PRIVATE int sqlite3FixExpr(
  57108. DbFixer *pFix, /* Context of the fixation */
  57109. Expr *pExpr /* The expression to be fixed to one database */
  57110. ){
  57111. while( pExpr ){
  57112. if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
  57113. return 1;
  57114. }
  57115. if( sqlite3FixExprList(pFix, pExpr->pList) ){
  57116. return 1;
  57117. }
  57118. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  57119. return 1;
  57120. }
  57121. pExpr = pExpr->pLeft;
  57122. }
  57123. return 0;
  57124. }
  57125. SQLITE_PRIVATE int sqlite3FixExprList(
  57126. DbFixer *pFix, /* Context of the fixation */
  57127. ExprList *pList /* The expression to be fixed to one database */
  57128. ){
  57129. int i;
  57130. struct ExprList_item *pItem;
  57131. if( pList==0 ) return 0;
  57132. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  57133. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  57134. return 1;
  57135. }
  57136. }
  57137. return 0;
  57138. }
  57139. #endif
  57140. #ifndef SQLITE_OMIT_TRIGGER
  57141. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  57142. DbFixer *pFix, /* Context of the fixation */
  57143. TriggerStep *pStep /* The trigger step be fixed to one database */
  57144. ){
  57145. while( pStep ){
  57146. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  57147. return 1;
  57148. }
  57149. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  57150. return 1;
  57151. }
  57152. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  57153. return 1;
  57154. }
  57155. pStep = pStep->pNext;
  57156. }
  57157. return 0;
  57158. }
  57159. #endif
  57160. /************** End of attach.c **********************************************/
  57161. /************** Begin file auth.c ********************************************/
  57162. /*
  57163. ** 2003 January 11
  57164. **
  57165. ** The author disclaims copyright to this source code. In place of
  57166. ** a legal notice, here is a blessing:
  57167. **
  57168. ** May you do good and not evil.
  57169. ** May you find forgiveness for yourself and forgive others.
  57170. ** May you share freely, never taking more than you give.
  57171. **
  57172. *************************************************************************
  57173. ** This file contains code used to implement the sqlite3_set_authorizer()
  57174. ** API. This facility is an optional feature of the library. Embedded
  57175. ** systems that do not need this facility may omit it by recompiling
  57176. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  57177. **
  57178. ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
  57179. */
  57180. /*
  57181. ** All of the code in this file may be omitted by defining a single
  57182. ** macro.
  57183. */
  57184. #ifndef SQLITE_OMIT_AUTHORIZATION
  57185. /*
  57186. ** Set or clear the access authorization function.
  57187. **
  57188. ** The access authorization function is be called during the compilation
  57189. ** phase to verify that the user has read and/or write access permission on
  57190. ** various fields of the database. The first argument to the auth function
  57191. ** is a copy of the 3rd argument to this routine. The second argument
  57192. ** to the auth function is one of these constants:
  57193. **
  57194. ** SQLITE_CREATE_INDEX
  57195. ** SQLITE_CREATE_TABLE
  57196. ** SQLITE_CREATE_TEMP_INDEX
  57197. ** SQLITE_CREATE_TEMP_TABLE
  57198. ** SQLITE_CREATE_TEMP_TRIGGER
  57199. ** SQLITE_CREATE_TEMP_VIEW
  57200. ** SQLITE_CREATE_TRIGGER
  57201. ** SQLITE_CREATE_VIEW
  57202. ** SQLITE_DELETE
  57203. ** SQLITE_DROP_INDEX
  57204. ** SQLITE_DROP_TABLE
  57205. ** SQLITE_DROP_TEMP_INDEX
  57206. ** SQLITE_DROP_TEMP_TABLE
  57207. ** SQLITE_DROP_TEMP_TRIGGER
  57208. ** SQLITE_DROP_TEMP_VIEW
  57209. ** SQLITE_DROP_TRIGGER
  57210. ** SQLITE_DROP_VIEW
  57211. ** SQLITE_INSERT
  57212. ** SQLITE_PRAGMA
  57213. ** SQLITE_READ
  57214. ** SQLITE_SELECT
  57215. ** SQLITE_TRANSACTION
  57216. ** SQLITE_UPDATE
  57217. **
  57218. ** The third and fourth arguments to the auth function are the name of
  57219. ** the table and the column that are being accessed. The auth function
  57220. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  57221. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  57222. ** means that the SQL statement will never-run - the sqlite3_exec() call
  57223. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  57224. ** should run but attempts to read the specified column will return NULL
  57225. ** and attempts to write the column will be ignored.
  57226. **
  57227. ** Setting the auth function to NULL disables this hook. The default
  57228. ** setting of the auth function is NULL.
  57229. */
  57230. SQLITE_API int sqlite3_set_authorizer(
  57231. sqlite3 *db,
  57232. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  57233. void *pArg
  57234. ){
  57235. sqlite3_mutex_enter(db->mutex);
  57236. db->xAuth = xAuth;
  57237. db->pAuthArg = pArg;
  57238. sqlite3ExpirePreparedStatements(db);
  57239. sqlite3_mutex_leave(db->mutex);
  57240. return SQLITE_OK;
  57241. }
  57242. /*
  57243. ** Write an error message into pParse->zErrMsg that explains that the
  57244. ** user-supplied authorization function returned an illegal value.
  57245. */
  57246. static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
  57247. sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
  57248. "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
  57249. "or SQLITE_DENY", rc);
  57250. pParse->rc = SQLITE_ERROR;
  57251. }
  57252. /*
  57253. ** The pExpr should be a TK_COLUMN expression. The table referred to
  57254. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  57255. ** Check to see if it is OK to read this particular column.
  57256. **
  57257. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  57258. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  57259. ** then generate an error.
  57260. */
  57261. SQLITE_PRIVATE void sqlite3AuthRead(
  57262. Parse *pParse, /* The parser context */
  57263. Expr *pExpr, /* The expression to check authorization on */
  57264. Schema *pSchema, /* The schema of the expression */
  57265. SrcList *pTabList /* All table that pExpr might refer to */
  57266. ){
  57267. sqlite3 *db = pParse->db;
  57268. int rc;
  57269. Table *pTab = 0; /* The table being read */
  57270. const char *zCol; /* Name of the column of the table */
  57271. int iSrc; /* Index in pTabList->a[] of table being read */
  57272. const char *zDBase; /* Name of database being accessed */
  57273. TriggerStack *pStack; /* The stack of current triggers */
  57274. int iDb; /* The index of the database the expression refers to */
  57275. if( db->xAuth==0 ) return;
  57276. if( pExpr->op!=TK_COLUMN ) return;
  57277. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  57278. if( iDb<0 ){
  57279. /* An attempt to read a column out of a subquery or other
  57280. ** temporary table. */
  57281. return;
  57282. }
  57283. for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
  57284. if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
  57285. }
  57286. if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
  57287. pTab = pTabList->a[iSrc].pTab;
  57288. }else if( (pStack = pParse->trigStack)!=0 ){
  57289. /* This must be an attempt to read the NEW or OLD pseudo-tables
  57290. ** of a trigger.
  57291. */
  57292. assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
  57293. pTab = pStack->pTab;
  57294. }
  57295. if( pTab==0 ) return;
  57296. if( pExpr->iColumn>=0 ){
  57297. assert( pExpr->iColumn<pTab->nCol );
  57298. zCol = pTab->aCol[pExpr->iColumn].zName;
  57299. }else if( pTab->iPKey>=0 ){
  57300. assert( pTab->iPKey<pTab->nCol );
  57301. zCol = pTab->aCol[pTab->iPKey].zName;
  57302. }else{
  57303. zCol = "ROWID";
  57304. }
  57305. assert( iDb>=0 && iDb<db->nDb );
  57306. zDBase = db->aDb[iDb].zName;
  57307. rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase,
  57308. pParse->zAuthContext);
  57309. if( rc==SQLITE_IGNORE ){
  57310. pExpr->op = TK_NULL;
  57311. }else if( rc==SQLITE_DENY ){
  57312. if( db->nDb>2 || iDb!=0 ){
  57313. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",
  57314. zDBase, pTab->zName, zCol);
  57315. }else{
  57316. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
  57317. }
  57318. pParse->rc = SQLITE_AUTH;
  57319. }else if( rc!=SQLITE_OK ){
  57320. sqliteAuthBadReturnCode(pParse, rc);
  57321. }
  57322. }
  57323. /*
  57324. ** Do an authorization check using the code and arguments given. Return
  57325. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  57326. ** is returned, then the error count and error message in pParse are
  57327. ** modified appropriately.
  57328. */
  57329. SQLITE_PRIVATE int sqlite3AuthCheck(
  57330. Parse *pParse,
  57331. int code,
  57332. const char *zArg1,
  57333. const char *zArg2,
  57334. const char *zArg3
  57335. ){
  57336. sqlite3 *db = pParse->db;
  57337. int rc;
  57338. /* Don't do any authorization checks if the database is initialising
  57339. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  57340. */
  57341. if( db->init.busy || IN_DECLARE_VTAB ){
  57342. return SQLITE_OK;
  57343. }
  57344. if( db->xAuth==0 ){
  57345. return SQLITE_OK;
  57346. }
  57347. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  57348. if( rc==SQLITE_DENY ){
  57349. sqlite3ErrorMsg(pParse, "not authorized");
  57350. pParse->rc = SQLITE_AUTH;
  57351. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  57352. rc = SQLITE_DENY;
  57353. sqliteAuthBadReturnCode(pParse, rc);
  57354. }
  57355. return rc;
  57356. }
  57357. /*
  57358. ** Push an authorization context. After this routine is called, the
  57359. ** zArg3 argument to authorization callbacks will be zContext until
  57360. ** popped. Or if pParse==0, this routine is a no-op.
  57361. */
  57362. SQLITE_PRIVATE void sqlite3AuthContextPush(
  57363. Parse *pParse,
  57364. AuthContext *pContext,
  57365. const char *zContext
  57366. ){
  57367. pContext->pParse = pParse;
  57368. if( pParse ){
  57369. pContext->zAuthContext = pParse->zAuthContext;
  57370. pParse->zAuthContext = zContext;
  57371. }
  57372. }
  57373. /*
  57374. ** Pop an authorization context that was previously pushed
  57375. ** by sqlite3AuthContextPush
  57376. */
  57377. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  57378. if( pContext->pParse ){
  57379. pContext->pParse->zAuthContext = pContext->zAuthContext;
  57380. pContext->pParse = 0;
  57381. }
  57382. }
  57383. #endif /* SQLITE_OMIT_AUTHORIZATION */
  57384. /************** End of auth.c ************************************************/
  57385. /************** Begin file build.c *******************************************/
  57386. /*
  57387. ** 2001 September 15
  57388. **
  57389. ** The author disclaims copyright to this source code. In place of
  57390. ** a legal notice, here is a blessing:
  57391. **
  57392. ** May you do good and not evil.
  57393. ** May you find forgiveness for yourself and forgive others.
  57394. ** May you share freely, never taking more than you give.
  57395. **
  57396. *************************************************************************
  57397. ** This file contains C code routines that are called by the SQLite parser
  57398. ** when syntax rules are reduced. The routines in this file handle the
  57399. ** following kinds of SQL syntax:
  57400. **
  57401. ** CREATE TABLE
  57402. ** DROP TABLE
  57403. ** CREATE INDEX
  57404. ** DROP INDEX
  57405. ** creating ID lists
  57406. ** BEGIN TRANSACTION
  57407. ** COMMIT
  57408. ** ROLLBACK
  57409. **
  57410. ** $Id: build.c,v 1.511 2008/12/30 06:24:58 danielk1977 Exp $
  57411. */
  57412. /*
  57413. ** This routine is called when a new SQL statement is beginning to
  57414. ** be parsed. Initialize the pParse structure as needed.
  57415. */
  57416. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  57417. pParse->explain = (u8)explainFlag;
  57418. pParse->nVar = 0;
  57419. }
  57420. #ifndef SQLITE_OMIT_SHARED_CACHE
  57421. /*
  57422. ** The TableLock structure is only used by the sqlite3TableLock() and
  57423. ** codeTableLocks() functions.
  57424. */
  57425. struct TableLock {
  57426. int iDb; /* The database containing the table to be locked */
  57427. int iTab; /* The root page of the table to be locked */
  57428. u8 isWriteLock; /* True for write lock. False for a read lock */
  57429. const char *zName; /* Name of the table */
  57430. };
  57431. /*
  57432. ** Record the fact that we want to lock a table at run-time.
  57433. **
  57434. ** The table to be locked has root page iTab and is found in database iDb.
  57435. ** A read or a write lock can be taken depending on isWritelock.
  57436. **
  57437. ** This routine just records the fact that the lock is desired. The
  57438. ** code to make the lock occur is generated by a later call to
  57439. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  57440. */
  57441. SQLITE_PRIVATE void sqlite3TableLock(
  57442. Parse *pParse, /* Parsing context */
  57443. int iDb, /* Index of the database containing the table to lock */
  57444. int iTab, /* Root page number of the table to be locked */
  57445. u8 isWriteLock, /* True for a write lock */
  57446. const char *zName /* Name of the table to be locked */
  57447. ){
  57448. int i;
  57449. int nBytes;
  57450. TableLock *p;
  57451. if( iDb<0 ){
  57452. return;
  57453. }
  57454. for(i=0; i<pParse->nTableLock; i++){
  57455. p = &pParse->aTableLock[i];
  57456. if( p->iDb==iDb && p->iTab==iTab ){
  57457. p->isWriteLock = (p->isWriteLock || isWriteLock);
  57458. return;
  57459. }
  57460. }
  57461. nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
  57462. pParse->aTableLock =
  57463. sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
  57464. if( pParse->aTableLock ){
  57465. p = &pParse->aTableLock[pParse->nTableLock++];
  57466. p->iDb = iDb;
  57467. p->iTab = iTab;
  57468. p->isWriteLock = isWriteLock;
  57469. p->zName = zName;
  57470. }else{
  57471. pParse->nTableLock = 0;
  57472. pParse->db->mallocFailed = 1;
  57473. }
  57474. }
  57475. /*
  57476. ** Code an OP_TableLock instruction for each table locked by the
  57477. ** statement (configured by calls to sqlite3TableLock()).
  57478. */
  57479. static void codeTableLocks(Parse *pParse){
  57480. int i;
  57481. Vdbe *pVdbe;
  57482. if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
  57483. return;
  57484. }
  57485. for(i=0; i<pParse->nTableLock; i++){
  57486. TableLock *p = &pParse->aTableLock[i];
  57487. int p1 = p->iDb;
  57488. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  57489. p->zName, P4_STATIC);
  57490. }
  57491. }
  57492. #else
  57493. #define codeTableLocks(x)
  57494. #endif
  57495. /*
  57496. ** This routine is called after a single SQL statement has been
  57497. ** parsed and a VDBE program to execute that statement has been
  57498. ** prepared. This routine puts the finishing touches on the
  57499. ** VDBE program and resets the pParse structure for the next
  57500. ** parse.
  57501. **
  57502. ** Note that if an error occurred, it might be the case that
  57503. ** no VDBE code was generated.
  57504. */
  57505. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  57506. sqlite3 *db;
  57507. Vdbe *v;
  57508. db = pParse->db;
  57509. if( db->mallocFailed ) return;
  57510. if( pParse->nested ) return;
  57511. if( pParse->nErr ) return;
  57512. /* Begin by generating some termination code at the end of the
  57513. ** vdbe program
  57514. */
  57515. v = sqlite3GetVdbe(pParse);
  57516. if( v ){
  57517. sqlite3VdbeAddOp0(v, OP_Halt);
  57518. /* The cookie mask contains one bit for each database file open.
  57519. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  57520. ** set for each database that is used. Generate code to start a
  57521. ** transaction on each used database and to verify the schema cookie
  57522. ** on each used database.
  57523. */
  57524. if( pParse->cookieGoto>0 ){
  57525. u32 mask;
  57526. int iDb;
  57527. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  57528. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  57529. if( (mask & pParse->cookieMask)==0 ) continue;
  57530. sqlite3VdbeUsesBtree(v, iDb);
  57531. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  57532. sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
  57533. }
  57534. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57535. {
  57536. int i;
  57537. for(i=0; i<pParse->nVtabLock; i++){
  57538. char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
  57539. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  57540. }
  57541. pParse->nVtabLock = 0;
  57542. }
  57543. #endif
  57544. /* Once all the cookies have been verified and transactions opened,
  57545. ** obtain the required table-locks. This is a no-op unless the
  57546. ** shared-cache feature is enabled.
  57547. */
  57548. codeTableLocks(pParse);
  57549. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  57550. }
  57551. #ifndef SQLITE_OMIT_TRACE
  57552. if( !db->init.busy ){
  57553. /* Change the P4 argument of the first opcode (which will always be
  57554. ** an OP_Trace) to be the complete text of the current SQL statement.
  57555. */
  57556. VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
  57557. if( pOp && pOp->opcode==OP_Trace ){
  57558. sqlite3VdbeChangeP4(v, 0, pParse->zSql,
  57559. (int)(pParse->zTail - pParse->zSql));
  57560. }
  57561. }
  57562. #endif /* SQLITE_OMIT_TRACE */
  57563. }
  57564. /* Get the VDBE program ready for execution
  57565. */
  57566. if( v && pParse->nErr==0 && !db->mallocFailed ){
  57567. #ifdef SQLITE_DEBUG
  57568. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  57569. sqlite3VdbeTrace(v, trace);
  57570. #endif
  57571. assert( pParse->disableColCache==0 ); /* Disables and re-enables match */
  57572. sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
  57573. pParse->nTab+3, pParse->explain);
  57574. pParse->rc = SQLITE_DONE;
  57575. pParse->colNamesSet = 0;
  57576. }else if( pParse->rc==SQLITE_OK ){
  57577. pParse->rc = SQLITE_ERROR;
  57578. }
  57579. pParse->nTab = 0;
  57580. pParse->nMem = 0;
  57581. pParse->nSet = 0;
  57582. pParse->nVar = 0;
  57583. pParse->cookieMask = 0;
  57584. pParse->cookieGoto = 0;
  57585. }
  57586. /*
  57587. ** Run the parser and code generator recursively in order to generate
  57588. ** code for the SQL statement given onto the end of the pParse context
  57589. ** currently under construction. When the parser is run recursively
  57590. ** this way, the final OP_Halt is not appended and other initialization
  57591. ** and finalization steps are omitted because those are handling by the
  57592. ** outermost parser.
  57593. **
  57594. ** Not everything is nestable. This facility is designed to permit
  57595. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  57596. ** care if you decide to try to use this routine for some other purposes.
  57597. */
  57598. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  57599. va_list ap;
  57600. char *zSql;
  57601. char *zErrMsg = 0;
  57602. sqlite3 *db = pParse->db;
  57603. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  57604. char saveBuf[SAVE_SZ];
  57605. if( pParse->nErr ) return;
  57606. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  57607. va_start(ap, zFormat);
  57608. zSql = sqlite3VMPrintf(db, zFormat, ap);
  57609. va_end(ap);
  57610. if( zSql==0 ){
  57611. return; /* A malloc must have failed */
  57612. }
  57613. pParse->nested++;
  57614. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  57615. memset(&pParse->nVar, 0, SAVE_SZ);
  57616. sqlite3RunParser(pParse, zSql, &zErrMsg);
  57617. sqlite3DbFree(db, zErrMsg);
  57618. sqlite3DbFree(db, zSql);
  57619. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  57620. pParse->nested--;
  57621. }
  57622. /*
  57623. ** Locate the in-memory structure that describes a particular database
  57624. ** table given the name of that table and (optionally) the name of the
  57625. ** database containing the table. Return NULL if not found.
  57626. **
  57627. ** If zDatabase is 0, all databases are searched for the table and the
  57628. ** first matching table is returned. (No checking for duplicate table
  57629. ** names is done.) The search order is TEMP first, then MAIN, then any
  57630. ** auxiliary databases added using the ATTACH command.
  57631. **
  57632. ** See also sqlite3LocateTable().
  57633. */
  57634. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  57635. Table *p = 0;
  57636. int i;
  57637. int nName;
  57638. assert( zName!=0 );
  57639. nName = sqlite3Strlen(db, zName) + 1;
  57640. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  57641. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  57642. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  57643. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  57644. if( p ) break;
  57645. }
  57646. return p;
  57647. }
  57648. /*
  57649. ** Locate the in-memory structure that describes a particular database
  57650. ** table given the name of that table and (optionally) the name of the
  57651. ** database containing the table. Return NULL if not found. Also leave an
  57652. ** error message in pParse->zErrMsg.
  57653. **
  57654. ** The difference between this routine and sqlite3FindTable() is that this
  57655. ** routine leaves an error message in pParse->zErrMsg where
  57656. ** sqlite3FindTable() does not.
  57657. */
  57658. SQLITE_PRIVATE Table *sqlite3LocateTable(
  57659. Parse *pParse, /* context in which to report errors */
  57660. int isView, /* True if looking for a VIEW rather than a TABLE */
  57661. const char *zName, /* Name of the table we are looking for */
  57662. const char *zDbase /* Name of the database. Might be NULL */
  57663. ){
  57664. Table *p;
  57665. /* Read the database schema. If an error occurs, leave an error message
  57666. ** and code in pParse and return NULL. */
  57667. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  57668. return 0;
  57669. }
  57670. p = sqlite3FindTable(pParse->db, zName, zDbase);
  57671. if( p==0 ){
  57672. const char *zMsg = isView ? "no such view" : "no such table";
  57673. if( zDbase ){
  57674. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  57675. }else{
  57676. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  57677. }
  57678. pParse->checkSchema = 1;
  57679. }
  57680. return p;
  57681. }
  57682. /*
  57683. ** Locate the in-memory structure that describes
  57684. ** a particular index given the name of that index
  57685. ** and the name of the database that contains the index.
  57686. ** Return NULL if not found.
  57687. **
  57688. ** If zDatabase is 0, all databases are searched for the
  57689. ** table and the first matching index is returned. (No checking
  57690. ** for duplicate index names is done.) The search order is
  57691. ** TEMP first, then MAIN, then any auxiliary databases added
  57692. ** using the ATTACH command.
  57693. */
  57694. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  57695. Index *p = 0;
  57696. int i;
  57697. int nName = sqlite3Strlen(db, zName)+1;
  57698. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  57699. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  57700. Schema *pSchema = db->aDb[j].pSchema;
  57701. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  57702. assert( pSchema || (j==1 && !db->aDb[1].pBt) );
  57703. if( pSchema ){
  57704. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  57705. }
  57706. if( p ) break;
  57707. }
  57708. return p;
  57709. }
  57710. /*
  57711. ** Reclaim the memory used by an index
  57712. */
  57713. static void freeIndex(Index *p){
  57714. sqlite3 *db = p->pTable->db;
  57715. sqlite3DbFree(db, p->zColAff);
  57716. sqlite3DbFree(db, p);
  57717. }
  57718. /*
  57719. ** Remove the given index from the index hash table, and free
  57720. ** its memory structures.
  57721. **
  57722. ** The index is removed from the database hash tables but
  57723. ** it is not unlinked from the Table that it indexes.
  57724. ** Unlinking from the Table must be done by the calling function.
  57725. */
  57726. static void sqliteDeleteIndex(Index *p){
  57727. Index *pOld;
  57728. const char *zName = p->zName;
  57729. pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
  57730. sqlite3Strlen30(zName)+1, 0);
  57731. assert( pOld==0 || pOld==p );
  57732. freeIndex(p);
  57733. }
  57734. /*
  57735. ** For the index called zIdxName which is found in the database iDb,
  57736. ** unlike that index from its Table then remove the index from
  57737. ** the index hash table and free all memory structures associated
  57738. ** with the index.
  57739. */
  57740. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  57741. Index *pIndex;
  57742. int len;
  57743. Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
  57744. len = sqlite3Strlen(db, zIdxName);
  57745. pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
  57746. if( pIndex ){
  57747. if( pIndex->pTable->pIndex==pIndex ){
  57748. pIndex->pTable->pIndex = pIndex->pNext;
  57749. }else{
  57750. Index *p;
  57751. for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
  57752. if( p && p->pNext==pIndex ){
  57753. p->pNext = pIndex->pNext;
  57754. }
  57755. }
  57756. freeIndex(pIndex);
  57757. }
  57758. db->flags |= SQLITE_InternChanges;
  57759. }
  57760. /*
  57761. ** Erase all schema information from the in-memory hash tables of
  57762. ** a single database. This routine is called to reclaim memory
  57763. ** before the database closes. It is also called during a rollback
  57764. ** if there were schema changes during the transaction or if a
  57765. ** schema-cookie mismatch occurs.
  57766. **
  57767. ** If iDb<=0 then reset the internal schema tables for all database
  57768. ** files. If iDb>=2 then reset the internal schema for only the
  57769. ** single file indicated.
  57770. */
  57771. SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
  57772. int i, j;
  57773. assert( iDb>=0 && iDb<db->nDb );
  57774. if( iDb==0 ){
  57775. sqlite3BtreeEnterAll(db);
  57776. }
  57777. for(i=iDb; i<db->nDb; i++){
  57778. Db *pDb = &db->aDb[i];
  57779. if( pDb->pSchema ){
  57780. assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
  57781. sqlite3SchemaFree(pDb->pSchema);
  57782. }
  57783. if( iDb>0 ) return;
  57784. }
  57785. assert( iDb==0 );
  57786. db->flags &= ~SQLITE_InternChanges;
  57787. sqlite3BtreeLeaveAll(db);
  57788. /* If one or more of the auxiliary database files has been closed,
  57789. ** then remove them from the auxiliary database list. We take the
  57790. ** opportunity to do this here since we have just deleted all of the
  57791. ** schema hash tables and therefore do not have to make any changes
  57792. ** to any of those tables.
  57793. */
  57794. for(i=0; i<db->nDb; i++){
  57795. struct Db *pDb = &db->aDb[i];
  57796. if( pDb->pBt==0 ){
  57797. if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
  57798. pDb->pAux = 0;
  57799. }
  57800. }
  57801. for(i=j=2; i<db->nDb; i++){
  57802. struct Db *pDb = &db->aDb[i];
  57803. if( pDb->pBt==0 ){
  57804. sqlite3DbFree(db, pDb->zName);
  57805. pDb->zName = 0;
  57806. continue;
  57807. }
  57808. if( j<i ){
  57809. db->aDb[j] = db->aDb[i];
  57810. }
  57811. j++;
  57812. }
  57813. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  57814. db->nDb = j;
  57815. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  57816. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  57817. sqlite3DbFree(db, db->aDb);
  57818. db->aDb = db->aDbStatic;
  57819. }
  57820. }
  57821. /*
  57822. ** This routine is called when a commit occurs.
  57823. */
  57824. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  57825. db->flags &= ~SQLITE_InternChanges;
  57826. }
  57827. /*
  57828. ** Clear the column names from a table or view.
  57829. */
  57830. static void sqliteResetColumnNames(Table *pTable){
  57831. int i;
  57832. Column *pCol;
  57833. sqlite3 *db = pTable->db;
  57834. assert( pTable!=0 );
  57835. if( (pCol = pTable->aCol)!=0 ){
  57836. for(i=0; i<pTable->nCol; i++, pCol++){
  57837. sqlite3DbFree(db, pCol->zName);
  57838. sqlite3ExprDelete(db, pCol->pDflt);
  57839. sqlite3DbFree(db, pCol->zType);
  57840. sqlite3DbFree(db, pCol->zColl);
  57841. }
  57842. sqlite3DbFree(db, pTable->aCol);
  57843. }
  57844. pTable->aCol = 0;
  57845. pTable->nCol = 0;
  57846. }
  57847. /*
  57848. ** Remove the memory data structures associated with the given
  57849. ** Table. No changes are made to disk by this routine.
  57850. **
  57851. ** This routine just deletes the data structure. It does not unlink
  57852. ** the table data structure from the hash table. Nor does it remove
  57853. ** foreign keys from the sqlite.aFKey hash table. But it does destroy
  57854. ** memory structures of the indices and foreign keys associated with
  57855. ** the table.
  57856. */
  57857. SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
  57858. Index *pIndex, *pNext;
  57859. FKey *pFKey, *pNextFKey;
  57860. sqlite3 *db;
  57861. if( pTable==0 ) return;
  57862. db = pTable->db;
  57863. /* Do not delete the table until the reference count reaches zero. */
  57864. pTable->nRef--;
  57865. if( pTable->nRef>0 ){
  57866. return;
  57867. }
  57868. assert( pTable->nRef==0 );
  57869. /* Delete all indices associated with this table
  57870. */
  57871. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  57872. pNext = pIndex->pNext;
  57873. assert( pIndex->pSchema==pTable->pSchema );
  57874. sqliteDeleteIndex(pIndex);
  57875. }
  57876. #ifndef SQLITE_OMIT_FOREIGN_KEY
  57877. /* Delete all foreign keys associated with this table. The keys
  57878. ** should have already been unlinked from the pSchema->aFKey hash table
  57879. */
  57880. for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
  57881. pNextFKey = pFKey->pNextFrom;
  57882. assert( sqlite3HashFind(&pTable->pSchema->aFKey,
  57883. pFKey->zTo, sqlite3Strlen30(pFKey->zTo)+1)!=pFKey );
  57884. sqlite3DbFree(db, pFKey);
  57885. }
  57886. #endif
  57887. /* Delete the Table structure itself.
  57888. */
  57889. sqliteResetColumnNames(pTable);
  57890. sqlite3DbFree(db, pTable->zName);
  57891. sqlite3DbFree(db, pTable->zColAff);
  57892. sqlite3SelectDelete(db, pTable->pSelect);
  57893. #ifndef SQLITE_OMIT_CHECK
  57894. sqlite3ExprDelete(db, pTable->pCheck);
  57895. #endif
  57896. sqlite3VtabClear(pTable);
  57897. sqlite3DbFree(db, pTable);
  57898. }
  57899. /*
  57900. ** Unlink the given table from the hash tables and the delete the
  57901. ** table structure with all its indices and foreign keys.
  57902. */
  57903. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  57904. Table *p;
  57905. FKey *pF1, *pF2;
  57906. Db *pDb;
  57907. assert( db!=0 );
  57908. assert( iDb>=0 && iDb<db->nDb );
  57909. assert( zTabName && zTabName[0] );
  57910. pDb = &db->aDb[iDb];
  57911. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  57912. sqlite3Strlen30(zTabName)+1,0);
  57913. if( p ){
  57914. #ifndef SQLITE_OMIT_FOREIGN_KEY
  57915. for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
  57916. int nTo = sqlite3Strlen30(pF1->zTo) + 1;
  57917. pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
  57918. if( pF2==pF1 ){
  57919. sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
  57920. }else{
  57921. while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
  57922. if( pF2 ){
  57923. pF2->pNextTo = pF1->pNextTo;
  57924. }
  57925. }
  57926. }
  57927. #endif
  57928. sqlite3DeleteTable(p);
  57929. }
  57930. db->flags |= SQLITE_InternChanges;
  57931. }
  57932. /*
  57933. ** Given a token, return a string that consists of the text of that
  57934. ** token with any quotations removed. Space to hold the returned string
  57935. ** is obtained from sqliteMalloc() and must be freed by the calling
  57936. ** function.
  57937. **
  57938. ** Tokens are often just pointers into the original SQL text and so
  57939. ** are not \000 terminated and are not persistent. The returned string
  57940. ** is \000 terminated and is persistent.
  57941. */
  57942. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  57943. char *zName;
  57944. if( pName ){
  57945. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  57946. sqlite3Dequote(zName);
  57947. }else{
  57948. zName = 0;
  57949. }
  57950. return zName;
  57951. }
  57952. /*
  57953. ** Open the sqlite_master table stored in database number iDb for
  57954. ** writing. The table is opened using cursor 0.
  57955. */
  57956. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  57957. Vdbe *v = sqlite3GetVdbe(p);
  57958. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  57959. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
  57960. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  57961. }
  57962. /*
  57963. ** The token *pName contains the name of a database (either "main" or
  57964. ** "temp" or the name of an attached db). This routine returns the
  57965. ** index of the named database in db->aDb[], or -1 if the named db
  57966. ** does not exist.
  57967. */
  57968. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  57969. int i = -1; /* Database number */
  57970. int n; /* Number of characters in the name */
  57971. Db *pDb; /* A database whose name space is being searched */
  57972. char *zName; /* Name we are searching for */
  57973. zName = sqlite3NameFromToken(db, pName);
  57974. if( zName ){
  57975. n = sqlite3Strlen30(zName);
  57976. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  57977. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  57978. 0==sqlite3StrICmp(pDb->zName, zName) ){
  57979. break;
  57980. }
  57981. }
  57982. sqlite3DbFree(db, zName);
  57983. }
  57984. return i;
  57985. }
  57986. /* The table or view or trigger name is passed to this routine via tokens
  57987. ** pName1 and pName2. If the table name was fully qualified, for example:
  57988. **
  57989. ** CREATE TABLE xxx.yyy (...);
  57990. **
  57991. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  57992. ** the table name is not fully qualified, i.e.:
  57993. **
  57994. ** CREATE TABLE yyy(...);
  57995. **
  57996. ** Then pName1 is set to "yyy" and pName2 is "".
  57997. **
  57998. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  57999. ** pName2) that stores the unqualified table name. The index of the
  58000. ** database "xxx" is returned.
  58001. */
  58002. SQLITE_PRIVATE int sqlite3TwoPartName(
  58003. Parse *pParse, /* Parsing and code generating context */
  58004. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  58005. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  58006. Token **pUnqual /* Write the unqualified object name here */
  58007. ){
  58008. int iDb; /* Database holding the object */
  58009. sqlite3 *db = pParse->db;
  58010. if( pName2 && pName2->n>0 ){
  58011. if( db->init.busy ) {
  58012. sqlite3ErrorMsg(pParse, "corrupt database");
  58013. pParse->nErr++;
  58014. return -1;
  58015. }
  58016. *pUnqual = pName2;
  58017. iDb = sqlite3FindDb(db, pName1);
  58018. if( iDb<0 ){
  58019. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  58020. pParse->nErr++;
  58021. return -1;
  58022. }
  58023. }else{
  58024. assert( db->init.iDb==0 || db->init.busy );
  58025. iDb = db->init.iDb;
  58026. *pUnqual = pName1;
  58027. }
  58028. return iDb;
  58029. }
  58030. /*
  58031. ** This routine is used to check if the UTF-8 string zName is a legal
  58032. ** unqualified name for a new schema object (table, index, view or
  58033. ** trigger). All names are legal except those that begin with the string
  58034. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  58035. ** is reserved for internal use.
  58036. */
  58037. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  58038. if( !pParse->db->init.busy && pParse->nested==0
  58039. && (pParse->db->flags & SQLITE_WriteSchema)==0
  58040. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  58041. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  58042. return SQLITE_ERROR;
  58043. }
  58044. return SQLITE_OK;
  58045. }
  58046. /*
  58047. ** Begin constructing a new table representation in memory. This is
  58048. ** the first of several action routines that get called in response
  58049. ** to a CREATE TABLE statement. In particular, this routine is called
  58050. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  58051. ** flag is true if the table should be stored in the auxiliary database
  58052. ** file instead of in the main database file. This is normally the case
  58053. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  58054. ** CREATE and TABLE.
  58055. **
  58056. ** The new table record is initialized and put in pParse->pNewTable.
  58057. ** As more of the CREATE TABLE statement is parsed, additional action
  58058. ** routines will be called to add more information to this record.
  58059. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  58060. ** is called to complete the construction of the new table record.
  58061. */
  58062. SQLITE_PRIVATE void sqlite3StartTable(
  58063. Parse *pParse, /* Parser context */
  58064. Token *pName1, /* First part of the name of the table or view */
  58065. Token *pName2, /* Second part of the name of the table or view */
  58066. int isTemp, /* True if this is a TEMP table */
  58067. int isView, /* True if this is a VIEW */
  58068. int isVirtual, /* True if this is a VIRTUAL table */
  58069. int noErr /* Do nothing if table already exists */
  58070. ){
  58071. Table *pTable;
  58072. char *zName = 0; /* The name of the new table */
  58073. sqlite3 *db = pParse->db;
  58074. Vdbe *v;
  58075. int iDb; /* Database number to create the table in */
  58076. Token *pName; /* Unqualified name of the table to create */
  58077. /* The table or view name to create is passed to this routine via tokens
  58078. ** pName1 and pName2. If the table name was fully qualified, for example:
  58079. **
  58080. ** CREATE TABLE xxx.yyy (...);
  58081. **
  58082. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  58083. ** the table name is not fully qualified, i.e.:
  58084. **
  58085. ** CREATE TABLE yyy(...);
  58086. **
  58087. ** Then pName1 is set to "yyy" and pName2 is "".
  58088. **
  58089. ** The call below sets the pName pointer to point at the token (pName1 or
  58090. ** pName2) that stores the unqualified table name. The variable iDb is
  58091. ** set to the index of the database that the table or view is to be
  58092. ** created in.
  58093. */
  58094. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  58095. if( iDb<0 ) return;
  58096. if( !OMIT_TEMPDB && isTemp && iDb>1 ){
  58097. /* If creating a temp table, the name may not be qualified */
  58098. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  58099. return;
  58100. }
  58101. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  58102. pParse->sNameToken = *pName;
  58103. zName = sqlite3NameFromToken(db, pName);
  58104. if( zName==0 ) return;
  58105. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  58106. goto begin_table_error;
  58107. }
  58108. if( db->init.iDb==1 ) isTemp = 1;
  58109. #ifndef SQLITE_OMIT_AUTHORIZATION
  58110. assert( (isTemp & 1)==isTemp );
  58111. {
  58112. int code;
  58113. char *zDb = db->aDb[iDb].zName;
  58114. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  58115. goto begin_table_error;
  58116. }
  58117. if( isView ){
  58118. if( !OMIT_TEMPDB && isTemp ){
  58119. code = SQLITE_CREATE_TEMP_VIEW;
  58120. }else{
  58121. code = SQLITE_CREATE_VIEW;
  58122. }
  58123. }else{
  58124. if( !OMIT_TEMPDB && isTemp ){
  58125. code = SQLITE_CREATE_TEMP_TABLE;
  58126. }else{
  58127. code = SQLITE_CREATE_TABLE;
  58128. }
  58129. }
  58130. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  58131. goto begin_table_error;
  58132. }
  58133. }
  58134. #endif
  58135. /* Make sure the new table name does not collide with an existing
  58136. ** index or table name in the same database. Issue an error message if
  58137. ** it does. The exception is if the statement being parsed was passed
  58138. ** to an sqlite3_declare_vtab() call. In that case only the column names
  58139. ** and types will be used, so there is no need to test for namespace
  58140. ** collisions.
  58141. */
  58142. if( !IN_DECLARE_VTAB ){
  58143. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  58144. goto begin_table_error;
  58145. }
  58146. pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
  58147. if( pTable ){
  58148. if( !noErr ){
  58149. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  58150. }
  58151. goto begin_table_error;
  58152. }
  58153. if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
  58154. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  58155. goto begin_table_error;
  58156. }
  58157. }
  58158. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  58159. if( pTable==0 ){
  58160. db->mallocFailed = 1;
  58161. pParse->rc = SQLITE_NOMEM;
  58162. pParse->nErr++;
  58163. goto begin_table_error;
  58164. }
  58165. pTable->zName = zName;
  58166. pTable->iPKey = -1;
  58167. pTable->pSchema = db->aDb[iDb].pSchema;
  58168. pTable->nRef = 1;
  58169. pTable->db = db;
  58170. if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
  58171. pParse->pNewTable = pTable;
  58172. /* If this is the magic sqlite_sequence table used by autoincrement,
  58173. ** then record a pointer to this table in the main database structure
  58174. ** so that INSERT can find the table easily.
  58175. */
  58176. #ifndef SQLITE_OMIT_AUTOINCREMENT
  58177. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  58178. pTable->pSchema->pSeqTab = pTable;
  58179. }
  58180. #endif
  58181. /* Begin generating the code that will insert the table record into
  58182. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  58183. ** and allocate the record number for the table entry now. Before any
  58184. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  58185. ** indices to be created and the table record must come before the
  58186. ** indices. Hence, the record number for the table must be allocated
  58187. ** now.
  58188. */
  58189. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  58190. int j1;
  58191. int fileFormat;
  58192. int reg1, reg2, reg3;
  58193. sqlite3BeginWriteOperation(pParse, 0, iDb);
  58194. #ifndef SQLITE_OMIT_VIRTUALTABLE
  58195. if( isVirtual ){
  58196. sqlite3VdbeAddOp0(v, OP_VBegin);
  58197. }
  58198. #endif
  58199. /* If the file format and encoding in the database have not been set,
  58200. ** set them now.
  58201. */
  58202. reg1 = pParse->regRowid = ++pParse->nMem;
  58203. reg2 = pParse->regRoot = ++pParse->nMem;
  58204. reg3 = ++pParse->nMem;
  58205. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1); /* file_format */
  58206. sqlite3VdbeUsesBtree(v, iDb);
  58207. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  58208. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  58209. 1 : SQLITE_MAX_FILE_FORMAT;
  58210. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  58211. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
  58212. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  58213. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
  58214. sqlite3VdbeJumpHere(v, j1);
  58215. /* This just creates a place-holder record in the sqlite_master table.
  58216. ** The record created does not contain anything yet. It will be replaced
  58217. ** by the real entry in code generated at sqlite3EndTable().
  58218. **
  58219. ** The rowid for the new entry is left on the top of the stack.
  58220. ** The rowid value is needed by the code that sqlite3EndTable will
  58221. ** generate.
  58222. */
  58223. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  58224. if( isView || isVirtual ){
  58225. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  58226. }else
  58227. #endif
  58228. {
  58229. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  58230. }
  58231. sqlite3OpenMasterTable(pParse, iDb);
  58232. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  58233. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  58234. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  58235. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  58236. sqlite3VdbeAddOp0(v, OP_Close);
  58237. }
  58238. /* Normal (non-error) return. */
  58239. return;
  58240. /* If an error occurs, we jump here */
  58241. begin_table_error:
  58242. sqlite3DbFree(db, zName);
  58243. return;
  58244. }
  58245. /*
  58246. ** This macro is used to compare two strings in a case-insensitive manner.
  58247. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  58248. ** produces larger code.
  58249. **
  58250. ** WARNING: This macro is not compatible with the strcmp() family. It
  58251. ** returns true if the two strings are equal, otherwise false.
  58252. */
  58253. #define STRICMP(x, y) (\
  58254. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  58255. sqlite3UpperToLower[*(unsigned char *)(y)] \
  58256. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  58257. /*
  58258. ** Add a new column to the table currently being constructed.
  58259. **
  58260. ** The parser calls this routine once for each column declaration
  58261. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  58262. ** first to get things going. Then this routine is called for each
  58263. ** column.
  58264. */
  58265. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  58266. Table *p;
  58267. int i;
  58268. char *z;
  58269. Column *pCol;
  58270. sqlite3 *db = pParse->db;
  58271. if( (p = pParse->pNewTable)==0 ) return;
  58272. #if SQLITE_MAX_COLUMN
  58273. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  58274. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  58275. return;
  58276. }
  58277. #endif
  58278. z = sqlite3NameFromToken(db, pName);
  58279. if( z==0 ) return;
  58280. for(i=0; i<p->nCol; i++){
  58281. if( STRICMP(z, p->aCol[i].zName) ){
  58282. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  58283. sqlite3DbFree(db, z);
  58284. return;
  58285. }
  58286. }
  58287. if( (p->nCol & 0x7)==0 ){
  58288. Column *aNew;
  58289. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  58290. if( aNew==0 ){
  58291. sqlite3DbFree(db, z);
  58292. return;
  58293. }
  58294. p->aCol = aNew;
  58295. }
  58296. pCol = &p->aCol[p->nCol];
  58297. memset(pCol, 0, sizeof(p->aCol[0]));
  58298. pCol->zName = z;
  58299. /* If there is no type specified, columns have the default affinity
  58300. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  58301. ** be called next to set pCol->affinity correctly.
  58302. */
  58303. pCol->affinity = SQLITE_AFF_NONE;
  58304. p->nCol++;
  58305. }
  58306. /*
  58307. ** This routine is called by the parser while in the middle of
  58308. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  58309. ** been seen on a column. This routine sets the notNull flag on
  58310. ** the column currently under construction.
  58311. */
  58312. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  58313. Table *p;
  58314. int i;
  58315. if( (p = pParse->pNewTable)==0 ) return;
  58316. i = p->nCol-1;
  58317. if( i>=0 ) p->aCol[i].notNull = (u8)onError;
  58318. }
  58319. /*
  58320. ** Scan the column type name zType (length nType) and return the
  58321. ** associated affinity type.
  58322. **
  58323. ** This routine does a case-independent search of zType for the
  58324. ** substrings in the following table. If one of the substrings is
  58325. ** found, the corresponding affinity is returned. If zType contains
  58326. ** more than one of the substrings, entries toward the top of
  58327. ** the table take priority. For example, if zType is 'BLOBINT',
  58328. ** SQLITE_AFF_INTEGER is returned.
  58329. **
  58330. ** Substring | Affinity
  58331. ** --------------------------------
  58332. ** 'INT' | SQLITE_AFF_INTEGER
  58333. ** 'CHAR' | SQLITE_AFF_TEXT
  58334. ** 'CLOB' | SQLITE_AFF_TEXT
  58335. ** 'TEXT' | SQLITE_AFF_TEXT
  58336. ** 'BLOB' | SQLITE_AFF_NONE
  58337. ** 'REAL' | SQLITE_AFF_REAL
  58338. ** 'FLOA' | SQLITE_AFF_REAL
  58339. ** 'DOUB' | SQLITE_AFF_REAL
  58340. **
  58341. ** If none of the substrings in the above table are found,
  58342. ** SQLITE_AFF_NUMERIC is returned.
  58343. */
  58344. SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
  58345. u32 h = 0;
  58346. char aff = SQLITE_AFF_NUMERIC;
  58347. const unsigned char *zIn = pType->z;
  58348. const unsigned char *zEnd = &pType->z[pType->n];
  58349. while( zIn!=zEnd ){
  58350. h = (h<<8) + sqlite3UpperToLower[*zIn];
  58351. zIn++;
  58352. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  58353. aff = SQLITE_AFF_TEXT;
  58354. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  58355. aff = SQLITE_AFF_TEXT;
  58356. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  58357. aff = SQLITE_AFF_TEXT;
  58358. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  58359. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  58360. aff = SQLITE_AFF_NONE;
  58361. #ifndef SQLITE_OMIT_FLOATING_POINT
  58362. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  58363. && aff==SQLITE_AFF_NUMERIC ){
  58364. aff = SQLITE_AFF_REAL;
  58365. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  58366. && aff==SQLITE_AFF_NUMERIC ){
  58367. aff = SQLITE_AFF_REAL;
  58368. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  58369. && aff==SQLITE_AFF_NUMERIC ){
  58370. aff = SQLITE_AFF_REAL;
  58371. #endif
  58372. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  58373. aff = SQLITE_AFF_INTEGER;
  58374. break;
  58375. }
  58376. }
  58377. return aff;
  58378. }
  58379. /*
  58380. ** This routine is called by the parser while in the middle of
  58381. ** parsing a CREATE TABLE statement. The pFirst token is the first
  58382. ** token in the sequence of tokens that describe the type of the
  58383. ** column currently under construction. pLast is the last token
  58384. ** in the sequence. Use this information to construct a string
  58385. ** that contains the typename of the column and store that string
  58386. ** in zType.
  58387. */
  58388. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  58389. Table *p;
  58390. int i;
  58391. Column *pCol;
  58392. sqlite3 *db;
  58393. if( (p = pParse->pNewTable)==0 ) return;
  58394. i = p->nCol-1;
  58395. if( i<0 ) return;
  58396. pCol = &p->aCol[i];
  58397. db = pParse->db;
  58398. sqlite3DbFree(db, pCol->zType);
  58399. pCol->zType = sqlite3NameFromToken(db, pType);
  58400. pCol->affinity = sqlite3AffinityType(pType);
  58401. }
  58402. /*
  58403. ** The expression is the default value for the most recently added column
  58404. ** of the table currently under construction.
  58405. **
  58406. ** Default value expressions must be constant. Raise an exception if this
  58407. ** is not the case.
  58408. **
  58409. ** This routine is called by the parser while in the middle of
  58410. ** parsing a CREATE TABLE statement.
  58411. */
  58412. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
  58413. Table *p;
  58414. Column *pCol;
  58415. sqlite3 *db = pParse->db;
  58416. if( (p = pParse->pNewTable)!=0 ){
  58417. pCol = &(p->aCol[p->nCol-1]);
  58418. if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
  58419. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  58420. pCol->zName);
  58421. }else{
  58422. Expr *pCopy;
  58423. sqlite3ExprDelete(db, pCol->pDflt);
  58424. pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
  58425. if( pCopy ){
  58426. sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
  58427. }
  58428. }
  58429. }
  58430. sqlite3ExprDelete(db, pExpr);
  58431. }
  58432. /*
  58433. ** Designate the PRIMARY KEY for the table. pList is a list of names
  58434. ** of columns that form the primary key. If pList is NULL, then the
  58435. ** most recently added column of the table is the primary key.
  58436. **
  58437. ** A table can have at most one primary key. If the table already has
  58438. ** a primary key (and this is the second primary key) then create an
  58439. ** error.
  58440. **
  58441. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  58442. ** then we will try to use that column as the rowid. Set the Table.iPKey
  58443. ** field of the table under construction to be the index of the
  58444. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  58445. ** no INTEGER PRIMARY KEY.
  58446. **
  58447. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  58448. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  58449. */
  58450. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  58451. Parse *pParse, /* Parsing context */
  58452. ExprList *pList, /* List of field names to be indexed */
  58453. int onError, /* What to do with a uniqueness conflict */
  58454. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  58455. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  58456. ){
  58457. Table *pTab = pParse->pNewTable;
  58458. char *zType = 0;
  58459. int iCol = -1, i;
  58460. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  58461. if( pTab->tabFlags & TF_HasPrimaryKey ){
  58462. sqlite3ErrorMsg(pParse,
  58463. "table \"%s\" has more than one primary key", pTab->zName);
  58464. goto primary_key_exit;
  58465. }
  58466. pTab->tabFlags |= TF_HasPrimaryKey;
  58467. if( pList==0 ){
  58468. iCol = pTab->nCol - 1;
  58469. pTab->aCol[iCol].isPrimKey = 1;
  58470. }else{
  58471. for(i=0; i<pList->nExpr; i++){
  58472. for(iCol=0; iCol<pTab->nCol; iCol++){
  58473. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  58474. break;
  58475. }
  58476. }
  58477. if( iCol<pTab->nCol ){
  58478. pTab->aCol[iCol].isPrimKey = 1;
  58479. }
  58480. }
  58481. if( pList->nExpr>1 ) iCol = -1;
  58482. }
  58483. if( iCol>=0 && iCol<pTab->nCol ){
  58484. zType = pTab->aCol[iCol].zType;
  58485. }
  58486. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  58487. && sortOrder==SQLITE_SO_ASC ){
  58488. pTab->iPKey = iCol;
  58489. pTab->keyConf = (u8)onError;
  58490. assert( autoInc==0 || autoInc==1 );
  58491. pTab->tabFlags |= autoInc*TF_Autoincrement;
  58492. }else if( autoInc ){
  58493. #ifndef SQLITE_OMIT_AUTOINCREMENT
  58494. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  58495. "INTEGER PRIMARY KEY");
  58496. #endif
  58497. }else{
  58498. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
  58499. pList = 0;
  58500. }
  58501. primary_key_exit:
  58502. sqlite3ExprListDelete(pParse->db, pList);
  58503. return;
  58504. }
  58505. /*
  58506. ** Add a new CHECK constraint to the table currently under construction.
  58507. */
  58508. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  58509. Parse *pParse, /* Parsing context */
  58510. Expr *pCheckExpr /* The check expression */
  58511. ){
  58512. sqlite3 *db = pParse->db;
  58513. #ifndef SQLITE_OMIT_CHECK
  58514. Table *pTab = pParse->pNewTable;
  58515. if( pTab && !IN_DECLARE_VTAB ){
  58516. /* The CHECK expression must be duplicated so that tokens refer
  58517. ** to malloced space and not the (ephemeral) text of the CREATE TABLE
  58518. ** statement */
  58519. pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck,
  58520. sqlite3ExprDup(db, pCheckExpr));
  58521. }
  58522. #endif
  58523. sqlite3ExprDelete(db, pCheckExpr);
  58524. }
  58525. /*
  58526. ** Set the collation function of the most recently parsed table column
  58527. ** to the CollSeq given.
  58528. */
  58529. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  58530. Table *p;
  58531. int i;
  58532. char *zColl; /* Dequoted name of collation sequence */
  58533. sqlite3 *db;
  58534. if( (p = pParse->pNewTable)==0 ) return;
  58535. i = p->nCol-1;
  58536. db = pParse->db;
  58537. zColl = sqlite3NameFromToken(db, pToken);
  58538. if( !zColl ) return;
  58539. if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
  58540. Index *pIdx;
  58541. p->aCol[i].zColl = zColl;
  58542. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  58543. ** then an index may have been created on this column before the
  58544. ** collation type was added. Correct this if it is the case.
  58545. */
  58546. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  58547. assert( pIdx->nColumn==1 );
  58548. if( pIdx->aiColumn[0]==i ){
  58549. pIdx->azColl[0] = p->aCol[i].zColl;
  58550. }
  58551. }
  58552. }else{
  58553. sqlite3DbFree(db, zColl);
  58554. }
  58555. }
  58556. /*
  58557. ** This function returns the collation sequence for database native text
  58558. ** encoding identified by the string zName, length nName.
  58559. **
  58560. ** If the requested collation sequence is not available, or not available
  58561. ** in the database native encoding, the collation factory is invoked to
  58562. ** request it. If the collation factory does not supply such a sequence,
  58563. ** and the sequence is available in another text encoding, then that is
  58564. ** returned instead.
  58565. **
  58566. ** If no versions of the requested collations sequence are available, or
  58567. ** another error occurs, NULL is returned and an error message written into
  58568. ** pParse.
  58569. **
  58570. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  58571. ** invokes the collation factory if the named collation cannot be found
  58572. ** and generates an error message.
  58573. */
  58574. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
  58575. sqlite3 *db = pParse->db;
  58576. u8 enc = ENC(db);
  58577. u8 initbusy = db->init.busy;
  58578. CollSeq *pColl;
  58579. pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
  58580. if( !initbusy && (!pColl || !pColl->xCmp) ){
  58581. pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
  58582. if( !pColl ){
  58583. if( nName<0 ){
  58584. nName = sqlite3Strlen(db, zName);
  58585. }
  58586. sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
  58587. pColl = 0;
  58588. }
  58589. }
  58590. return pColl;
  58591. }
  58592. /*
  58593. ** Generate code that will increment the schema cookie.
  58594. **
  58595. ** The schema cookie is used to determine when the schema for the
  58596. ** database changes. After each schema change, the cookie value
  58597. ** changes. When a process first reads the schema it records the
  58598. ** cookie. Thereafter, whenever it goes to access the database,
  58599. ** it checks the cookie to make sure the schema has not changed
  58600. ** since it was last read.
  58601. **
  58602. ** This plan is not completely bullet-proof. It is possible for
  58603. ** the schema to change multiple times and for the cookie to be
  58604. ** set back to prior value. But schema changes are infrequent
  58605. ** and the probability of hitting the same cookie value is only
  58606. ** 1 chance in 2^32. So we're safe enough.
  58607. */
  58608. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  58609. int r1 = sqlite3GetTempReg(pParse);
  58610. sqlite3 *db = pParse->db;
  58611. Vdbe *v = pParse->pVdbe;
  58612. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  58613. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
  58614. sqlite3ReleaseTempReg(pParse, r1);
  58615. }
  58616. /*
  58617. ** Measure the number of characters needed to output the given
  58618. ** identifier. The number returned includes any quotes used
  58619. ** but does not include the null terminator.
  58620. **
  58621. ** The estimate is conservative. It might be larger that what is
  58622. ** really needed.
  58623. */
  58624. static int identLength(const char *z){
  58625. int n;
  58626. for(n=0; *z; n++, z++){
  58627. if( *z=='"' ){ n++; }
  58628. }
  58629. return n + 2;
  58630. }
  58631. /*
  58632. ** Write an identifier onto the end of the given string. Add
  58633. ** quote characters as needed.
  58634. */
  58635. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  58636. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  58637. int i, j, needQuote;
  58638. i = *pIdx;
  58639. for(j=0; zIdent[j]; j++){
  58640. if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  58641. }
  58642. needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
  58643. || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  58644. if( needQuote ) z[i++] = '"';
  58645. for(j=0; zIdent[j]; j++){
  58646. z[i++] = zIdent[j];
  58647. if( zIdent[j]=='"' ) z[i++] = '"';
  58648. }
  58649. if( needQuote ) z[i++] = '"';
  58650. z[i] = 0;
  58651. *pIdx = i;
  58652. }
  58653. /*
  58654. ** Generate a CREATE TABLE statement appropriate for the given
  58655. ** table. Memory to hold the text of the statement is obtained
  58656. ** from sqliteMalloc() and must be freed by the calling function.
  58657. */
  58658. static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
  58659. int i, k, n;
  58660. char *zStmt;
  58661. char *zSep, *zSep2, *zEnd, *z;
  58662. Column *pCol;
  58663. n = 0;
  58664. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  58665. n += identLength(pCol->zName);
  58666. z = pCol->zType;
  58667. if( z ){
  58668. n += (sqlite3Strlen30(z) + 1);
  58669. }
  58670. }
  58671. n += identLength(p->zName);
  58672. if( n<50 ){
  58673. zSep = "";
  58674. zSep2 = ",";
  58675. zEnd = ")";
  58676. }else{
  58677. zSep = "\n ";
  58678. zSep2 = ",\n ";
  58679. zEnd = "\n)";
  58680. }
  58681. n += 35 + 6*p->nCol;
  58682. zStmt = sqlite3Malloc( n );
  58683. if( zStmt==0 ){
  58684. db->mallocFailed = 1;
  58685. return 0;
  58686. }
  58687. sqlite3_snprintf(n, zStmt,
  58688. !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
  58689. k = sqlite3Strlen30(zStmt);
  58690. identPut(zStmt, &k, p->zName);
  58691. zStmt[k++] = '(';
  58692. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  58693. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  58694. k += sqlite3Strlen30(&zStmt[k]);
  58695. zSep = zSep2;
  58696. identPut(zStmt, &k, pCol->zName);
  58697. if( (z = pCol->zType)!=0 ){
  58698. zStmt[k++] = ' ';
  58699. assert( (int)(sqlite3Strlen30(z)+k+1)<=n );
  58700. sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
  58701. k += sqlite3Strlen30(z);
  58702. }
  58703. }
  58704. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  58705. return zStmt;
  58706. }
  58707. /*
  58708. ** This routine is called to report the final ")" that terminates
  58709. ** a CREATE TABLE statement.
  58710. **
  58711. ** The table structure that other action routines have been building
  58712. ** is added to the internal hash tables, assuming no errors have
  58713. ** occurred.
  58714. **
  58715. ** An entry for the table is made in the master table on disk, unless
  58716. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  58717. ** it means we are reading the sqlite_master table because we just
  58718. ** connected to the database or because the sqlite_master table has
  58719. ** recently changed, so the entry for this table already exists in
  58720. ** the sqlite_master table. We do not want to create it again.
  58721. **
  58722. ** If the pSelect argument is not NULL, it means that this routine
  58723. ** was called to create a table generated from a
  58724. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  58725. ** the new table will match the result set of the SELECT.
  58726. */
  58727. SQLITE_PRIVATE void sqlite3EndTable(
  58728. Parse *pParse, /* Parse context */
  58729. Token *pCons, /* The ',' token after the last column defn. */
  58730. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  58731. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  58732. ){
  58733. Table *p;
  58734. sqlite3 *db = pParse->db;
  58735. int iDb;
  58736. if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
  58737. return;
  58738. }
  58739. p = pParse->pNewTable;
  58740. if( p==0 ) return;
  58741. assert( !db->init.busy || !pSelect );
  58742. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  58743. #ifndef SQLITE_OMIT_CHECK
  58744. /* Resolve names in all CHECK constraint expressions.
  58745. */
  58746. if( p->pCheck ){
  58747. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  58748. NameContext sNC; /* Name context for pParse->pNewTable */
  58749. memset(&sNC, 0, sizeof(sNC));
  58750. memset(&sSrc, 0, sizeof(sSrc));
  58751. sSrc.nSrc = 1;
  58752. sSrc.a[0].zName = p->zName;
  58753. sSrc.a[0].pTab = p;
  58754. sSrc.a[0].iCursor = -1;
  58755. sNC.pParse = pParse;
  58756. sNC.pSrcList = &sSrc;
  58757. sNC.isCheck = 1;
  58758. if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
  58759. return;
  58760. }
  58761. }
  58762. #endif /* !defined(SQLITE_OMIT_CHECK) */
  58763. /* If the db->init.busy is 1 it means we are reading the SQL off the
  58764. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  58765. ** So do not write to the disk again. Extract the root page number
  58766. ** for the table from the db->init.newTnum field. (The page number
  58767. ** should have been put there by the sqliteOpenCb routine.)
  58768. */
  58769. if( db->init.busy ){
  58770. p->tnum = db->init.newTnum;
  58771. }
  58772. /* If not initializing, then create a record for the new table
  58773. ** in the SQLITE_MASTER table of the database. The record number
  58774. ** for the new table entry should already be on the stack.
  58775. **
  58776. ** If this is a TEMPORARY table, write the entry into the auxiliary
  58777. ** file instead of into the main database file.
  58778. */
  58779. if( !db->init.busy ){
  58780. int n;
  58781. Vdbe *v;
  58782. char *zType; /* "view" or "table" */
  58783. char *zType2; /* "VIEW" or "TABLE" */
  58784. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  58785. v = sqlite3GetVdbe(pParse);
  58786. if( v==0 ) return;
  58787. sqlite3VdbeAddOp1(v, OP_Close, 0);
  58788. /* Create the rootpage for the new table and push it onto the stack.
  58789. ** A view has no rootpage, so just push a zero onto the stack for
  58790. ** views. Initialize zType at the same time.
  58791. */
  58792. if( p->pSelect==0 ){
  58793. /* A regular table */
  58794. zType = "table";
  58795. zType2 = "TABLE";
  58796. #ifndef SQLITE_OMIT_VIEW
  58797. }else{
  58798. /* A view */
  58799. zType = "view";
  58800. zType2 = "VIEW";
  58801. #endif
  58802. }
  58803. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  58804. ** statement to populate the new table. The root-page number for the
  58805. ** new table is on the top of the vdbe stack.
  58806. **
  58807. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  58808. ** suitable state to query for the column names and types to be used
  58809. ** by the new table.
  58810. **
  58811. ** A shared-cache write-lock is not required to write to the new table,
  58812. ** as a schema-lock must have already been obtained to create it. Since
  58813. ** a schema-lock excludes all other database users, the write-lock would
  58814. ** be redundant.
  58815. */
  58816. if( pSelect ){
  58817. SelectDest dest;
  58818. Table *pSelTab;
  58819. assert(pParse->nTab==0);
  58820. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  58821. sqlite3VdbeChangeP5(v, 1);
  58822. pParse->nTab = 2;
  58823. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  58824. sqlite3Select(pParse, pSelect, &dest);
  58825. sqlite3VdbeAddOp1(v, OP_Close, 1);
  58826. if( pParse->nErr==0 ){
  58827. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  58828. if( pSelTab==0 ) return;
  58829. assert( p->aCol==0 );
  58830. p->nCol = pSelTab->nCol;
  58831. p->aCol = pSelTab->aCol;
  58832. pSelTab->nCol = 0;
  58833. pSelTab->aCol = 0;
  58834. sqlite3DeleteTable(pSelTab);
  58835. }
  58836. }
  58837. /* Compute the complete text of the CREATE statement */
  58838. if( pSelect ){
  58839. zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
  58840. }else{
  58841. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  58842. zStmt = sqlite3MPrintf(db,
  58843. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  58844. );
  58845. }
  58846. /* A slot for the record has already been allocated in the
  58847. ** SQLITE_MASTER table. We just need to update that slot with all
  58848. ** the information we've collected. The rowid for the preallocated
  58849. ** slot is the 2nd item on the stack. The top of the stack is the
  58850. ** root page for the new table (or a 0 if this is a view).
  58851. */
  58852. sqlite3NestedParse(pParse,
  58853. "UPDATE %Q.%s "
  58854. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  58855. "WHERE rowid=#%d",
  58856. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  58857. zType,
  58858. p->zName,
  58859. p->zName,
  58860. pParse->regRoot,
  58861. zStmt,
  58862. pParse->regRowid
  58863. );
  58864. sqlite3DbFree(db, zStmt);
  58865. sqlite3ChangeCookie(pParse, iDb);
  58866. #ifndef SQLITE_OMIT_AUTOINCREMENT
  58867. /* Check to see if we need to create an sqlite_sequence table for
  58868. ** keeping track of autoincrement keys.
  58869. */
  58870. if( p->tabFlags & TF_Autoincrement ){
  58871. Db *pDb = &db->aDb[iDb];
  58872. if( pDb->pSchema->pSeqTab==0 ){
  58873. sqlite3NestedParse(pParse,
  58874. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  58875. pDb->zName
  58876. );
  58877. }
  58878. }
  58879. #endif
  58880. /* Reparse everything to update our internal data structures */
  58881. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
  58882. sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
  58883. }
  58884. /* Add the table to the in-memory representation of the database.
  58885. */
  58886. if( db->init.busy && pParse->nErr==0 ){
  58887. Table *pOld;
  58888. FKey *pFKey;
  58889. Schema *pSchema = p->pSchema;
  58890. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  58891. sqlite3Strlen30(p->zName)+1,p);
  58892. if( pOld ){
  58893. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  58894. db->mallocFailed = 1;
  58895. return;
  58896. }
  58897. #ifndef SQLITE_OMIT_FOREIGN_KEY
  58898. for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  58899. void *data;
  58900. int nTo = sqlite3Strlen30(pFKey->zTo) + 1;
  58901. pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
  58902. data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
  58903. if( data==(void *)pFKey ){
  58904. db->mallocFailed = 1;
  58905. }
  58906. }
  58907. #endif
  58908. pParse->pNewTable = 0;
  58909. db->nTable++;
  58910. db->flags |= SQLITE_InternChanges;
  58911. #ifndef SQLITE_OMIT_ALTERTABLE
  58912. if( !p->pSelect ){
  58913. const char *zName = (const char *)pParse->sNameToken.z;
  58914. int nName;
  58915. assert( !pSelect && pCons && pEnd );
  58916. if( pCons->z==0 ){
  58917. pCons = pEnd;
  58918. }
  58919. nName = (int)((const char *)pCons->z - zName);
  58920. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  58921. }
  58922. #endif
  58923. }
  58924. }
  58925. #ifndef SQLITE_OMIT_VIEW
  58926. /*
  58927. ** The parser calls this routine in order to create a new VIEW
  58928. */
  58929. SQLITE_PRIVATE void sqlite3CreateView(
  58930. Parse *pParse, /* The parsing context */
  58931. Token *pBegin, /* The CREATE token that begins the statement */
  58932. Token *pName1, /* The token that holds the name of the view */
  58933. Token *pName2, /* The token that holds the name of the view */
  58934. Select *pSelect, /* A SELECT statement that will become the new view */
  58935. int isTemp, /* TRUE for a TEMPORARY view */
  58936. int noErr /* Suppress error messages if VIEW already exists */
  58937. ){
  58938. Table *p;
  58939. int n;
  58940. const unsigned char *z;
  58941. Token sEnd;
  58942. DbFixer sFix;
  58943. Token *pName;
  58944. int iDb;
  58945. sqlite3 *db = pParse->db;
  58946. if( pParse->nVar>0 ){
  58947. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  58948. sqlite3SelectDelete(db, pSelect);
  58949. return;
  58950. }
  58951. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  58952. p = pParse->pNewTable;
  58953. if( p==0 || pParse->nErr ){
  58954. sqlite3SelectDelete(db, pSelect);
  58955. return;
  58956. }
  58957. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  58958. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  58959. if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
  58960. && sqlite3FixSelect(&sFix, pSelect)
  58961. ){
  58962. sqlite3SelectDelete(db, pSelect);
  58963. return;
  58964. }
  58965. /* Make a copy of the entire SELECT statement that defines the view.
  58966. ** This will force all the Expr.token.z values to be dynamically
  58967. ** allocated rather than point to the input string - which means that
  58968. ** they will persist after the current sqlite3_exec() call returns.
  58969. */
  58970. p->pSelect = sqlite3SelectDup(db, pSelect);
  58971. sqlite3SelectDelete(db, pSelect);
  58972. if( db->mallocFailed ){
  58973. return;
  58974. }
  58975. if( !db->init.busy ){
  58976. sqlite3ViewGetColumnNames(pParse, p);
  58977. }
  58978. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  58979. ** the end.
  58980. */
  58981. sEnd = pParse->sLastToken;
  58982. if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
  58983. sEnd.z += sEnd.n;
  58984. }
  58985. sEnd.n = 0;
  58986. n = (int)(sEnd.z - pBegin->z);
  58987. z = (const unsigned char*)pBegin->z;
  58988. while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
  58989. sEnd.z = &z[n-1];
  58990. sEnd.n = 1;
  58991. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  58992. sqlite3EndTable(pParse, 0, &sEnd, 0);
  58993. return;
  58994. }
  58995. #endif /* SQLITE_OMIT_VIEW */
  58996. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  58997. /*
  58998. ** The Table structure pTable is really a VIEW. Fill in the names of
  58999. ** the columns of the view in the pTable structure. Return the number
  59000. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  59001. */
  59002. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  59003. Table *pSelTab; /* A fake table from which we get the result set */
  59004. Select *pSel; /* Copy of the SELECT that implements the view */
  59005. int nErr = 0; /* Number of errors encountered */
  59006. int n; /* Temporarily holds the number of cursors assigned */
  59007. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  59008. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  59009. assert( pTable );
  59010. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59011. if( sqlite3VtabCallConnect(pParse, pTable) ){
  59012. return SQLITE_ERROR;
  59013. }
  59014. if( IsVirtual(pTable) ) return 0;
  59015. #endif
  59016. #ifndef SQLITE_OMIT_VIEW
  59017. /* A positive nCol means the columns names for this view are
  59018. ** already known.
  59019. */
  59020. if( pTable->nCol>0 ) return 0;
  59021. /* A negative nCol is a special marker meaning that we are currently
  59022. ** trying to compute the column names. If we enter this routine with
  59023. ** a negative nCol, it means two or more views form a loop, like this:
  59024. **
  59025. ** CREATE VIEW one AS SELECT * FROM two;
  59026. ** CREATE VIEW two AS SELECT * FROM one;
  59027. **
  59028. ** Actually, this error is caught previously and so the following test
  59029. ** should always fail. But we will leave it in place just to be safe.
  59030. */
  59031. if( pTable->nCol<0 ){
  59032. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  59033. return 1;
  59034. }
  59035. assert( pTable->nCol>=0 );
  59036. /* If we get this far, it means we need to compute the table names.
  59037. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  59038. ** "*" elements in the results set of the view and will assign cursors
  59039. ** to the elements of the FROM clause. But we do not want these changes
  59040. ** to be permanent. So the computation is done on a copy of the SELECT
  59041. ** statement that defines the view.
  59042. */
  59043. assert( pTable->pSelect );
  59044. pSel = sqlite3SelectDup(db, pTable->pSelect);
  59045. if( pSel ){
  59046. n = pParse->nTab;
  59047. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  59048. pTable->nCol = -1;
  59049. #ifndef SQLITE_OMIT_AUTHORIZATION
  59050. xAuth = db->xAuth;
  59051. db->xAuth = 0;
  59052. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  59053. db->xAuth = xAuth;
  59054. #else
  59055. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  59056. #endif
  59057. pParse->nTab = n;
  59058. if( pSelTab ){
  59059. assert( pTable->aCol==0 );
  59060. pTable->nCol = pSelTab->nCol;
  59061. pTable->aCol = pSelTab->aCol;
  59062. pSelTab->nCol = 0;
  59063. pSelTab->aCol = 0;
  59064. sqlite3DeleteTable(pSelTab);
  59065. pTable->pSchema->flags |= DB_UnresetViews;
  59066. }else{
  59067. pTable->nCol = 0;
  59068. nErr++;
  59069. }
  59070. sqlite3SelectDelete(db, pSel);
  59071. } else {
  59072. nErr++;
  59073. }
  59074. #endif /* SQLITE_OMIT_VIEW */
  59075. return nErr;
  59076. }
  59077. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  59078. #ifndef SQLITE_OMIT_VIEW
  59079. /*
  59080. ** Clear the column names from every VIEW in database idx.
  59081. */
  59082. static void sqliteViewResetAll(sqlite3 *db, int idx){
  59083. HashElem *i;
  59084. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  59085. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  59086. Table *pTab = sqliteHashData(i);
  59087. if( pTab->pSelect ){
  59088. sqliteResetColumnNames(pTab);
  59089. }
  59090. }
  59091. DbClearProperty(db, idx, DB_UnresetViews);
  59092. }
  59093. #else
  59094. # define sqliteViewResetAll(A,B)
  59095. #endif /* SQLITE_OMIT_VIEW */
  59096. /*
  59097. ** This function is called by the VDBE to adjust the internal schema
  59098. ** used by SQLite when the btree layer moves a table root page. The
  59099. ** root-page of a table or index in database iDb has changed from iFrom
  59100. ** to iTo.
  59101. **
  59102. ** Ticket #1728: The symbol table might still contain information
  59103. ** on tables and/or indices that are the process of being deleted.
  59104. ** If you are unlucky, one of those deleted indices or tables might
  59105. ** have the same rootpage number as the real table or index that is
  59106. ** being moved. So we cannot stop searching after the first match
  59107. ** because the first match might be for one of the deleted indices
  59108. ** or tables and not the table/index that is actually being moved.
  59109. ** We must continue looping until all tables and indices with
  59110. ** rootpage==iFrom have been converted to have a rootpage of iTo
  59111. ** in order to be certain that we got the right one.
  59112. */
  59113. #ifndef SQLITE_OMIT_AUTOVACUUM
  59114. SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
  59115. HashElem *pElem;
  59116. Hash *pHash;
  59117. pHash = &pDb->pSchema->tblHash;
  59118. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  59119. Table *pTab = sqliteHashData(pElem);
  59120. if( pTab->tnum==iFrom ){
  59121. pTab->tnum = iTo;
  59122. }
  59123. }
  59124. pHash = &pDb->pSchema->idxHash;
  59125. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  59126. Index *pIdx = sqliteHashData(pElem);
  59127. if( pIdx->tnum==iFrom ){
  59128. pIdx->tnum = iTo;
  59129. }
  59130. }
  59131. }
  59132. #endif
  59133. /*
  59134. ** Write code to erase the table with root-page iTable from database iDb.
  59135. ** Also write code to modify the sqlite_master table and internal schema
  59136. ** if a root-page of another table is moved by the btree-layer whilst
  59137. ** erasing iTable (this can happen with an auto-vacuum database).
  59138. */
  59139. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  59140. Vdbe *v = sqlite3GetVdbe(pParse);
  59141. int r1 = sqlite3GetTempReg(pParse);
  59142. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  59143. #ifndef SQLITE_OMIT_AUTOVACUUM
  59144. /* OP_Destroy stores an in integer r1. If this integer
  59145. ** is non-zero, then it is the root page number of a table moved to
  59146. ** location iTable. The following code modifies the sqlite_master table to
  59147. ** reflect this.
  59148. **
  59149. ** The "#%d" in the SQL is a special constant that means whatever value
  59150. ** is on the top of the stack. See sqlite3RegisterExpr().
  59151. */
  59152. sqlite3NestedParse(pParse,
  59153. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  59154. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  59155. #endif
  59156. sqlite3ReleaseTempReg(pParse, r1);
  59157. }
  59158. /*
  59159. ** Write VDBE code to erase table pTab and all associated indices on disk.
  59160. ** Code to update the sqlite_master tables and internal schema definitions
  59161. ** in case a root-page belonging to another table is moved by the btree layer
  59162. ** is also added (this can happen with an auto-vacuum database).
  59163. */
  59164. static void destroyTable(Parse *pParse, Table *pTab){
  59165. #ifdef SQLITE_OMIT_AUTOVACUUM
  59166. Index *pIdx;
  59167. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  59168. destroyRootPage(pParse, pTab->tnum, iDb);
  59169. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  59170. destroyRootPage(pParse, pIdx->tnum, iDb);
  59171. }
  59172. #else
  59173. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  59174. ** is not defined), then it is important to call OP_Destroy on the
  59175. ** table and index root-pages in order, starting with the numerically
  59176. ** largest root-page number. This guarantees that none of the root-pages
  59177. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  59178. ** following were coded:
  59179. **
  59180. ** OP_Destroy 4 0
  59181. ** ...
  59182. ** OP_Destroy 5 0
  59183. **
  59184. ** and root page 5 happened to be the largest root-page number in the
  59185. ** database, then root page 5 would be moved to page 4 by the
  59186. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  59187. ** a free-list page.
  59188. */
  59189. int iTab = pTab->tnum;
  59190. int iDestroyed = 0;
  59191. while( 1 ){
  59192. Index *pIdx;
  59193. int iLargest = 0;
  59194. if( iDestroyed==0 || iTab<iDestroyed ){
  59195. iLargest = iTab;
  59196. }
  59197. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  59198. int iIdx = pIdx->tnum;
  59199. assert( pIdx->pSchema==pTab->pSchema );
  59200. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  59201. iLargest = iIdx;
  59202. }
  59203. }
  59204. if( iLargest==0 ){
  59205. return;
  59206. }else{
  59207. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  59208. destroyRootPage(pParse, iLargest, iDb);
  59209. iDestroyed = iLargest;
  59210. }
  59211. }
  59212. #endif
  59213. }
  59214. /*
  59215. ** This routine is called to do the work of a DROP TABLE statement.
  59216. ** pName is the name of the table to be dropped.
  59217. */
  59218. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  59219. Table *pTab;
  59220. Vdbe *v;
  59221. sqlite3 *db = pParse->db;
  59222. int iDb;
  59223. if( pParse->nErr || db->mallocFailed ){
  59224. goto exit_drop_table;
  59225. }
  59226. assert( pName->nSrc==1 );
  59227. pTab = sqlite3LocateTable(pParse, isView,
  59228. pName->a[0].zName, pName->a[0].zDatabase);
  59229. if( pTab==0 ){
  59230. if( noErr ){
  59231. sqlite3ErrorClear(pParse);
  59232. }
  59233. goto exit_drop_table;
  59234. }
  59235. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  59236. assert( iDb>=0 && iDb<db->nDb );
  59237. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  59238. ** it is initialized.
  59239. */
  59240. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  59241. goto exit_drop_table;
  59242. }
  59243. #ifndef SQLITE_OMIT_AUTHORIZATION
  59244. {
  59245. int code;
  59246. const char *zTab = SCHEMA_TABLE(iDb);
  59247. const char *zDb = db->aDb[iDb].zName;
  59248. const char *zArg2 = 0;
  59249. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  59250. goto exit_drop_table;
  59251. }
  59252. if( isView ){
  59253. if( !OMIT_TEMPDB && iDb==1 ){
  59254. code = SQLITE_DROP_TEMP_VIEW;
  59255. }else{
  59256. code = SQLITE_DROP_VIEW;
  59257. }
  59258. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59259. }else if( IsVirtual(pTab) ){
  59260. code = SQLITE_DROP_VTABLE;
  59261. zArg2 = pTab->pMod->zName;
  59262. #endif
  59263. }else{
  59264. if( !OMIT_TEMPDB && iDb==1 ){
  59265. code = SQLITE_DROP_TEMP_TABLE;
  59266. }else{
  59267. code = SQLITE_DROP_TABLE;
  59268. }
  59269. }
  59270. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  59271. goto exit_drop_table;
  59272. }
  59273. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  59274. goto exit_drop_table;
  59275. }
  59276. }
  59277. #endif
  59278. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  59279. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  59280. goto exit_drop_table;
  59281. }
  59282. #ifndef SQLITE_OMIT_VIEW
  59283. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  59284. ** on a table.
  59285. */
  59286. if( isView && pTab->pSelect==0 ){
  59287. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  59288. goto exit_drop_table;
  59289. }
  59290. if( !isView && pTab->pSelect ){
  59291. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  59292. goto exit_drop_table;
  59293. }
  59294. #endif
  59295. /* Generate code to remove the table from the master table
  59296. ** on disk.
  59297. */
  59298. v = sqlite3GetVdbe(pParse);
  59299. if( v ){
  59300. Trigger *pTrigger;
  59301. Db *pDb = &db->aDb[iDb];
  59302. sqlite3BeginWriteOperation(pParse, 1, iDb);
  59303. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59304. if( IsVirtual(pTab) ){
  59305. if( v ){
  59306. sqlite3VdbeAddOp0(v, OP_VBegin);
  59307. }
  59308. }
  59309. #endif
  59310. /* Drop all triggers associated with the table being dropped. Code
  59311. ** is generated to remove entries from sqlite_master and/or
  59312. ** sqlite_temp_master if required.
  59313. */
  59314. pTrigger = pTab->pTrigger;
  59315. while( pTrigger ){
  59316. assert( pTrigger->pSchema==pTab->pSchema ||
  59317. pTrigger->pSchema==db->aDb[1].pSchema );
  59318. sqlite3DropTriggerPtr(pParse, pTrigger);
  59319. pTrigger = pTrigger->pNext;
  59320. }
  59321. #ifndef SQLITE_OMIT_AUTOINCREMENT
  59322. /* Remove any entries of the sqlite_sequence table associated with
  59323. ** the table being dropped. This is done before the table is dropped
  59324. ** at the btree level, in case the sqlite_sequence table needs to
  59325. ** move as a result of the drop (can happen in auto-vacuum mode).
  59326. */
  59327. if( pTab->tabFlags & TF_Autoincrement ){
  59328. sqlite3NestedParse(pParse,
  59329. "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
  59330. pDb->zName, pTab->zName
  59331. );
  59332. }
  59333. #endif
  59334. /* Drop all SQLITE_MASTER table and index entries that refer to the
  59335. ** table. The program name loops through the master table and deletes
  59336. ** every row that refers to a table of the same name as the one being
  59337. ** dropped. Triggers are handled seperately because a trigger can be
  59338. ** created in the temp database that refers to a table in another
  59339. ** database.
  59340. */
  59341. sqlite3NestedParse(pParse,
  59342. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  59343. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  59344. /* Drop any statistics from the sqlite_stat1 table, if it exists */
  59345. if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
  59346. sqlite3NestedParse(pParse,
  59347. "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
  59348. );
  59349. }
  59350. if( !isView && !IsVirtual(pTab) ){
  59351. destroyTable(pParse, pTab);
  59352. }
  59353. /* Remove the table entry from SQLite's internal schema and modify
  59354. ** the schema cookie.
  59355. */
  59356. if( IsVirtual(pTab) ){
  59357. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  59358. }
  59359. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  59360. sqlite3ChangeCookie(pParse, iDb);
  59361. }
  59362. sqliteViewResetAll(db, iDb);
  59363. exit_drop_table:
  59364. sqlite3SrcListDelete(db, pName);
  59365. }
  59366. /*
  59367. ** This routine is called to create a new foreign key on the table
  59368. ** currently under construction. pFromCol determines which columns
  59369. ** in the current table point to the foreign key. If pFromCol==0 then
  59370. ** connect the key to the last column inserted. pTo is the name of
  59371. ** the table referred to. pToCol is a list of tables in the other
  59372. ** pTo table that the foreign key points to. flags contains all
  59373. ** information about the conflict resolution algorithms specified
  59374. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  59375. **
  59376. ** An FKey structure is created and added to the table currently
  59377. ** under construction in the pParse->pNewTable field. The new FKey
  59378. ** is not linked into db->aFKey at this point - that does not happen
  59379. ** until sqlite3EndTable().
  59380. **
  59381. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  59382. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  59383. */
  59384. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  59385. Parse *pParse, /* Parsing context */
  59386. ExprList *pFromCol, /* Columns in this table that point to other table */
  59387. Token *pTo, /* Name of the other table */
  59388. ExprList *pToCol, /* Columns in the other table */
  59389. int flags /* Conflict resolution algorithms. */
  59390. ){
  59391. sqlite3 *db = pParse->db;
  59392. #ifndef SQLITE_OMIT_FOREIGN_KEY
  59393. FKey *pFKey = 0;
  59394. Table *p = pParse->pNewTable;
  59395. int nByte;
  59396. int i;
  59397. int nCol;
  59398. char *z;
  59399. assert( pTo!=0 );
  59400. if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
  59401. if( pFromCol==0 ){
  59402. int iCol = p->nCol-1;
  59403. if( iCol<0 ) goto fk_end;
  59404. if( pToCol && pToCol->nExpr!=1 ){
  59405. sqlite3ErrorMsg(pParse, "foreign key on %s"
  59406. " should reference only one column of table %T",
  59407. p->aCol[iCol].zName, pTo);
  59408. goto fk_end;
  59409. }
  59410. nCol = 1;
  59411. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  59412. sqlite3ErrorMsg(pParse,
  59413. "number of columns in foreign key does not match the number of "
  59414. "columns in the referenced table");
  59415. goto fk_end;
  59416. }else{
  59417. nCol = pFromCol->nExpr;
  59418. }
  59419. nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  59420. if( pToCol ){
  59421. for(i=0; i<pToCol->nExpr; i++){
  59422. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  59423. }
  59424. }
  59425. pFKey = sqlite3DbMallocZero(db, nByte );
  59426. if( pFKey==0 ){
  59427. goto fk_end;
  59428. }
  59429. pFKey->pFrom = p;
  59430. pFKey->pNextFrom = p->pFKey;
  59431. z = (char*)&pFKey[1];
  59432. pFKey->aCol = (struct sColMap*)z;
  59433. z += sizeof(struct sColMap)*nCol;
  59434. pFKey->zTo = z;
  59435. memcpy(z, pTo->z, pTo->n);
  59436. z[pTo->n] = 0;
  59437. z += pTo->n+1;
  59438. pFKey->pNextTo = 0;
  59439. pFKey->nCol = nCol;
  59440. if( pFromCol==0 ){
  59441. pFKey->aCol[0].iFrom = p->nCol-1;
  59442. }else{
  59443. for(i=0; i<nCol; i++){
  59444. int j;
  59445. for(j=0; j<p->nCol; j++){
  59446. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  59447. pFKey->aCol[i].iFrom = j;
  59448. break;
  59449. }
  59450. }
  59451. if( j>=p->nCol ){
  59452. sqlite3ErrorMsg(pParse,
  59453. "unknown column \"%s\" in foreign key definition",
  59454. pFromCol->a[i].zName);
  59455. goto fk_end;
  59456. }
  59457. }
  59458. }
  59459. if( pToCol ){
  59460. for(i=0; i<nCol; i++){
  59461. int n = sqlite3Strlen30(pToCol->a[i].zName);
  59462. pFKey->aCol[i].zCol = z;
  59463. memcpy(z, pToCol->a[i].zName, n);
  59464. z[n] = 0;
  59465. z += n+1;
  59466. }
  59467. }
  59468. pFKey->isDeferred = 0;
  59469. pFKey->deleteConf = (u8)(flags & 0xff);
  59470. pFKey->updateConf = (u8)((flags >> 8 ) & 0xff);
  59471. pFKey->insertConf = (u8)((flags >> 16 ) & 0xff);
  59472. /* Link the foreign key to the table as the last step.
  59473. */
  59474. p->pFKey = pFKey;
  59475. pFKey = 0;
  59476. fk_end:
  59477. sqlite3DbFree(db, pFKey);
  59478. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  59479. sqlite3ExprListDelete(db, pFromCol);
  59480. sqlite3ExprListDelete(db, pToCol);
  59481. }
  59482. /*
  59483. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  59484. ** clause is seen as part of a foreign key definition. The isDeferred
  59485. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  59486. ** The behavior of the most recently created foreign key is adjusted
  59487. ** accordingly.
  59488. */
  59489. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  59490. #ifndef SQLITE_OMIT_FOREIGN_KEY
  59491. Table *pTab;
  59492. FKey *pFKey;
  59493. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  59494. assert( isDeferred==0 || isDeferred==1 );
  59495. pFKey->isDeferred = (u8)isDeferred;
  59496. #endif
  59497. }
  59498. /*
  59499. ** Generate code that will erase and refill index *pIdx. This is
  59500. ** used to initialize a newly created index or to recompute the
  59501. ** content of an index in response to a REINDEX command.
  59502. **
  59503. ** if memRootPage is not negative, it means that the index is newly
  59504. ** created. The register specified by memRootPage contains the
  59505. ** root page number of the index. If memRootPage is negative, then
  59506. ** the index already exists and must be cleared before being refilled and
  59507. ** the root page number of the index is taken from pIndex->tnum.
  59508. */
  59509. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  59510. Table *pTab = pIndex->pTable; /* The table that is indexed */
  59511. int iTab = pParse->nTab; /* Btree cursor used for pTab */
  59512. int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
  59513. int addr1; /* Address of top of loop */
  59514. int tnum; /* Root page of index */
  59515. Vdbe *v; /* Generate code into this virtual machine */
  59516. KeyInfo *pKey; /* KeyInfo for index */
  59517. int regIdxKey; /* Registers containing the index key */
  59518. int regRecord; /* Register holding assemblied index record */
  59519. sqlite3 *db = pParse->db; /* The database connection */
  59520. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  59521. #ifndef SQLITE_OMIT_AUTHORIZATION
  59522. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  59523. db->aDb[iDb].zName ) ){
  59524. return;
  59525. }
  59526. #endif
  59527. /* Require a write-lock on the table to perform this operation */
  59528. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  59529. v = sqlite3GetVdbe(pParse);
  59530. if( v==0 ) return;
  59531. if( memRootPage>=0 ){
  59532. tnum = memRootPage;
  59533. }else{
  59534. tnum = pIndex->tnum;
  59535. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  59536. }
  59537. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  59538. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  59539. (char *)pKey, P4_KEYINFO_HANDOFF);
  59540. if( memRootPage>=0 ){
  59541. sqlite3VdbeChangeP5(v, 1);
  59542. }
  59543. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  59544. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  59545. regRecord = sqlite3GetTempReg(pParse);
  59546. regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
  59547. if( pIndex->onError!=OE_None ){
  59548. int j1, j2;
  59549. int regRowid;
  59550. regRowid = regIdxKey + pIndex->nColumn;
  59551. j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
  59552. j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
  59553. 0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
  59554. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
  59555. "indexed columns are not unique", P4_STATIC);
  59556. sqlite3VdbeJumpHere(v, j1);
  59557. sqlite3VdbeJumpHere(v, j2);
  59558. }
  59559. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  59560. sqlite3ReleaseTempReg(pParse, regRecord);
  59561. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  59562. sqlite3VdbeJumpHere(v, addr1);
  59563. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  59564. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  59565. }
  59566. /*
  59567. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  59568. ** and pTblList is the name of the table that is to be indexed. Both will
  59569. ** be NULL for a primary key or an index that is created to satisfy a
  59570. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  59571. ** as the table to be indexed. pParse->pNewTable is a table that is
  59572. ** currently being constructed by a CREATE TABLE statement.
  59573. **
  59574. ** pList is a list of columns to be indexed. pList will be NULL if this
  59575. ** is a primary key or unique-constraint on the most recent column added
  59576. ** to the table currently under construction.
  59577. */
  59578. SQLITE_PRIVATE void sqlite3CreateIndex(
  59579. Parse *pParse, /* All information about this parse */
  59580. Token *pName1, /* First part of index name. May be NULL */
  59581. Token *pName2, /* Second part of index name. May be NULL */
  59582. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  59583. ExprList *pList, /* A list of columns to be indexed */
  59584. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  59585. Token *pStart, /* The CREATE token that begins this statement */
  59586. Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
  59587. int sortOrder, /* Sort order of primary key when pList==NULL */
  59588. int ifNotExist /* Omit error if index already exists */
  59589. ){
  59590. Table *pTab = 0; /* Table to be indexed */
  59591. Index *pIndex = 0; /* The index to be created */
  59592. char *zName = 0; /* Name of the index */
  59593. int nName; /* Number of characters in zName */
  59594. int i, j;
  59595. Token nullId; /* Fake token for an empty ID list */
  59596. DbFixer sFix; /* For assigning database names to pTable */
  59597. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  59598. sqlite3 *db = pParse->db;
  59599. Db *pDb; /* The specific table containing the indexed database */
  59600. int iDb; /* Index of the database that is being written */
  59601. Token *pName = 0; /* Unqualified name of the index to create */
  59602. struct ExprList_item *pListItem; /* For looping over pList */
  59603. int nCol;
  59604. int nExtra = 0;
  59605. char *zExtra;
  59606. if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
  59607. goto exit_create_index;
  59608. }
  59609. /*
  59610. ** Find the table that is to be indexed. Return early if not found.
  59611. */
  59612. if( pTblName!=0 ){
  59613. /* Use the two-part index name to determine the database
  59614. ** to search for the table. 'Fix' the table name to this db
  59615. ** before looking up the table.
  59616. */
  59617. assert( pName1 && pName2 );
  59618. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  59619. if( iDb<0 ) goto exit_create_index;
  59620. #ifndef SQLITE_OMIT_TEMPDB
  59621. /* If the index name was unqualified, check if the the table
  59622. ** is a temp table. If so, set the database to 1. Do not do this
  59623. ** if initialising a database schema.
  59624. */
  59625. if( !db->init.busy ){
  59626. pTab = sqlite3SrcListLookup(pParse, pTblName);
  59627. if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  59628. iDb = 1;
  59629. }
  59630. }
  59631. #endif
  59632. if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
  59633. sqlite3FixSrcList(&sFix, pTblName)
  59634. ){
  59635. /* Because the parser constructs pTblName from a single identifier,
  59636. ** sqlite3FixSrcList can never fail. */
  59637. assert(0);
  59638. }
  59639. pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
  59640. pTblName->a[0].zDatabase);
  59641. if( !pTab || db->mallocFailed ) goto exit_create_index;
  59642. assert( db->aDb[iDb].pSchema==pTab->pSchema );
  59643. }else{
  59644. assert( pName==0 );
  59645. pTab = pParse->pNewTable;
  59646. if( !pTab ) goto exit_create_index;
  59647. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  59648. }
  59649. pDb = &db->aDb[iDb];
  59650. if( pTab==0 || pParse->nErr ) goto exit_create_index;
  59651. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  59652. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  59653. goto exit_create_index;
  59654. }
  59655. #ifndef SQLITE_OMIT_VIEW
  59656. if( pTab->pSelect ){
  59657. sqlite3ErrorMsg(pParse, "views may not be indexed");
  59658. goto exit_create_index;
  59659. }
  59660. #endif
  59661. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59662. if( IsVirtual(pTab) ){
  59663. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  59664. goto exit_create_index;
  59665. }
  59666. #endif
  59667. /*
  59668. ** Find the name of the index. Make sure there is not already another
  59669. ** index or table with the same name.
  59670. **
  59671. ** Exception: If we are reading the names of permanent indices from the
  59672. ** sqlite_master table (because some other process changed the schema) and
  59673. ** one of the index names collides with the name of a temporary table or
  59674. ** index, then we will continue to process this index.
  59675. **
  59676. ** If pName==0 it means that we are
  59677. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  59678. ** own name.
  59679. */
  59680. if( pName ){
  59681. zName = sqlite3NameFromToken(db, pName);
  59682. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
  59683. if( zName==0 ) goto exit_create_index;
  59684. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  59685. goto exit_create_index;
  59686. }
  59687. if( !db->init.busy ){
  59688. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
  59689. if( sqlite3FindTable(db, zName, 0)!=0 ){
  59690. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  59691. goto exit_create_index;
  59692. }
  59693. }
  59694. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  59695. if( !ifNotExist ){
  59696. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  59697. }
  59698. goto exit_create_index;
  59699. }
  59700. }else{
  59701. int n;
  59702. Index *pLoop;
  59703. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  59704. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  59705. if( zName==0 ){
  59706. goto exit_create_index;
  59707. }
  59708. }
  59709. /* Check for authorization to create an index.
  59710. */
  59711. #ifndef SQLITE_OMIT_AUTHORIZATION
  59712. {
  59713. const char *zDb = pDb->zName;
  59714. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  59715. goto exit_create_index;
  59716. }
  59717. i = SQLITE_CREATE_INDEX;
  59718. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  59719. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  59720. goto exit_create_index;
  59721. }
  59722. }
  59723. #endif
  59724. /* If pList==0, it means this routine was called to make a primary
  59725. ** key out of the last column added to the table under construction.
  59726. ** So create a fake list to simulate this.
  59727. */
  59728. if( pList==0 ){
  59729. nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
  59730. nullId.n = sqlite3Strlen30((char*)nullId.z);
  59731. pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
  59732. if( pList==0 ) goto exit_create_index;
  59733. pList->a[0].sortOrder = (u8)sortOrder;
  59734. }
  59735. /* Figure out how many bytes of space are required to store explicitly
  59736. ** specified collation sequence names.
  59737. */
  59738. for(i=0; i<pList->nExpr; i++){
  59739. Expr *pExpr;
  59740. CollSeq *pColl;
  59741. if( (pExpr = pList->a[i].pExpr)!=0 && (pColl = pExpr->pColl)!=0 ){
  59742. nExtra += (1 + sqlite3Strlen30(pColl->zName));
  59743. }
  59744. }
  59745. /*
  59746. ** Allocate the index structure.
  59747. */
  59748. nName = sqlite3Strlen30(zName);
  59749. nCol = pList->nExpr;
  59750. pIndex = sqlite3DbMallocZero(db,
  59751. sizeof(Index) + /* Index structure */
  59752. sizeof(int)*nCol + /* Index.aiColumn */
  59753. sizeof(int)*(nCol+1) + /* Index.aiRowEst */
  59754. sizeof(char *)*nCol + /* Index.azColl */
  59755. sizeof(u8)*nCol + /* Index.aSortOrder */
  59756. nName + 1 + /* Index.zName */
  59757. nExtra /* Collation sequence names */
  59758. );
  59759. if( db->mallocFailed ){
  59760. goto exit_create_index;
  59761. }
  59762. pIndex->azColl = (char**)(&pIndex[1]);
  59763. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  59764. pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
  59765. pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
  59766. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  59767. zExtra = (char *)(&pIndex->zName[nName+1]);
  59768. memcpy(pIndex->zName, zName, nName+1);
  59769. pIndex->pTable = pTab;
  59770. pIndex->nColumn = pList->nExpr;
  59771. pIndex->onError = (u8)onError;
  59772. pIndex->autoIndex = (u8)(pName==0);
  59773. pIndex->pSchema = db->aDb[iDb].pSchema;
  59774. /* Check to see if we should honor DESC requests on index columns
  59775. */
  59776. if( pDb->pSchema->file_format>=4 ){
  59777. sortOrderMask = -1; /* Honor DESC */
  59778. }else{
  59779. sortOrderMask = 0; /* Ignore DESC */
  59780. }
  59781. /* Scan the names of the columns of the table to be indexed and
  59782. ** load the column indices into the Index structure. Report an error
  59783. ** if any column is not found.
  59784. */
  59785. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  59786. const char *zColName = pListItem->zName;
  59787. Column *pTabCol;
  59788. int requestedSortOrder;
  59789. char *zColl; /* Collation sequence name */
  59790. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  59791. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  59792. }
  59793. if( j>=pTab->nCol ){
  59794. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  59795. pTab->zName, zColName);
  59796. goto exit_create_index;
  59797. }
  59798. /* TODO: Add a test to make sure that the same column is not named
  59799. ** more than once within the same index. Only the first instance of
  59800. ** the column will ever be used by the optimizer. Note that using the
  59801. ** same column more than once cannot be an error because that would
  59802. ** break backwards compatibility - it needs to be a warning.
  59803. */
  59804. pIndex->aiColumn[i] = j;
  59805. if( pListItem->pExpr && pListItem->pExpr->pColl ){
  59806. assert( pListItem->pExpr->pColl );
  59807. zColl = zExtra;
  59808. sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
  59809. zExtra += (sqlite3Strlen30(zColl) + 1);
  59810. }else{
  59811. zColl = pTab->aCol[j].zColl;
  59812. if( !zColl ){
  59813. zColl = db->pDfltColl->zName;
  59814. }
  59815. }
  59816. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
  59817. goto exit_create_index;
  59818. }
  59819. pIndex->azColl[i] = zColl;
  59820. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  59821. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  59822. }
  59823. sqlite3DefaultRowEst(pIndex);
  59824. if( pTab==pParse->pNewTable ){
  59825. /* This routine has been called to create an automatic index as a
  59826. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  59827. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  59828. ** i.e. one of:
  59829. **
  59830. ** CREATE TABLE t(x PRIMARY KEY, y);
  59831. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  59832. **
  59833. ** Either way, check to see if the table already has such an index. If
  59834. ** so, don't bother creating this one. This only applies to
  59835. ** automatically created indices. Users can do as they wish with
  59836. ** explicit indices.
  59837. */
  59838. Index *pIdx;
  59839. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  59840. int k;
  59841. assert( pIdx->onError!=OE_None );
  59842. assert( pIdx->autoIndex );
  59843. assert( pIndex->onError!=OE_None );
  59844. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  59845. for(k=0; k<pIdx->nColumn; k++){
  59846. const char *z1 = pIdx->azColl[k];
  59847. const char *z2 = pIndex->azColl[k];
  59848. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  59849. if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
  59850. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  59851. }
  59852. if( k==pIdx->nColumn ){
  59853. if( pIdx->onError!=pIndex->onError ){
  59854. /* This constraint creates the same index as a previous
  59855. ** constraint specified somewhere in the CREATE TABLE statement.
  59856. ** However the ON CONFLICT clauses are different. If both this
  59857. ** constraint and the previous equivalent constraint have explicit
  59858. ** ON CONFLICT clauses this is an error. Otherwise, use the
  59859. ** explicitly specified behaviour for the index.
  59860. */
  59861. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  59862. sqlite3ErrorMsg(pParse,
  59863. "conflicting ON CONFLICT clauses specified", 0);
  59864. }
  59865. if( pIdx->onError==OE_Default ){
  59866. pIdx->onError = pIndex->onError;
  59867. }
  59868. }
  59869. goto exit_create_index;
  59870. }
  59871. }
  59872. }
  59873. /* Link the new Index structure to its table and to the other
  59874. ** in-memory database structures.
  59875. */
  59876. if( db->init.busy ){
  59877. Index *p;
  59878. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  59879. pIndex->zName, sqlite3Strlen30(pIndex->zName)+1,
  59880. pIndex);
  59881. if( p ){
  59882. assert( p==pIndex ); /* Malloc must have failed */
  59883. db->mallocFailed = 1;
  59884. goto exit_create_index;
  59885. }
  59886. db->flags |= SQLITE_InternChanges;
  59887. if( pTblName!=0 ){
  59888. pIndex->tnum = db->init.newTnum;
  59889. }
  59890. }
  59891. /* If the db->init.busy is 0 then create the index on disk. This
  59892. ** involves writing the index into the master table and filling in the
  59893. ** index with the current table contents.
  59894. **
  59895. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  59896. ** command. db->init.busy is 1 when a database is opened and
  59897. ** CREATE INDEX statements are read out of the master table. In
  59898. ** the latter case the index already exists on disk, which is why
  59899. ** we don't want to recreate it.
  59900. **
  59901. ** If pTblName==0 it means this index is generated as a primary key
  59902. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  59903. ** has just been created, it contains no data and the index initialization
  59904. ** step can be skipped.
  59905. */
  59906. else if( db->init.busy==0 ){
  59907. Vdbe *v;
  59908. char *zStmt;
  59909. int iMem = ++pParse->nMem;
  59910. v = sqlite3GetVdbe(pParse);
  59911. if( v==0 ) goto exit_create_index;
  59912. /* Create the rootpage for the index
  59913. */
  59914. sqlite3BeginWriteOperation(pParse, 1, iDb);
  59915. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  59916. /* Gather the complete text of the CREATE INDEX statement into
  59917. ** the zStmt variable
  59918. */
  59919. if( pStart && pEnd ){
  59920. /* A named index with an explicit CREATE INDEX statement */
  59921. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  59922. onError==OE_None ? "" : " UNIQUE",
  59923. pEnd->z - pName->z + 1,
  59924. pName->z);
  59925. }else{
  59926. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  59927. /* zStmt = sqlite3MPrintf(""); */
  59928. zStmt = 0;
  59929. }
  59930. /* Add an entry in sqlite_master for this index
  59931. */
  59932. sqlite3NestedParse(pParse,
  59933. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  59934. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  59935. pIndex->zName,
  59936. pTab->zName,
  59937. iMem,
  59938. zStmt
  59939. );
  59940. sqlite3DbFree(db, zStmt);
  59941. /* Fill the index with data and reparse the schema. Code an OP_Expire
  59942. ** to invalidate all pre-compiled statements.
  59943. */
  59944. if( pTblName ){
  59945. sqlite3RefillIndex(pParse, pIndex, iMem);
  59946. sqlite3ChangeCookie(pParse, iDb);
  59947. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
  59948. sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
  59949. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  59950. }
  59951. }
  59952. /* When adding an index to the list of indices for a table, make
  59953. ** sure all indices labeled OE_Replace come after all those labeled
  59954. ** OE_Ignore. This is necessary for the correct operation of UPDATE
  59955. ** and INSERT.
  59956. */
  59957. if( db->init.busy || pTblName==0 ){
  59958. if( onError!=OE_Replace || pTab->pIndex==0
  59959. || pTab->pIndex->onError==OE_Replace){
  59960. pIndex->pNext = pTab->pIndex;
  59961. pTab->pIndex = pIndex;
  59962. }else{
  59963. Index *pOther = pTab->pIndex;
  59964. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  59965. pOther = pOther->pNext;
  59966. }
  59967. pIndex->pNext = pOther->pNext;
  59968. pOther->pNext = pIndex;
  59969. }
  59970. pIndex = 0;
  59971. }
  59972. /* Clean up before exiting */
  59973. exit_create_index:
  59974. if( pIndex ){
  59975. freeIndex(pIndex);
  59976. }
  59977. sqlite3ExprListDelete(db, pList);
  59978. sqlite3SrcListDelete(db, pTblName);
  59979. sqlite3DbFree(db, zName);
  59980. return;
  59981. }
  59982. /*
  59983. ** Generate code to make sure the file format number is at least minFormat.
  59984. ** The generated code will increase the file format number if necessary.
  59985. */
  59986. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  59987. Vdbe *v;
  59988. v = sqlite3GetVdbe(pParse);
  59989. if( v ){
  59990. int r1 = sqlite3GetTempReg(pParse);
  59991. int r2 = sqlite3GetTempReg(pParse);
  59992. int j1;
  59993. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
  59994. sqlite3VdbeUsesBtree(v, iDb);
  59995. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  59996. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  59997. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
  59998. sqlite3VdbeJumpHere(v, j1);
  59999. sqlite3ReleaseTempReg(pParse, r1);
  60000. sqlite3ReleaseTempReg(pParse, r2);
  60001. }
  60002. }
  60003. /*
  60004. ** Fill the Index.aiRowEst[] array with default information - information
  60005. ** to be used when we have not run the ANALYZE command.
  60006. **
  60007. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  60008. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  60009. ** number of rows in the table that match any particular value of the
  60010. ** first column of the index. aiRowEst[2] is an estimate of the number
  60011. ** of rows that match any particular combiniation of the first 2 columns
  60012. ** of the index. And so forth. It must always be the case that
  60013. *
  60014. ** aiRowEst[N]<=aiRowEst[N-1]
  60015. ** aiRowEst[N]>=1
  60016. **
  60017. ** Apart from that, we have little to go on besides intuition as to
  60018. ** how aiRowEst[] should be initialized. The numbers generated here
  60019. ** are based on typical values found in actual indices.
  60020. */
  60021. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  60022. unsigned *a = pIdx->aiRowEst;
  60023. int i;
  60024. assert( a!=0 );
  60025. a[0] = 1000000;
  60026. for(i=pIdx->nColumn; i>=5; i--){
  60027. a[i] = 5;
  60028. }
  60029. while( i>=1 ){
  60030. a[i] = 11 - i;
  60031. i--;
  60032. }
  60033. if( pIdx->onError!=OE_None ){
  60034. a[pIdx->nColumn] = 1;
  60035. }
  60036. }
  60037. /*
  60038. ** This routine will drop an existing named index. This routine
  60039. ** implements the DROP INDEX statement.
  60040. */
  60041. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  60042. Index *pIndex;
  60043. Vdbe *v;
  60044. sqlite3 *db = pParse->db;
  60045. int iDb;
  60046. if( pParse->nErr || db->mallocFailed ){
  60047. goto exit_drop_index;
  60048. }
  60049. assert( pName->nSrc==1 );
  60050. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  60051. goto exit_drop_index;
  60052. }
  60053. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  60054. if( pIndex==0 ){
  60055. if( !ifExists ){
  60056. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  60057. }
  60058. pParse->checkSchema = 1;
  60059. goto exit_drop_index;
  60060. }
  60061. if( pIndex->autoIndex ){
  60062. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  60063. "or PRIMARY KEY constraint cannot be dropped", 0);
  60064. goto exit_drop_index;
  60065. }
  60066. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  60067. #ifndef SQLITE_OMIT_AUTHORIZATION
  60068. {
  60069. int code = SQLITE_DROP_INDEX;
  60070. Table *pTab = pIndex->pTable;
  60071. const char *zDb = db->aDb[iDb].zName;
  60072. const char *zTab = SCHEMA_TABLE(iDb);
  60073. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  60074. goto exit_drop_index;
  60075. }
  60076. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  60077. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  60078. goto exit_drop_index;
  60079. }
  60080. }
  60081. #endif
  60082. /* Generate code to remove the index and from the master table */
  60083. v = sqlite3GetVdbe(pParse);
  60084. if( v ){
  60085. sqlite3BeginWriteOperation(pParse, 1, iDb);
  60086. sqlite3NestedParse(pParse,
  60087. "DELETE FROM %Q.%s WHERE name=%Q",
  60088. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  60089. pIndex->zName
  60090. );
  60091. if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
  60092. sqlite3NestedParse(pParse,
  60093. "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
  60094. db->aDb[iDb].zName, pIndex->zName
  60095. );
  60096. }
  60097. sqlite3ChangeCookie(pParse, iDb);
  60098. destroyRootPage(pParse, pIndex->tnum, iDb);
  60099. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  60100. }
  60101. exit_drop_index:
  60102. sqlite3SrcListDelete(db, pName);
  60103. }
  60104. /*
  60105. ** pArray is a pointer to an array of objects. Each object in the
  60106. ** array is szEntry bytes in size. This routine allocates a new
  60107. ** object on the end of the array.
  60108. **
  60109. ** *pnEntry is the number of entries already in use. *pnAlloc is
  60110. ** the previously allocated size of the array. initSize is the
  60111. ** suggested initial array size allocation.
  60112. **
  60113. ** The index of the new entry is returned in *pIdx.
  60114. **
  60115. ** This routine returns a pointer to the array of objects. This
  60116. ** might be the same as the pArray parameter or it might be a different
  60117. ** pointer if the array was resized.
  60118. */
  60119. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  60120. sqlite3 *db, /* Connection to notify of malloc failures */
  60121. void *pArray, /* Array of objects. Might be reallocated */
  60122. int szEntry, /* Size of each object in the array */
  60123. int initSize, /* Suggested initial allocation, in elements */
  60124. int *pnEntry, /* Number of objects currently in use */
  60125. int *pnAlloc, /* Current size of the allocation, in elements */
  60126. int *pIdx /* Write the index of a new slot here */
  60127. ){
  60128. char *z;
  60129. if( *pnEntry >= *pnAlloc ){
  60130. void *pNew;
  60131. int newSize;
  60132. newSize = (*pnAlloc)*2 + initSize;
  60133. pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
  60134. if( pNew==0 ){
  60135. *pIdx = -1;
  60136. return pArray;
  60137. }
  60138. *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
  60139. pArray = pNew;
  60140. }
  60141. z = (char*)pArray;
  60142. memset(&z[*pnEntry * szEntry], 0, szEntry);
  60143. *pIdx = *pnEntry;
  60144. ++*pnEntry;
  60145. return pArray;
  60146. }
  60147. /*
  60148. ** Append a new element to the given IdList. Create a new IdList if
  60149. ** need be.
  60150. **
  60151. ** A new IdList is returned, or NULL if malloc() fails.
  60152. */
  60153. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  60154. int i;
  60155. if( pList==0 ){
  60156. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  60157. if( pList==0 ) return 0;
  60158. pList->nAlloc = 0;
  60159. }
  60160. pList->a = sqlite3ArrayAllocate(
  60161. db,
  60162. pList->a,
  60163. sizeof(pList->a[0]),
  60164. 5,
  60165. &pList->nId,
  60166. &pList->nAlloc,
  60167. &i
  60168. );
  60169. if( i<0 ){
  60170. sqlite3IdListDelete(db, pList);
  60171. return 0;
  60172. }
  60173. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  60174. return pList;
  60175. }
  60176. /*
  60177. ** Delete an IdList.
  60178. */
  60179. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  60180. int i;
  60181. if( pList==0 ) return;
  60182. for(i=0; i<pList->nId; i++){
  60183. sqlite3DbFree(db, pList->a[i].zName);
  60184. }
  60185. sqlite3DbFree(db, pList->a);
  60186. sqlite3DbFree(db, pList);
  60187. }
  60188. /*
  60189. ** Return the index in pList of the identifier named zId. Return -1
  60190. ** if not found.
  60191. */
  60192. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  60193. int i;
  60194. if( pList==0 ) return -1;
  60195. for(i=0; i<pList->nId; i++){
  60196. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  60197. }
  60198. return -1;
  60199. }
  60200. /*
  60201. ** Expand the space allocated for the given SrcList object by
  60202. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  60203. ** New slots are zeroed.
  60204. **
  60205. ** For example, suppose a SrcList initially contains two entries: A,B.
  60206. ** To append 3 new entries onto the end, do this:
  60207. **
  60208. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  60209. **
  60210. ** After the call above it would contain: A, B, nil, nil, nil.
  60211. ** If the iStart argument had been 1 instead of 2, then the result
  60212. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  60213. ** the iStart value would be 0. The result then would
  60214. ** be: nil, nil, nil, A, B.
  60215. **
  60216. ** If a memory allocation fails the SrcList is unchanged. The
  60217. ** db->mallocFailed flag will be set to true.
  60218. */
  60219. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  60220. sqlite3 *db, /* Database connection to notify of OOM errors */
  60221. SrcList *pSrc, /* The SrcList to be enlarged */
  60222. int nExtra, /* Number of new slots to add to pSrc->a[] */
  60223. int iStart /* Index in pSrc->a[] of first new slot */
  60224. ){
  60225. int i;
  60226. /* Sanity checking on calling parameters */
  60227. assert( iStart>=0 );
  60228. assert( nExtra>=1 );
  60229. if( pSrc==0 || iStart>pSrc->nSrc ){
  60230. assert( db->mallocFailed );
  60231. return pSrc;
  60232. }
  60233. /* Allocate additional space if needed */
  60234. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  60235. SrcList *pNew;
  60236. int nAlloc = pSrc->nSrc+nExtra;
  60237. int nGot;
  60238. pNew = sqlite3DbRealloc(db, pSrc,
  60239. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  60240. if( pNew==0 ){
  60241. assert( db->mallocFailed );
  60242. return pSrc;
  60243. }
  60244. pSrc = pNew;
  60245. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  60246. pSrc->nAlloc = (u16)nGot;
  60247. }
  60248. /* Move existing slots that come after the newly inserted slots
  60249. ** out of the way */
  60250. for(i=pSrc->nSrc-1; i>=iStart; i--){
  60251. pSrc->a[i+nExtra] = pSrc->a[i];
  60252. }
  60253. pSrc->nSrc += (i16)nExtra;
  60254. /* Zero the newly allocated slots */
  60255. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  60256. for(i=iStart; i<iStart+nExtra; i++){
  60257. pSrc->a[i].iCursor = -1;
  60258. }
  60259. /* Return a pointer to the enlarged SrcList */
  60260. return pSrc;
  60261. }
  60262. /*
  60263. ** Append a new table name to the given SrcList. Create a new SrcList if
  60264. ** need be. A new entry is created in the SrcList even if pToken is NULL.
  60265. **
  60266. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  60267. ** SrcList might be the same as the SrcList that was input or it might be
  60268. ** a new one. If an OOM error does occurs, then the prior value of pList
  60269. ** that is input to this routine is automatically freed.
  60270. **
  60271. ** If pDatabase is not null, it means that the table has an optional
  60272. ** database name prefix. Like this: "database.table". The pDatabase
  60273. ** points to the table name and the pTable points to the database name.
  60274. ** The SrcList.a[].zName field is filled with the table name which might
  60275. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  60276. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  60277. ** or with NULL if no database is specified.
  60278. **
  60279. ** In other words, if call like this:
  60280. **
  60281. ** sqlite3SrcListAppend(D,A,B,0);
  60282. **
  60283. ** Then B is a table name and the database name is unspecified. If called
  60284. ** like this:
  60285. **
  60286. ** sqlite3SrcListAppend(D,A,B,C);
  60287. **
  60288. ** Then C is the table name and B is the database name.
  60289. */
  60290. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  60291. sqlite3 *db, /* Connection to notify of malloc failures */
  60292. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  60293. Token *pTable, /* Table to append */
  60294. Token *pDatabase /* Database of the table */
  60295. ){
  60296. struct SrcList_item *pItem;
  60297. if( pList==0 ){
  60298. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  60299. if( pList==0 ) return 0;
  60300. pList->nAlloc = 1;
  60301. }
  60302. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  60303. if( db->mallocFailed ){
  60304. sqlite3SrcListDelete(db, pList);
  60305. return 0;
  60306. }
  60307. pItem = &pList->a[pList->nSrc-1];
  60308. if( pDatabase && pDatabase->z==0 ){
  60309. pDatabase = 0;
  60310. }
  60311. if( pDatabase && pTable ){
  60312. Token *pTemp = pDatabase;
  60313. pDatabase = pTable;
  60314. pTable = pTemp;
  60315. }
  60316. pItem->zName = sqlite3NameFromToken(db, pTable);
  60317. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  60318. return pList;
  60319. }
  60320. /*
  60321. ** Assign VdbeCursor index numbers to all tables in a SrcList
  60322. */
  60323. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  60324. int i;
  60325. struct SrcList_item *pItem;
  60326. assert(pList || pParse->db->mallocFailed );
  60327. if( pList ){
  60328. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  60329. if( pItem->iCursor>=0 ) break;
  60330. pItem->iCursor = pParse->nTab++;
  60331. if( pItem->pSelect ){
  60332. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  60333. }
  60334. }
  60335. }
  60336. }
  60337. /*
  60338. ** Delete an entire SrcList including all its substructure.
  60339. */
  60340. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  60341. int i;
  60342. struct SrcList_item *pItem;
  60343. if( pList==0 ) return;
  60344. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  60345. sqlite3DbFree(db, pItem->zDatabase);
  60346. sqlite3DbFree(db, pItem->zName);
  60347. sqlite3DbFree(db, pItem->zAlias);
  60348. sqlite3DbFree(db, pItem->zIndex);
  60349. sqlite3DeleteTable(pItem->pTab);
  60350. sqlite3SelectDelete(db, pItem->pSelect);
  60351. sqlite3ExprDelete(db, pItem->pOn);
  60352. sqlite3IdListDelete(db, pItem->pUsing);
  60353. }
  60354. sqlite3DbFree(db, pList);
  60355. }
  60356. /*
  60357. ** This routine is called by the parser to add a new term to the
  60358. ** end of a growing FROM clause. The "p" parameter is the part of
  60359. ** the FROM clause that has already been constructed. "p" is NULL
  60360. ** if this is the first term of the FROM clause. pTable and pDatabase
  60361. ** are the name of the table and database named in the FROM clause term.
  60362. ** pDatabase is NULL if the database name qualifier is missing - the
  60363. ** usual case. If the term has a alias, then pAlias points to the
  60364. ** alias token. If the term is a subquery, then pSubquery is the
  60365. ** SELECT statement that the subquery encodes. The pTable and
  60366. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  60367. ** parameters are the content of the ON and USING clauses.
  60368. **
  60369. ** Return a new SrcList which encodes is the FROM with the new
  60370. ** term added.
  60371. */
  60372. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  60373. Parse *pParse, /* Parsing context */
  60374. SrcList *p, /* The left part of the FROM clause already seen */
  60375. Token *pTable, /* Name of the table to add to the FROM clause */
  60376. Token *pDatabase, /* Name of the database containing pTable */
  60377. Token *pAlias, /* The right-hand side of the AS subexpression */
  60378. Select *pSubquery, /* A subquery used in place of a table name */
  60379. Expr *pOn, /* The ON clause of a join */
  60380. IdList *pUsing /* The USING clause of a join */
  60381. ){
  60382. struct SrcList_item *pItem;
  60383. sqlite3 *db = pParse->db;
  60384. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  60385. if( p==0 || p->nSrc==0 ){
  60386. sqlite3ExprDelete(db, pOn);
  60387. sqlite3IdListDelete(db, pUsing);
  60388. sqlite3SelectDelete(db, pSubquery);
  60389. return p;
  60390. }
  60391. pItem = &p->a[p->nSrc-1];
  60392. if( pAlias && pAlias->n ){
  60393. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  60394. }
  60395. pItem->pSelect = pSubquery;
  60396. pItem->pOn = pOn;
  60397. pItem->pUsing = pUsing;
  60398. return p;
  60399. }
  60400. /*
  60401. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  60402. ** element of the source-list passed as the second argument.
  60403. */
  60404. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  60405. if( pIndexedBy && p && p->nSrc>0 ){
  60406. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  60407. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  60408. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  60409. /* A "NOT INDEXED" clause was supplied. See parse.y
  60410. ** construct "indexed_opt" for details. */
  60411. pItem->notIndexed = 1;
  60412. }else{
  60413. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  60414. }
  60415. }
  60416. }
  60417. /*
  60418. ** When building up a FROM clause in the parser, the join operator
  60419. ** is initially attached to the left operand. But the code generator
  60420. ** expects the join operator to be on the right operand. This routine
  60421. ** Shifts all join operators from left to right for an entire FROM
  60422. ** clause.
  60423. **
  60424. ** Example: Suppose the join is like this:
  60425. **
  60426. ** A natural cross join B
  60427. **
  60428. ** The operator is "natural cross join". The A and B operands are stored
  60429. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  60430. ** operator with A. This routine shifts that operator over to B.
  60431. */
  60432. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  60433. if( p && p->a ){
  60434. int i;
  60435. for(i=p->nSrc-1; i>0; i--){
  60436. p->a[i].jointype = p->a[i-1].jointype;
  60437. }
  60438. p->a[0].jointype = 0;
  60439. }
  60440. }
  60441. /*
  60442. ** Begin a transaction
  60443. */
  60444. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  60445. sqlite3 *db;
  60446. Vdbe *v;
  60447. int i;
  60448. if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  60449. if( pParse->nErr || db->mallocFailed ) return;
  60450. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
  60451. v = sqlite3GetVdbe(pParse);
  60452. if( !v ) return;
  60453. if( type!=TK_DEFERRED ){
  60454. for(i=0; i<db->nDb; i++){
  60455. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  60456. sqlite3VdbeUsesBtree(v, i);
  60457. }
  60458. }
  60459. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  60460. }
  60461. /*
  60462. ** Commit a transaction
  60463. */
  60464. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  60465. sqlite3 *db;
  60466. Vdbe *v;
  60467. if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  60468. if( pParse->nErr || db->mallocFailed ) return;
  60469. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
  60470. v = sqlite3GetVdbe(pParse);
  60471. if( v ){
  60472. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  60473. }
  60474. }
  60475. /*
  60476. ** Rollback a transaction
  60477. */
  60478. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  60479. sqlite3 *db;
  60480. Vdbe *v;
  60481. if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  60482. if( pParse->nErr || db->mallocFailed ) return;
  60483. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
  60484. v = sqlite3GetVdbe(pParse);
  60485. if( v ){
  60486. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  60487. }
  60488. }
  60489. /*
  60490. ** This function is called by the parser when it parses a command to create,
  60491. ** release or rollback an SQL savepoint.
  60492. */
  60493. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  60494. char *zName = sqlite3NameFromToken(pParse->db, pName);
  60495. if( zName ){
  60496. Vdbe *v = sqlite3GetVdbe(pParse);
  60497. #ifndef SQLITE_OMIT_AUTHORIZATION
  60498. static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  60499. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  60500. #endif
  60501. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  60502. sqlite3DbFree(pParse->db, zName);
  60503. return;
  60504. }
  60505. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  60506. }
  60507. }
  60508. /*
  60509. ** Make sure the TEMP database is open and available for use. Return
  60510. ** the number of errors. Leave any error messages in the pParse structure.
  60511. */
  60512. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  60513. sqlite3 *db = pParse->db;
  60514. if( db->aDb[1].pBt==0 && !pParse->explain ){
  60515. int rc;
  60516. static const int flags =
  60517. SQLITE_OPEN_READWRITE |
  60518. SQLITE_OPEN_CREATE |
  60519. SQLITE_OPEN_EXCLUSIVE |
  60520. SQLITE_OPEN_DELETEONCLOSE |
  60521. SQLITE_OPEN_TEMP_DB;
  60522. rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
  60523. &db->aDb[1].pBt);
  60524. if( rc!=SQLITE_OK ){
  60525. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  60526. "file for storing temporary tables");
  60527. pParse->rc = rc;
  60528. return 1;
  60529. }
  60530. assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
  60531. assert( db->aDb[1].pSchema );
  60532. sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
  60533. db->dfltJournalMode);
  60534. }
  60535. return 0;
  60536. }
  60537. /*
  60538. ** Generate VDBE code that will verify the schema cookie and start
  60539. ** a read-transaction for all named database files.
  60540. **
  60541. ** It is important that all schema cookies be verified and all
  60542. ** read transactions be started before anything else happens in
  60543. ** the VDBE program. But this routine can be called after much other
  60544. ** code has been generated. So here is what we do:
  60545. **
  60546. ** The first time this routine is called, we code an OP_Goto that
  60547. ** will jump to a subroutine at the end of the program. Then we
  60548. ** record every database that needs its schema verified in the
  60549. ** pParse->cookieMask field. Later, after all other code has been
  60550. ** generated, the subroutine that does the cookie verifications and
  60551. ** starts the transactions will be coded and the OP_Goto P2 value
  60552. ** will be made to point to that subroutine. The generation of the
  60553. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  60554. **
  60555. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  60556. ** schema on any databases. This can be used to position the OP_Goto
  60557. ** early in the code, before we know if any database tables will be used.
  60558. */
  60559. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  60560. sqlite3 *db;
  60561. Vdbe *v;
  60562. int mask;
  60563. v = sqlite3GetVdbe(pParse);
  60564. if( v==0 ) return; /* This only happens if there was a prior error */
  60565. db = pParse->db;
  60566. if( pParse->cookieGoto==0 ){
  60567. pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  60568. }
  60569. if( iDb>=0 ){
  60570. assert( iDb<db->nDb );
  60571. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  60572. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  60573. mask = 1<<iDb;
  60574. if( (pParse->cookieMask & mask)==0 ){
  60575. pParse->cookieMask |= mask;
  60576. pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  60577. if( !OMIT_TEMPDB && iDb==1 ){
  60578. sqlite3OpenTempDatabase(pParse);
  60579. }
  60580. }
  60581. }
  60582. }
  60583. /*
  60584. ** Generate VDBE code that prepares for doing an operation that
  60585. ** might change the database.
  60586. **
  60587. ** This routine starts a new transaction if we are not already within
  60588. ** a transaction. If we are already within a transaction, then a checkpoint
  60589. ** is set if the setStatement parameter is true. A checkpoint should
  60590. ** be set for operations that might fail (due to a constraint) part of
  60591. ** the way through and which will need to undo some writes without having to
  60592. ** rollback the whole transaction. For operations where all constraints
  60593. ** can be checked before any changes are made to the database, it is never
  60594. ** necessary to undo a write and the checkpoint should not be set.
  60595. **
  60596. ** Only database iDb and the temp database are made writable by this call.
  60597. ** If iDb==0, then the main and temp databases are made writable. If
  60598. ** iDb==1 then only the temp database is made writable. If iDb>1 then the
  60599. ** specified auxiliary database and the temp database are made writable.
  60600. */
  60601. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  60602. Vdbe *v = sqlite3GetVdbe(pParse);
  60603. if( v==0 ) return;
  60604. sqlite3CodeVerifySchema(pParse, iDb);
  60605. pParse->writeMask |= 1<<iDb;
  60606. if( setStatement && pParse->nested==0 ){
  60607. sqlite3VdbeAddOp1(v, OP_Statement, iDb);
  60608. }
  60609. if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
  60610. sqlite3BeginWriteOperation(pParse, setStatement, 1);
  60611. }
  60612. }
  60613. /*
  60614. ** Check to see if pIndex uses the collating sequence pColl. Return
  60615. ** true if it does and false if it does not.
  60616. */
  60617. #ifndef SQLITE_OMIT_REINDEX
  60618. static int collationMatch(const char *zColl, Index *pIndex){
  60619. int i;
  60620. for(i=0; i<pIndex->nColumn; i++){
  60621. const char *z = pIndex->azColl[i];
  60622. if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
  60623. return 1;
  60624. }
  60625. }
  60626. return 0;
  60627. }
  60628. #endif
  60629. /*
  60630. ** Recompute all indices of pTab that use the collating sequence pColl.
  60631. ** If pColl==0 then recompute all indices of pTab.
  60632. */
  60633. #ifndef SQLITE_OMIT_REINDEX
  60634. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  60635. Index *pIndex; /* An index associated with pTab */
  60636. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  60637. if( zColl==0 || collationMatch(zColl, pIndex) ){
  60638. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  60639. sqlite3BeginWriteOperation(pParse, 0, iDb);
  60640. sqlite3RefillIndex(pParse, pIndex, -1);
  60641. }
  60642. }
  60643. }
  60644. #endif
  60645. /*
  60646. ** Recompute all indices of all tables in all databases where the
  60647. ** indices use the collating sequence pColl. If pColl==0 then recompute
  60648. ** all indices everywhere.
  60649. */
  60650. #ifndef SQLITE_OMIT_REINDEX
  60651. static void reindexDatabases(Parse *pParse, char const *zColl){
  60652. Db *pDb; /* A single database */
  60653. int iDb; /* The database index number */
  60654. sqlite3 *db = pParse->db; /* The database connection */
  60655. HashElem *k; /* For looping over tables in pDb */
  60656. Table *pTab; /* A table in the database */
  60657. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  60658. assert( pDb!=0 );
  60659. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  60660. pTab = (Table*)sqliteHashData(k);
  60661. reindexTable(pParse, pTab, zColl);
  60662. }
  60663. }
  60664. }
  60665. #endif
  60666. /*
  60667. ** Generate code for the REINDEX command.
  60668. **
  60669. ** REINDEX -- 1
  60670. ** REINDEX <collation> -- 2
  60671. ** REINDEX ?<database>.?<tablename> -- 3
  60672. ** REINDEX ?<database>.?<indexname> -- 4
  60673. **
  60674. ** Form 1 causes all indices in all attached databases to be rebuilt.
  60675. ** Form 2 rebuilds all indices in all databases that use the named
  60676. ** collating function. Forms 3 and 4 rebuild the named index or all
  60677. ** indices associated with the named table.
  60678. */
  60679. #ifndef SQLITE_OMIT_REINDEX
  60680. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  60681. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  60682. char *z; /* Name of a table or index */
  60683. const char *zDb; /* Name of the database */
  60684. Table *pTab; /* A table in the database */
  60685. Index *pIndex; /* An index associated with pTab */
  60686. int iDb; /* The database index number */
  60687. sqlite3 *db = pParse->db; /* The database connection */
  60688. Token *pObjName; /* Name of the table or index to be reindexed */
  60689. /* Read the database schema. If an error occurs, leave an error message
  60690. ** and code in pParse and return NULL. */
  60691. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  60692. return;
  60693. }
  60694. if( pName1==0 || pName1->z==0 ){
  60695. reindexDatabases(pParse, 0);
  60696. return;
  60697. }else if( pName2==0 || pName2->z==0 ){
  60698. char *zColl;
  60699. assert( pName1->z );
  60700. zColl = sqlite3NameFromToken(pParse->db, pName1);
  60701. if( !zColl ) return;
  60702. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
  60703. if( pColl ){
  60704. if( zColl ){
  60705. reindexDatabases(pParse, zColl);
  60706. sqlite3DbFree(db, zColl);
  60707. }
  60708. return;
  60709. }
  60710. sqlite3DbFree(db, zColl);
  60711. }
  60712. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  60713. if( iDb<0 ) return;
  60714. z = sqlite3NameFromToken(db, pObjName);
  60715. if( z==0 ) return;
  60716. zDb = db->aDb[iDb].zName;
  60717. pTab = sqlite3FindTable(db, z, zDb);
  60718. if( pTab ){
  60719. reindexTable(pParse, pTab, 0);
  60720. sqlite3DbFree(db, z);
  60721. return;
  60722. }
  60723. pIndex = sqlite3FindIndex(db, z, zDb);
  60724. sqlite3DbFree(db, z);
  60725. if( pIndex ){
  60726. sqlite3BeginWriteOperation(pParse, 0, iDb);
  60727. sqlite3RefillIndex(pParse, pIndex, -1);
  60728. return;
  60729. }
  60730. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  60731. }
  60732. #endif
  60733. /*
  60734. ** Return a dynamicly allocated KeyInfo structure that can be used
  60735. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  60736. **
  60737. ** If successful, a pointer to the new structure is returned. In this case
  60738. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  60739. ** pointer. If an error occurs (out of memory or missing collation
  60740. ** sequence), NULL is returned and the state of pParse updated to reflect
  60741. ** the error.
  60742. */
  60743. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  60744. int i;
  60745. int nCol = pIdx->nColumn;
  60746. int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
  60747. sqlite3 *db = pParse->db;
  60748. KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
  60749. if( pKey ){
  60750. pKey->db = pParse->db;
  60751. pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
  60752. assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
  60753. for(i=0; i<nCol; i++){
  60754. char *zColl = pIdx->azColl[i];
  60755. assert( zColl );
  60756. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
  60757. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  60758. }
  60759. pKey->nField = (u16)nCol;
  60760. }
  60761. if( pParse->nErr ){
  60762. sqlite3DbFree(db, pKey);
  60763. pKey = 0;
  60764. }
  60765. return pKey;
  60766. }
  60767. /************** End of build.c ***********************************************/
  60768. /************** Begin file callback.c ****************************************/
  60769. /*
  60770. ** 2005 May 23
  60771. **
  60772. ** The author disclaims copyright to this source code. In place of
  60773. ** a legal notice, here is a blessing:
  60774. **
  60775. ** May you do good and not evil.
  60776. ** May you find forgiveness for yourself and forgive others.
  60777. ** May you share freely, never taking more than you give.
  60778. **
  60779. *************************************************************************
  60780. **
  60781. ** This file contains functions used to access the internal hash tables
  60782. ** of user defined functions and collation sequences.
  60783. **
  60784. ** $Id: callback.c,v 1.34 2008/12/10 21:19:57 drh Exp $
  60785. */
  60786. /*
  60787. ** Invoke the 'collation needed' callback to request a collation sequence
  60788. ** in the database text encoding of name zName, length nName.
  60789. ** If the collation sequence
  60790. */
  60791. static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
  60792. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  60793. if( nName<0 ) nName = sqlite3Strlen(db, zName);
  60794. if( db->xCollNeeded ){
  60795. char *zExternal = sqlite3DbStrNDup(db, zName, nName);
  60796. if( !zExternal ) return;
  60797. db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  60798. sqlite3DbFree(db, zExternal);
  60799. }
  60800. #ifndef SQLITE_OMIT_UTF16
  60801. if( db->xCollNeeded16 ){
  60802. char const *zExternal;
  60803. sqlite3_value *pTmp = sqlite3ValueNew(db);
  60804. sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
  60805. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  60806. if( zExternal ){
  60807. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  60808. }
  60809. sqlite3ValueFree(pTmp);
  60810. }
  60811. #endif
  60812. }
  60813. /*
  60814. ** This routine is called if the collation factory fails to deliver a
  60815. ** collation function in the best encoding but there may be other versions
  60816. ** of this collation function (for other text encodings) available. Use one
  60817. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  60818. ** possible.
  60819. */
  60820. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  60821. CollSeq *pColl2;
  60822. char *z = pColl->zName;
  60823. int n = sqlite3Strlen30(z);
  60824. int i;
  60825. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  60826. for(i=0; i<3; i++){
  60827. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
  60828. if( pColl2->xCmp!=0 ){
  60829. memcpy(pColl, pColl2, sizeof(CollSeq));
  60830. pColl->xDel = 0; /* Do not copy the destructor */
  60831. return SQLITE_OK;
  60832. }
  60833. }
  60834. return SQLITE_ERROR;
  60835. }
  60836. /*
  60837. ** This function is responsible for invoking the collation factory callback
  60838. ** or substituting a collation sequence of a different encoding when the
  60839. ** requested collation sequence is not available in the database native
  60840. ** encoding.
  60841. **
  60842. ** If it is not NULL, then pColl must point to the database native encoding
  60843. ** collation sequence with name zName, length nName.
  60844. **
  60845. ** The return value is either the collation sequence to be used in database
  60846. ** db for collation type name zName, length nName, or NULL, if no collation
  60847. ** sequence can be found.
  60848. */
  60849. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  60850. sqlite3* db,
  60851. CollSeq *pColl,
  60852. const char *zName,
  60853. int nName
  60854. ){
  60855. CollSeq *p;
  60856. p = pColl;
  60857. if( !p ){
  60858. p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
  60859. }
  60860. if( !p || !p->xCmp ){
  60861. /* No collation sequence of this type for this encoding is registered.
  60862. ** Call the collation factory to see if it can supply us with one.
  60863. */
  60864. callCollNeeded(db, zName, nName);
  60865. p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
  60866. }
  60867. if( p && !p->xCmp && synthCollSeq(db, p) ){
  60868. p = 0;
  60869. }
  60870. assert( !p || p->xCmp );
  60871. return p;
  60872. }
  60873. /*
  60874. ** This routine is called on a collation sequence before it is used to
  60875. ** check that it is defined. An undefined collation sequence exists when
  60876. ** a database is loaded that contains references to collation sequences
  60877. ** that have not been defined by sqlite3_create_collation() etc.
  60878. **
  60879. ** If required, this routine calls the 'collation needed' callback to
  60880. ** request a definition of the collating sequence. If this doesn't work,
  60881. ** an equivalent collating sequence that uses a text encoding different
  60882. ** from the main database is substituted, if one is available.
  60883. */
  60884. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  60885. if( pColl ){
  60886. const char *zName = pColl->zName;
  60887. CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
  60888. if( !p ){
  60889. if( pParse->nErr==0 ){
  60890. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  60891. }
  60892. pParse->nErr++;
  60893. return SQLITE_ERROR;
  60894. }
  60895. assert( p==pColl );
  60896. }
  60897. return SQLITE_OK;
  60898. }
  60899. /*
  60900. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  60901. ** specified by zName and nName is not found and parameter 'create' is
  60902. ** true, then create a new entry. Otherwise return NULL.
  60903. **
  60904. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  60905. ** array of three CollSeq structures. The first is the collation sequence
  60906. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  60907. **
  60908. ** Stored immediately after the three collation sequences is a copy of
  60909. ** the collation sequence name. A pointer to this string is stored in
  60910. ** each collation sequence structure.
  60911. */
  60912. static CollSeq *findCollSeqEntry(
  60913. sqlite3 *db,
  60914. const char *zName,
  60915. int nName,
  60916. int create
  60917. ){
  60918. CollSeq *pColl;
  60919. if( nName<0 ) nName = sqlite3Strlen(db, zName);
  60920. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  60921. if( 0==pColl && create ){
  60922. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  60923. if( pColl ){
  60924. CollSeq *pDel = 0;
  60925. pColl[0].zName = (char*)&pColl[3];
  60926. pColl[0].enc = SQLITE_UTF8;
  60927. pColl[1].zName = (char*)&pColl[3];
  60928. pColl[1].enc = SQLITE_UTF16LE;
  60929. pColl[2].zName = (char*)&pColl[3];
  60930. pColl[2].enc = SQLITE_UTF16BE;
  60931. memcpy(pColl[0].zName, zName, nName);
  60932. pColl[0].zName[nName] = 0;
  60933. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  60934. /* If a malloc() failure occured in sqlite3HashInsert(), it will
  60935. ** return the pColl pointer to be deleted (because it wasn't added
  60936. ** to the hash table).
  60937. */
  60938. assert( pDel==0 || pDel==pColl );
  60939. if( pDel!=0 ){
  60940. db->mallocFailed = 1;
  60941. sqlite3DbFree(db, pDel);
  60942. pColl = 0;
  60943. }
  60944. }
  60945. }
  60946. return pColl;
  60947. }
  60948. /*
  60949. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  60950. ** Return the CollSeq* pointer for the collation sequence named zName
  60951. ** for the encoding 'enc' from the database 'db'.
  60952. **
  60953. ** If the entry specified is not found and 'create' is true, then create a
  60954. ** new entry. Otherwise return NULL.
  60955. **
  60956. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  60957. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  60958. ** if necessary and generates an error message if the collating sequence
  60959. ** cannot be found.
  60960. */
  60961. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  60962. sqlite3 *db,
  60963. u8 enc,
  60964. const char *zName,
  60965. int nName,
  60966. int create
  60967. ){
  60968. CollSeq *pColl;
  60969. if( zName ){
  60970. pColl = findCollSeqEntry(db, zName, nName, create);
  60971. }else{
  60972. pColl = db->pDfltColl;
  60973. }
  60974. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  60975. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  60976. if( pColl ) pColl += enc-1;
  60977. return pColl;
  60978. }
  60979. /* During the search for the best function definition, this procedure
  60980. ** is called to test how well the function passed as the first argument
  60981. ** matches the request for a function with nArg arguments in a system
  60982. ** that uses encoding enc. The value returned indicates how well the
  60983. ** request is matched. A higher value indicates a better match.
  60984. **
  60985. ** The returned value is always between 1 and 6, as follows:
  60986. **
  60987. ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
  60988. ** encoding is requested, or vice versa.
  60989. ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
  60990. ** requested, or vice versa.
  60991. ** 3: A variable arguments function using the same text encoding.
  60992. ** 4: A function with the exact number of arguments requested that
  60993. ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
  60994. ** 5: A function with the exact number of arguments requested that
  60995. ** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
  60996. ** 6: An exact match.
  60997. **
  60998. */
  60999. static int matchQuality(FuncDef *p, int nArg, u8 enc){
  61000. int match = 0;
  61001. if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
  61002. match = 1;
  61003. if( p->nArg==nArg || nArg==-1 ){
  61004. match = 4;
  61005. }
  61006. if( enc==p->iPrefEnc ){
  61007. match += 2;
  61008. }
  61009. else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
  61010. (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
  61011. match += 1;
  61012. }
  61013. }
  61014. return match;
  61015. }
  61016. /*
  61017. ** Search a FuncDefHash for a function with the given name. Return
  61018. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  61019. */
  61020. static FuncDef *functionSearch(
  61021. FuncDefHash *pHash, /* Hash table to search */
  61022. int h, /* Hash of the name */
  61023. const char *zFunc, /* Name of function */
  61024. int nFunc /* Number of bytes in zFunc */
  61025. ){
  61026. FuncDef *p;
  61027. for(p=pHash->a[h]; p; p=p->pHash){
  61028. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  61029. return p;
  61030. }
  61031. }
  61032. return 0;
  61033. }
  61034. /*
  61035. ** Insert a new FuncDef into a FuncDefHash hash table.
  61036. */
  61037. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  61038. FuncDefHash *pHash, /* The hash table into which to insert */
  61039. FuncDef *pDef /* The function definition to insert */
  61040. ){
  61041. FuncDef *pOther;
  61042. int nName = sqlite3Strlen30(pDef->zName);
  61043. u8 c1 = (u8)pDef->zName[0];
  61044. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  61045. pOther = functionSearch(pHash, h, pDef->zName, nName);
  61046. if( pOther ){
  61047. pDef->pNext = pOther->pNext;
  61048. pOther->pNext = pDef;
  61049. }else{
  61050. pDef->pNext = 0;
  61051. pDef->pHash = pHash->a[h];
  61052. pHash->a[h] = pDef;
  61053. }
  61054. }
  61055. /*
  61056. ** Locate a user function given a name, a number of arguments and a flag
  61057. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  61058. ** pointer to the FuncDef structure that defines that function, or return
  61059. ** NULL if the function does not exist.
  61060. **
  61061. ** If the createFlag argument is true, then a new (blank) FuncDef
  61062. ** structure is created and liked into the "db" structure if a
  61063. ** no matching function previously existed. When createFlag is true
  61064. ** and the nArg parameter is -1, then only a function that accepts
  61065. ** any number of arguments will be returned.
  61066. **
  61067. ** If createFlag is false and nArg is -1, then the first valid
  61068. ** function found is returned. A function is valid if either xFunc
  61069. ** or xStep is non-zero.
  61070. **
  61071. ** If createFlag is false, then a function with the required name and
  61072. ** number of arguments may be returned even if the eTextRep flag does not
  61073. ** match that requested.
  61074. */
  61075. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  61076. sqlite3 *db, /* An open database */
  61077. const char *zName, /* Name of the function. Not null-terminated */
  61078. int nName, /* Number of characters in the name */
  61079. int nArg, /* Number of arguments. -1 means any number */
  61080. u8 enc, /* Preferred text encoding */
  61081. int createFlag /* Create new entry if true and does not otherwise exist */
  61082. ){
  61083. FuncDef *p; /* Iterator variable */
  61084. FuncDef *pBest = 0; /* Best match found so far */
  61085. int bestScore = 0; /* Score of best match */
  61086. int h; /* Hash value */
  61087. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  61088. if( nArg<-1 ) nArg = -1;
  61089. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  61090. /* First search for a match amongst the application-defined functions.
  61091. */
  61092. p = functionSearch(&db->aFunc, h, zName, nName);
  61093. while( p ){
  61094. int score = matchQuality(p, nArg, enc);
  61095. if( score>bestScore ){
  61096. pBest = p;
  61097. bestScore = score;
  61098. }
  61099. p = p->pNext;
  61100. }
  61101. /* If no match is found, search the built-in functions.
  61102. **
  61103. ** Except, if createFlag is true, that means that we are trying to
  61104. ** install a new function. Whatever FuncDef structure is returned will
  61105. ** have fields overwritten with new information appropriate for the
  61106. ** new function. But the FuncDefs for built-in functions are read-only.
  61107. ** So we must not search for built-ins when creating a new function.
  61108. */
  61109. if( !createFlag && !pBest ){
  61110. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  61111. p = functionSearch(pHash, h, zName, nName);
  61112. while( p ){
  61113. int score = matchQuality(p, nArg, enc);
  61114. if( score>bestScore ){
  61115. pBest = p;
  61116. bestScore = score;
  61117. }
  61118. p = p->pNext;
  61119. }
  61120. }
  61121. /* If the createFlag parameter is true and the search did not reveal an
  61122. ** exact match for the name, number of arguments and encoding, then add a
  61123. ** new entry to the hash table and return it.
  61124. */
  61125. if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
  61126. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  61127. pBest->zName = (char *)&pBest[1];
  61128. pBest->nArg = (u16)nArg;
  61129. pBest->iPrefEnc = enc;
  61130. memcpy(pBest->zName, zName, nName);
  61131. pBest->zName[nName] = 0;
  61132. sqlite3FuncDefInsert(&db->aFunc, pBest);
  61133. }
  61134. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  61135. return pBest;
  61136. }
  61137. return 0;
  61138. }
  61139. /*
  61140. ** Free all resources held by the schema structure. The void* argument points
  61141. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  61142. ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
  61143. ** of the schema hash tables).
  61144. **
  61145. ** The Schema.cache_size variable is not cleared.
  61146. */
  61147. SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
  61148. Hash temp1;
  61149. Hash temp2;
  61150. HashElem *pElem;
  61151. Schema *pSchema = (Schema *)p;
  61152. temp1 = pSchema->tblHash;
  61153. temp2 = pSchema->trigHash;
  61154. sqlite3HashInit(&pSchema->trigHash, 0);
  61155. sqlite3HashClear(&pSchema->aFKey);
  61156. sqlite3HashClear(&pSchema->idxHash);
  61157. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  61158. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  61159. }
  61160. sqlite3HashClear(&temp2);
  61161. sqlite3HashInit(&pSchema->tblHash, 0);
  61162. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  61163. Table *pTab = sqliteHashData(pElem);
  61164. sqlite3DeleteTable(pTab);
  61165. }
  61166. sqlite3HashClear(&temp1);
  61167. pSchema->pSeqTab = 0;
  61168. pSchema->flags &= ~DB_SchemaLoaded;
  61169. }
  61170. /*
  61171. ** Find and return the schema associated with a BTree. Create
  61172. ** a new one if necessary.
  61173. */
  61174. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  61175. Schema * p;
  61176. if( pBt ){
  61177. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
  61178. }else{
  61179. p = (Schema *)sqlite3MallocZero(sizeof(Schema));
  61180. }
  61181. if( !p ){
  61182. db->mallocFailed = 1;
  61183. }else if ( 0==p->file_format ){
  61184. sqlite3HashInit(&p->tblHash, 0);
  61185. sqlite3HashInit(&p->idxHash, 0);
  61186. sqlite3HashInit(&p->trigHash, 0);
  61187. sqlite3HashInit(&p->aFKey, 1);
  61188. p->enc = SQLITE_UTF8;
  61189. }
  61190. return p;
  61191. }
  61192. /************** End of callback.c ********************************************/
  61193. /************** Begin file delete.c ******************************************/
  61194. /*
  61195. ** 2001 September 15
  61196. **
  61197. ** The author disclaims copyright to this source code. In place of
  61198. ** a legal notice, here is a blessing:
  61199. **
  61200. ** May you do good and not evil.
  61201. ** May you find forgiveness for yourself and forgive others.
  61202. ** May you share freely, never taking more than you give.
  61203. **
  61204. *************************************************************************
  61205. ** This file contains C code routines that are called by the parser
  61206. ** in order to generate code for DELETE FROM statements.
  61207. **
  61208. ** $Id: delete.c,v 1.191 2008/12/23 23:56:22 drh Exp $
  61209. */
  61210. /*
  61211. ** Look up every table that is named in pSrc. If any table is not found,
  61212. ** add an error message to pParse->zErrMsg and return NULL. If all tables
  61213. ** are found, return a pointer to the last table.
  61214. */
  61215. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  61216. struct SrcList_item *pItem = pSrc->a;
  61217. Table *pTab;
  61218. assert( pItem && pSrc->nSrc==1 );
  61219. pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
  61220. sqlite3DeleteTable(pItem->pTab);
  61221. pItem->pTab = pTab;
  61222. if( pTab ){
  61223. pTab->nRef++;
  61224. }
  61225. if( sqlite3IndexedByLookup(pParse, pItem) ){
  61226. pTab = 0;
  61227. }
  61228. return pTab;
  61229. }
  61230. /*
  61231. ** Check to make sure the given table is writable. If it is not
  61232. ** writable, generate an error message and return 1. If it is
  61233. ** writable return 0;
  61234. */
  61235. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  61236. if( ((pTab->tabFlags & TF_Readonly)!=0
  61237. && (pParse->db->flags & SQLITE_WriteSchema)==0
  61238. && pParse->nested==0)
  61239. #ifndef SQLITE_OMIT_VIRTUALTABLE
  61240. || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
  61241. #endif
  61242. ){
  61243. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  61244. return 1;
  61245. }
  61246. #ifndef SQLITE_OMIT_VIEW
  61247. if( !viewOk && pTab->pSelect ){
  61248. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  61249. return 1;
  61250. }
  61251. #endif
  61252. return 0;
  61253. }
  61254. /*
  61255. ** Generate code that will open a table for reading.
  61256. */
  61257. SQLITE_PRIVATE void sqlite3OpenTable(
  61258. Parse *p, /* Generate code into this VDBE */
  61259. int iCur, /* The cursor number of the table */
  61260. int iDb, /* The database index in sqlite3.aDb[] */
  61261. Table *pTab, /* The table to be opened */
  61262. int opcode /* OP_OpenRead or OP_OpenWrite */
  61263. ){
  61264. Vdbe *v;
  61265. if( IsVirtual(pTab) ) return;
  61266. v = sqlite3GetVdbe(p);
  61267. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  61268. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  61269. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
  61270. sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  61271. VdbeComment((v, "%s", pTab->zName));
  61272. }
  61273. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  61274. /*
  61275. ** Evaluate a view and store its result in an ephemeral table. The
  61276. ** pWhere argument is an optional WHERE clause that restricts the
  61277. ** set of rows in the view that are to be added to the ephemeral table.
  61278. */
  61279. SQLITE_PRIVATE void sqlite3MaterializeView(
  61280. Parse *pParse, /* Parsing context */
  61281. Table *pView, /* View definition */
  61282. Expr *pWhere, /* Optional WHERE clause to be added */
  61283. int iCur /* Cursor number for ephemerial table */
  61284. ){
  61285. SelectDest dest;
  61286. Select *pDup;
  61287. sqlite3 *db = pParse->db;
  61288. pDup = sqlite3SelectDup(db, pView->pSelect);
  61289. if( pWhere ){
  61290. SrcList *pFrom;
  61291. Token viewName;
  61292. pWhere = sqlite3ExprDup(db, pWhere);
  61293. viewName.z = (u8*)pView->zName;
  61294. viewName.n = (unsigned int)sqlite3Strlen30((const char*)viewName.z);
  61295. pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &viewName, pDup, 0,0);
  61296. pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  61297. }
  61298. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  61299. sqlite3Select(pParse, pDup, &dest);
  61300. sqlite3SelectDelete(db, pDup);
  61301. }
  61302. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  61303. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  61304. /*
  61305. ** Generate an expression tree to implement the WHERE, ORDER BY,
  61306. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  61307. **
  61308. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  61309. ** \__________________________/
  61310. ** pLimitWhere (pInClause)
  61311. */
  61312. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  61313. Parse *pParse, /* The parser context */
  61314. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  61315. Expr *pWhere, /* The WHERE clause. May be null */
  61316. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  61317. Expr *pLimit, /* The LIMIT clause. May be null */
  61318. Expr *pOffset, /* The OFFSET clause. May be null */
  61319. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  61320. ){
  61321. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  61322. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  61323. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  61324. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  61325. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  61326. Select *pSelect = NULL; /* Complete SELECT tree */
  61327. /* Check that there isn't an ORDER BY without a LIMIT clause.
  61328. */
  61329. if( pOrderBy && (pLimit == 0) ) {
  61330. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  61331. pParse->parseError = 1;
  61332. goto limit_where_cleanup_2;
  61333. }
  61334. /* We only need to generate a select expression if there
  61335. ** is a limit/offset term to enforce.
  61336. */
  61337. if( pLimit == 0 ) {
  61338. /* if pLimit is null, pOffset will always be null as well. */
  61339. assert( pOffset == 0 );
  61340. return pWhere;
  61341. }
  61342. /* Generate a select expression tree to enforce the limit/offset
  61343. ** term for the DELETE or UPDATE statement. For example:
  61344. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  61345. ** becomes:
  61346. ** DELETE FROM table_a WHERE rowid IN (
  61347. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  61348. ** );
  61349. */
  61350. pSelectRowid = sqlite3Expr(pParse->db, TK_ROW, 0, 0, 0);
  61351. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  61352. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid, 0);
  61353. if( pEList == 0 ) goto limit_where_cleanup_2;
  61354. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  61355. ** and the SELECT subtree. */
  61356. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc);
  61357. if( pSelectSrc == 0 ) {
  61358. sqlite3ExprListDelete(pParse->db, pEList);
  61359. goto limit_where_cleanup_2;
  61360. }
  61361. /* generate the SELECT expression tree. */
  61362. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,pOrderBy,0,pLimit,pOffset);
  61363. if( pSelect == 0 ) return 0;
  61364. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  61365. pWhereRowid = sqlite3Expr(pParse->db, TK_ROW, 0, 0, 0);
  61366. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  61367. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  61368. if( pInClause == 0 ) goto limit_where_cleanup_1;
  61369. pInClause->pSelect = pSelect;
  61370. sqlite3ExprSetHeight(pParse, pInClause);
  61371. return pInClause;
  61372. /* something went wrong. clean up anything allocated. */
  61373. limit_where_cleanup_1:
  61374. sqlite3SelectDelete(pParse->db, pSelect);
  61375. return 0;
  61376. limit_where_cleanup_2:
  61377. sqlite3ExprDelete(pParse->db, pWhere);
  61378. sqlite3ExprListDelete(pParse->db, pOrderBy);
  61379. sqlite3ExprDelete(pParse->db, pLimit);
  61380. sqlite3ExprDelete(pParse->db, pOffset);
  61381. return 0;
  61382. }
  61383. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  61384. /*
  61385. ** Generate code for a DELETE FROM statement.
  61386. **
  61387. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  61388. ** \________/ \________________/
  61389. ** pTabList pWhere
  61390. */
  61391. SQLITE_PRIVATE void sqlite3DeleteFrom(
  61392. Parse *pParse, /* The parser context */
  61393. SrcList *pTabList, /* The table from which we should delete things */
  61394. Expr *pWhere /* The WHERE clause. May be null */
  61395. ){
  61396. Vdbe *v; /* The virtual database engine */
  61397. Table *pTab; /* The table from which records will be deleted */
  61398. const char *zDb; /* Name of database holding pTab */
  61399. int end, addr = 0; /* A couple addresses of generated code */
  61400. int i; /* Loop counter */
  61401. WhereInfo *pWInfo; /* Information about the WHERE clause */
  61402. Index *pIdx; /* For looping over indices of the table */
  61403. int iCur; /* VDBE Cursor number for pTab */
  61404. sqlite3 *db; /* Main database structure */
  61405. AuthContext sContext; /* Authorization context */
  61406. int oldIdx = -1; /* Cursor for the OLD table of AFTER triggers */
  61407. NameContext sNC; /* Name context to resolve expressions in */
  61408. int iDb; /* Database number */
  61409. int memCnt = -1; /* Memory cell used for change counting */
  61410. int rcauth; /* Value returned by authorization callback */
  61411. #ifndef SQLITE_OMIT_TRIGGER
  61412. int isView; /* True if attempting to delete from a view */
  61413. int triggers_exist = 0; /* True if any triggers exist */
  61414. #endif
  61415. int iBeginAfterTrigger = 0; /* Address of after trigger program */
  61416. int iEndAfterTrigger = 0; /* Exit of after trigger program */
  61417. int iBeginBeforeTrigger = 0; /* Address of before trigger program */
  61418. int iEndBeforeTrigger = 0; /* Exit of before trigger program */
  61419. u32 old_col_mask = 0; /* Mask of OLD.* columns in use */
  61420. sContext.pParse = 0;
  61421. db = pParse->db;
  61422. if( pParse->nErr || db->mallocFailed ){
  61423. goto delete_from_cleanup;
  61424. }
  61425. assert( pTabList->nSrc==1 );
  61426. /* Locate the table which we want to delete. This table has to be
  61427. ** put in an SrcList structure because some of the subroutines we
  61428. ** will be calling are designed to work with multiple tables and expect
  61429. ** an SrcList* parameter instead of just a Table* parameter.
  61430. */
  61431. pTab = sqlite3SrcListLookup(pParse, pTabList);
  61432. if( pTab==0 ) goto delete_from_cleanup;
  61433. /* Figure out if we have any triggers and if the table being
  61434. ** deleted from is a view
  61435. */
  61436. #ifndef SQLITE_OMIT_TRIGGER
  61437. triggers_exist = sqlite3TriggersExist(pTab, TK_DELETE, 0);
  61438. isView = pTab->pSelect!=0;
  61439. #else
  61440. # define triggers_exist 0
  61441. # define isView 0
  61442. #endif
  61443. #ifdef SQLITE_OMIT_VIEW
  61444. # undef isView
  61445. # define isView 0
  61446. #endif
  61447. if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
  61448. goto delete_from_cleanup;
  61449. }
  61450. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  61451. assert( iDb<db->nDb );
  61452. zDb = db->aDb[iDb].zName;
  61453. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  61454. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  61455. if( rcauth==SQLITE_DENY ){
  61456. goto delete_from_cleanup;
  61457. }
  61458. assert(!isView || triggers_exist);
  61459. /* If pTab is really a view, make sure it has been initialized.
  61460. */
  61461. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  61462. goto delete_from_cleanup;
  61463. }
  61464. /* Allocate a cursor used to store the old.* data for a trigger.
  61465. */
  61466. if( triggers_exist ){
  61467. oldIdx = pParse->nTab++;
  61468. }
  61469. /* Assign cursor number to the table and all its indices.
  61470. */
  61471. assert( pTabList->nSrc==1 );
  61472. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  61473. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  61474. pParse->nTab++;
  61475. }
  61476. /* Start the view context
  61477. */
  61478. if( isView ){
  61479. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  61480. }
  61481. /* Begin generating code.
  61482. */
  61483. v = sqlite3GetVdbe(pParse);
  61484. if( v==0 ){
  61485. goto delete_from_cleanup;
  61486. }
  61487. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  61488. sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
  61489. if( triggers_exist ){
  61490. int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
  61491. int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
  61492. addr = sqlite3VdbeMakeLabel(v);
  61493. iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
  61494. (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
  61495. -1, oldIdx, orconf, addr, &old_col_mask, 0);
  61496. iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
  61497. iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
  61498. (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
  61499. oldIdx, orconf, addr, &old_col_mask, 0);
  61500. iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
  61501. sqlite3VdbeJumpHere(v, iGoto);
  61502. }
  61503. /* If we are trying to delete from a view, realize that view into
  61504. ** a ephemeral table.
  61505. */
  61506. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  61507. if( isView ){
  61508. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  61509. }
  61510. #endif
  61511. /* Resolve the column names in the WHERE clause.
  61512. */
  61513. memset(&sNC, 0, sizeof(sNC));
  61514. sNC.pParse = pParse;
  61515. sNC.pSrcList = pTabList;
  61516. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  61517. goto delete_from_cleanup;
  61518. }
  61519. /* Initialize the counter of the number of rows deleted, if
  61520. ** we are counting rows.
  61521. */
  61522. if( db->flags & SQLITE_CountRows ){
  61523. memCnt = ++pParse->nMem;
  61524. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  61525. }
  61526. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  61527. /* Special case: A DELETE without a WHERE clause deletes everything.
  61528. ** It is easier just to erase the whole table. Note, however, that
  61529. ** this means that the row change count will be incorrect.
  61530. */
  61531. if( rcauth==SQLITE_OK && pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
  61532. assert( !isView );
  61533. sqlite3VdbeAddOp3(v, OP_Clear, pTab->tnum, iDb, memCnt);
  61534. if( !pParse->nested ){
  61535. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
  61536. }
  61537. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  61538. assert( pIdx->pSchema==pTab->pSchema );
  61539. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  61540. }
  61541. }else
  61542. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  61543. /* The usual case: There is a WHERE clause so we have to scan through
  61544. ** the table and pick which records to delete.
  61545. */
  61546. {
  61547. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  61548. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  61549. /* Collect rowids of every row to be deleted.
  61550. */
  61551. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  61552. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
  61553. WHERE_FILL_ROWSET, iRowSet);
  61554. if( pWInfo==0 ) goto delete_from_cleanup;
  61555. if( db->flags & SQLITE_CountRows ){
  61556. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  61557. }
  61558. sqlite3WhereEnd(pWInfo);
  61559. /* Open the pseudo-table used to store OLD if there are triggers.
  61560. */
  61561. if( triggers_exist ){
  61562. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
  61563. sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx);
  61564. }
  61565. /* Delete every item whose key was written to the list during the
  61566. ** database scan. We have to delete items after the scan is complete
  61567. ** because deleting an item can change the scan order.
  61568. */
  61569. end = sqlite3VdbeMakeLabel(v);
  61570. if( !isView ){
  61571. /* Open cursors for the table we are deleting from and
  61572. ** all its indices.
  61573. */
  61574. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  61575. }
  61576. /* This is the beginning of the delete loop. If a trigger encounters
  61577. ** an IGNORE constraint, it jumps back to here.
  61578. */
  61579. if( triggers_exist ){
  61580. sqlite3VdbeResolveLabel(v, addr);
  61581. }
  61582. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  61583. if( triggers_exist ){
  61584. int iData = ++pParse->nMem; /* For storing row data of OLD table */
  61585. /* If the record is no longer present in the table, jump to the
  61586. ** next iteration of the loop through the contents of the fifo.
  61587. */
  61588. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
  61589. /* Populate the OLD.* pseudo-table */
  61590. if( old_col_mask ){
  61591. sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
  61592. }else{
  61593. sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
  61594. }
  61595. sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
  61596. /* Jump back and run the BEFORE triggers */
  61597. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
  61598. sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
  61599. }
  61600. if( !isView ){
  61601. /* Delete the row */
  61602. #ifndef SQLITE_OMIT_VIRTUALTABLE
  61603. if( IsVirtual(pTab) ){
  61604. const char *pVtab = (const char *)pTab->pVtab;
  61605. sqlite3VtabMakeWritable(pParse, pTab);
  61606. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB);
  61607. }else
  61608. #endif
  61609. {
  61610. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
  61611. }
  61612. }
  61613. /* If there are row triggers, close all cursors then invoke
  61614. ** the AFTER triggers
  61615. */
  61616. if( triggers_exist ){
  61617. /* Jump back and run the AFTER triggers */
  61618. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
  61619. sqlite3VdbeJumpHere(v, iEndAfterTrigger);
  61620. }
  61621. /* End of the delete loop */
  61622. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  61623. sqlite3VdbeResolveLabel(v, end);
  61624. /* Close the cursors after the loop if there are no row triggers */
  61625. if( !isView && !IsVirtual(pTab) ){
  61626. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  61627. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  61628. }
  61629. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  61630. }
  61631. }
  61632. /*
  61633. ** Return the number of rows that were deleted. If this routine is
  61634. ** generating code because of a call to sqlite3NestedParse(), do not
  61635. ** invoke the callback function.
  61636. */
  61637. if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
  61638. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  61639. sqlite3VdbeSetNumCols(v, 1);
  61640. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  61641. }
  61642. delete_from_cleanup:
  61643. sqlite3AuthContextPop(&sContext);
  61644. sqlite3SrcListDelete(db, pTabList);
  61645. sqlite3ExprDelete(db, pWhere);
  61646. return;
  61647. }
  61648. /*
  61649. ** This routine generates VDBE code that causes a single row of a
  61650. ** single table to be deleted.
  61651. **
  61652. ** The VDBE must be in a particular state when this routine is called.
  61653. ** These are the requirements:
  61654. **
  61655. ** 1. A read/write cursor pointing to pTab, the table containing the row
  61656. ** to be deleted, must be opened as cursor number "base".
  61657. **
  61658. ** 2. Read/write cursors for all indices of pTab must be open as
  61659. ** cursor number base+i for the i-th index.
  61660. **
  61661. ** 3. The record number of the row to be deleted must be stored in
  61662. ** memory cell iRowid.
  61663. **
  61664. ** This routine pops the top of the stack to remove the record number
  61665. ** and then generates code to remove both the table record and all index
  61666. ** entries that point to that record.
  61667. */
  61668. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  61669. Parse *pParse, /* Parsing context */
  61670. Table *pTab, /* Table containing the row to be deleted */
  61671. int iCur, /* Cursor number for the table */
  61672. int iRowid, /* Memory cell that contains the rowid to delete */
  61673. int count /* Increment the row change counter */
  61674. ){
  61675. int addr;
  61676. Vdbe *v;
  61677. v = pParse->pVdbe;
  61678. addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid);
  61679. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  61680. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  61681. if( count ){
  61682. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
  61683. }
  61684. sqlite3VdbeJumpHere(v, addr);
  61685. }
  61686. /*
  61687. ** This routine generates VDBE code that causes the deletion of all
  61688. ** index entries associated with a single row of a single table.
  61689. **
  61690. ** The VDBE must be in a particular state when this routine is called.
  61691. ** These are the requirements:
  61692. **
  61693. ** 1. A read/write cursor pointing to pTab, the table containing the row
  61694. ** to be deleted, must be opened as cursor number "iCur".
  61695. **
  61696. ** 2. Read/write cursors for all indices of pTab must be open as
  61697. ** cursor number iCur+i for the i-th index.
  61698. **
  61699. ** 3. The "iCur" cursor must be pointing to the row that is to be
  61700. ** deleted.
  61701. */
  61702. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  61703. Parse *pParse, /* Parsing and code generating context */
  61704. Table *pTab, /* Table containing the row to be deleted */
  61705. int iCur, /* Cursor number for the table */
  61706. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  61707. ){
  61708. int i;
  61709. Index *pIdx;
  61710. int r1;
  61711. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  61712. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  61713. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
  61714. sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
  61715. }
  61716. }
  61717. /*
  61718. ** Generate code that will assemble an index key and put it in register
  61719. ** regOut. The key with be for index pIdx which is an index on pTab.
  61720. ** iCur is the index of a cursor open on the pTab table and pointing to
  61721. ** the entry that needs indexing.
  61722. **
  61723. ** Return a register number which is the first in a block of
  61724. ** registers that holds the elements of the index key. The
  61725. ** block of registers has already been deallocated by the time
  61726. ** this routine returns.
  61727. */
  61728. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  61729. Parse *pParse, /* Parsing context */
  61730. Index *pIdx, /* The index for which to generate a key */
  61731. int iCur, /* Cursor number for the pIdx->pTable table */
  61732. int regOut, /* Write the new index key to this register */
  61733. int doMakeRec /* Run the OP_MakeRecord instruction if true */
  61734. ){
  61735. Vdbe *v = pParse->pVdbe;
  61736. int j;
  61737. Table *pTab = pIdx->pTable;
  61738. int regBase;
  61739. int nCol;
  61740. nCol = pIdx->nColumn;
  61741. regBase = sqlite3GetTempRange(pParse, nCol+1);
  61742. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  61743. for(j=0; j<nCol; j++){
  61744. int idx = pIdx->aiColumn[j];
  61745. if( idx==pTab->iPKey ){
  61746. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  61747. }else{
  61748. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  61749. sqlite3ColumnDefault(v, pTab, idx);
  61750. }
  61751. }
  61752. if( doMakeRec ){
  61753. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  61754. sqlite3IndexAffinityStr(v, pIdx);
  61755. sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1);
  61756. }
  61757. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  61758. return regBase;
  61759. }
  61760. /* Make sure "isView" gets undefined in case this file becomes part of
  61761. ** the amalgamation - so that subsequent files do not see isView as a
  61762. ** macro. */
  61763. #undef isView
  61764. /************** End of delete.c **********************************************/
  61765. /************** Begin file func.c ********************************************/
  61766. /*
  61767. ** 2002 February 23
  61768. **
  61769. ** The author disclaims copyright to this source code. In place of
  61770. ** a legal notice, here is a blessing:
  61771. **
  61772. ** May you do good and not evil.
  61773. ** May you find forgiveness for yourself and forgive others.
  61774. ** May you share freely, never taking more than you give.
  61775. **
  61776. *************************************************************************
  61777. ** This file contains the C functions that implement various SQL
  61778. ** functions of SQLite.
  61779. **
  61780. ** There is only one exported symbol in this file - the function
  61781. ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  61782. ** All other code has file scope.
  61783. **
  61784. ** $Id: func.c,v 1.209 2008/12/10 23:04:13 drh Exp $
  61785. */
  61786. /*
  61787. ** Return the collating function associated with a function.
  61788. */
  61789. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  61790. return context->pColl;
  61791. }
  61792. /*
  61793. ** Implementation of the non-aggregate min() and max() functions
  61794. */
  61795. static void minmaxFunc(
  61796. sqlite3_context *context,
  61797. int argc,
  61798. sqlite3_value **argv
  61799. ){
  61800. int i;
  61801. int mask; /* 0 for min() or 0xffffffff for max() */
  61802. int iBest;
  61803. CollSeq *pColl;
  61804. if( argc==0 ) return;
  61805. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  61806. pColl = sqlite3GetFuncCollSeq(context);
  61807. assert( pColl );
  61808. assert( mask==-1 || mask==0 );
  61809. iBest = 0;
  61810. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  61811. for(i=1; i<argc; i++){
  61812. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  61813. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  61814. iBest = i;
  61815. }
  61816. }
  61817. sqlite3_result_value(context, argv[iBest]);
  61818. }
  61819. /*
  61820. ** Return the type of the argument.
  61821. */
  61822. static void typeofFunc(
  61823. sqlite3_context *context,
  61824. int NotUsed,
  61825. sqlite3_value **argv
  61826. ){
  61827. const char *z = 0;
  61828. UNUSED_PARAMETER(NotUsed);
  61829. switch( sqlite3_value_type(argv[0]) ){
  61830. case SQLITE_NULL: z = "null"; break;
  61831. case SQLITE_INTEGER: z = "integer"; break;
  61832. case SQLITE_TEXT: z = "text"; break;
  61833. case SQLITE_FLOAT: z = "real"; break;
  61834. case SQLITE_BLOB: z = "blob"; break;
  61835. }
  61836. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  61837. }
  61838. /*
  61839. ** Implementation of the length() function
  61840. */
  61841. static void lengthFunc(
  61842. sqlite3_context *context,
  61843. int argc,
  61844. sqlite3_value **argv
  61845. ){
  61846. int len;
  61847. assert( argc==1 );
  61848. UNUSED_PARAMETER(argc);
  61849. switch( sqlite3_value_type(argv[0]) ){
  61850. case SQLITE_BLOB:
  61851. case SQLITE_INTEGER:
  61852. case SQLITE_FLOAT: {
  61853. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  61854. break;
  61855. }
  61856. case SQLITE_TEXT: {
  61857. const unsigned char *z = sqlite3_value_text(argv[0]);
  61858. if( z==0 ) return;
  61859. len = 0;
  61860. while( *z ){
  61861. len++;
  61862. SQLITE_SKIP_UTF8(z);
  61863. }
  61864. sqlite3_result_int(context, len);
  61865. break;
  61866. }
  61867. default: {
  61868. sqlite3_result_null(context);
  61869. break;
  61870. }
  61871. }
  61872. }
  61873. /*
  61874. ** Implementation of the abs() function
  61875. */
  61876. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  61877. assert( argc==1 );
  61878. UNUSED_PARAMETER(argc);
  61879. switch( sqlite3_value_type(argv[0]) ){
  61880. case SQLITE_INTEGER: {
  61881. i64 iVal = sqlite3_value_int64(argv[0]);
  61882. if( iVal<0 ){
  61883. if( (iVal<<1)==0 ){
  61884. sqlite3_result_error(context, "integer overflow", -1);
  61885. return;
  61886. }
  61887. iVal = -iVal;
  61888. }
  61889. sqlite3_result_int64(context, iVal);
  61890. break;
  61891. }
  61892. case SQLITE_NULL: {
  61893. sqlite3_result_null(context);
  61894. break;
  61895. }
  61896. default: {
  61897. double rVal = sqlite3_value_double(argv[0]);
  61898. if( rVal<0 ) rVal = -rVal;
  61899. sqlite3_result_double(context, rVal);
  61900. break;
  61901. }
  61902. }
  61903. }
  61904. /*
  61905. ** Implementation of the substr() function.
  61906. **
  61907. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  61908. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  61909. ** of x. If x is text, then we actually count UTF-8 characters.
  61910. ** If x is a blob, then we count bytes.
  61911. **
  61912. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  61913. */
  61914. static void substrFunc(
  61915. sqlite3_context *context,
  61916. int argc,
  61917. sqlite3_value **argv
  61918. ){
  61919. const unsigned char *z;
  61920. const unsigned char *z2;
  61921. int len;
  61922. int p0type;
  61923. i64 p1, p2;
  61924. assert( argc==3 || argc==2 );
  61925. p0type = sqlite3_value_type(argv[0]);
  61926. if( p0type==SQLITE_BLOB ){
  61927. len = sqlite3_value_bytes(argv[0]);
  61928. z = sqlite3_value_blob(argv[0]);
  61929. if( z==0 ) return;
  61930. assert( len==sqlite3_value_bytes(argv[0]) );
  61931. }else{
  61932. z = sqlite3_value_text(argv[0]);
  61933. if( z==0 ) return;
  61934. len = 0;
  61935. for(z2=z; *z2; len++){
  61936. SQLITE_SKIP_UTF8(z2);
  61937. }
  61938. }
  61939. p1 = sqlite3_value_int(argv[1]);
  61940. if( argc==3 ){
  61941. p2 = sqlite3_value_int(argv[2]);
  61942. }else{
  61943. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  61944. }
  61945. if( p1<0 ){
  61946. p1 += len;
  61947. if( p1<0 ){
  61948. p2 += p1;
  61949. p1 = 0;
  61950. }
  61951. }else if( p1>0 ){
  61952. p1--;
  61953. }
  61954. if( p1+p2>len ){
  61955. p2 = len-p1;
  61956. }
  61957. if( p0type!=SQLITE_BLOB ){
  61958. while( *z && p1 ){
  61959. SQLITE_SKIP_UTF8(z);
  61960. p1--;
  61961. }
  61962. for(z2=z; *z2 && p2; p2--){
  61963. SQLITE_SKIP_UTF8(z2);
  61964. }
  61965. sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  61966. }else{
  61967. if( p2<0 ) p2 = 0;
  61968. sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  61969. }
  61970. }
  61971. /*
  61972. ** Implementation of the round() function
  61973. */
  61974. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  61975. int n = 0;
  61976. double r;
  61977. char zBuf[500]; /* larger than the %f representation of the largest double */
  61978. assert( argc==1 || argc==2 );
  61979. if( argc==2 ){
  61980. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  61981. n = sqlite3_value_int(argv[1]);
  61982. if( n>30 ) n = 30;
  61983. if( n<0 ) n = 0;
  61984. }
  61985. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  61986. r = sqlite3_value_double(argv[0]);
  61987. sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
  61988. sqlite3AtoF(zBuf, &r);
  61989. sqlite3_result_double(context, r);
  61990. }
  61991. /*
  61992. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  61993. ** allocation fails, call sqlite3_result_error_nomem() to notify
  61994. ** the database handle that malloc() has failed.
  61995. */
  61996. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  61997. char *z;
  61998. if( nByte>sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH] ){
  61999. sqlite3_result_error_toobig(context);
  62000. z = 0;
  62001. }else{
  62002. z = sqlite3Malloc((int)nByte);
  62003. if( !z && nByte>0 ){
  62004. sqlite3_result_error_nomem(context);
  62005. }
  62006. }
  62007. return z;
  62008. }
  62009. /*
  62010. ** Implementation of the upper() and lower() SQL functions.
  62011. */
  62012. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  62013. char *z1;
  62014. const char *z2;
  62015. int i, n;
  62016. if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
  62017. z2 = (char*)sqlite3_value_text(argv[0]);
  62018. n = sqlite3_value_bytes(argv[0]);
  62019. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  62020. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  62021. if( z2 ){
  62022. z1 = contextMalloc(context, ((i64)n)+1);
  62023. if( z1 ){
  62024. memcpy(z1, z2, n+1);
  62025. for(i=0; z1[i]; i++){
  62026. z1[i] = (char)toupper(z1[i]);
  62027. }
  62028. sqlite3_result_text(context, z1, -1, sqlite3_free);
  62029. }
  62030. }
  62031. }
  62032. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  62033. char *z1;
  62034. const char *z2;
  62035. int i, n;
  62036. if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
  62037. z2 = (char*)sqlite3_value_text(argv[0]);
  62038. n = sqlite3_value_bytes(argv[0]);
  62039. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  62040. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  62041. if( z2 ){
  62042. z1 = contextMalloc(context, ((i64)n)+1);
  62043. if( z1 ){
  62044. memcpy(z1, z2, n+1);
  62045. for(i=0; z1[i]; i++){
  62046. z1[i] = (char)tolower(z1[i]);
  62047. }
  62048. sqlite3_result_text(context, z1, -1, sqlite3_free);
  62049. }
  62050. }
  62051. }
  62052. /*
  62053. ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
  62054. ** All three do the same thing. They return the first non-NULL
  62055. ** argument.
  62056. */
  62057. static void ifnullFunc(
  62058. sqlite3_context *context,
  62059. int argc,
  62060. sqlite3_value **argv
  62061. ){
  62062. int i;
  62063. for(i=0; i<argc; i++){
  62064. if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
  62065. sqlite3_result_value(context, argv[i]);
  62066. break;
  62067. }
  62068. }
  62069. }
  62070. /*
  62071. ** Implementation of random(). Return a random integer.
  62072. */
  62073. static void randomFunc(
  62074. sqlite3_context *context,
  62075. int NotUsed,
  62076. sqlite3_value **NotUsed2
  62077. ){
  62078. sqlite_int64 r;
  62079. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  62080. sqlite3_randomness(sizeof(r), &r);
  62081. if( (r<<1)==0 ) r = 0; /* Prevent 0x8000.... as the result so that we */
  62082. /* can always do abs() of the result */
  62083. sqlite3_result_int64(context, r);
  62084. }
  62085. /*
  62086. ** Implementation of randomblob(N). Return a random blob
  62087. ** that is N bytes long.
  62088. */
  62089. static void randomBlob(
  62090. sqlite3_context *context,
  62091. int argc,
  62092. sqlite3_value **argv
  62093. ){
  62094. int n;
  62095. unsigned char *p;
  62096. assert( argc==1 );
  62097. UNUSED_PARAMETER(argc);
  62098. n = sqlite3_value_int(argv[0]);
  62099. if( n<1 ){
  62100. n = 1;
  62101. }
  62102. p = contextMalloc(context, n);
  62103. if( p ){
  62104. sqlite3_randomness(n, p);
  62105. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  62106. }
  62107. }
  62108. /*
  62109. ** Implementation of the last_insert_rowid() SQL function. The return
  62110. ** value is the same as the sqlite3_last_insert_rowid() API function.
  62111. */
  62112. static void last_insert_rowid(
  62113. sqlite3_context *context,
  62114. int NotUsed,
  62115. sqlite3_value **NotUsed2
  62116. ){
  62117. sqlite3 *db = sqlite3_context_db_handle(context);
  62118. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  62119. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  62120. }
  62121. /*
  62122. ** Implementation of the changes() SQL function. The return value is the
  62123. ** same as the sqlite3_changes() API function.
  62124. */
  62125. static void changes(
  62126. sqlite3_context *context,
  62127. int NotUsed,
  62128. sqlite3_value **NotUsed2
  62129. ){
  62130. sqlite3 *db = sqlite3_context_db_handle(context);
  62131. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  62132. sqlite3_result_int(context, sqlite3_changes(db));
  62133. }
  62134. /*
  62135. ** Implementation of the total_changes() SQL function. The return value is
  62136. ** the same as the sqlite3_total_changes() API function.
  62137. */
  62138. static void total_changes(
  62139. sqlite3_context *context,
  62140. int NotUsed,
  62141. sqlite3_value **NotUsed2
  62142. ){
  62143. sqlite3 *db = sqlite3_context_db_handle(context);
  62144. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  62145. sqlite3_result_int(context, sqlite3_total_changes(db));
  62146. }
  62147. /*
  62148. ** A structure defining how to do GLOB-style comparisons.
  62149. */
  62150. struct compareInfo {
  62151. u8 matchAll;
  62152. u8 matchOne;
  62153. u8 matchSet;
  62154. u8 noCase;
  62155. };
  62156. /*
  62157. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  62158. ** character is exactly one byte in size. Also, all characters are
  62159. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  62160. ** whereas only characters less than 0x80 do in ASCII.
  62161. */
  62162. #if defined(SQLITE_EBCDIC)
  62163. # define sqlite3Utf8Read(A,B,C) (*(A++))
  62164. # define GlogUpperToLower(A) A = sqlite3UpperToLower[A]
  62165. #else
  62166. # define GlogUpperToLower(A) if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
  62167. #endif
  62168. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  62169. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  62170. ** case. Thus 'a' LIKE 'A' would be true. */
  62171. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  62172. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  62173. ** is case sensitive causing 'a' LIKE 'A' to be false */
  62174. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  62175. /*
  62176. ** Compare two UTF-8 strings for equality where the first string can
  62177. ** potentially be a "glob" expression. Return true (1) if they
  62178. ** are the same and false (0) if they are different.
  62179. **
  62180. ** Globbing rules:
  62181. **
  62182. ** '*' Matches any sequence of zero or more characters.
  62183. **
  62184. ** '?' Matches exactly one character.
  62185. **
  62186. ** [...] Matches one character from the enclosed list of
  62187. ** characters.
  62188. **
  62189. ** [^...] Matches one character not in the enclosed list.
  62190. **
  62191. ** With the [...] and [^...] matching, a ']' character can be included
  62192. ** in the list by making it the first character after '[' or '^'. A
  62193. ** range of characters can be specified using '-'. Example:
  62194. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  62195. ** it the last character in the list.
  62196. **
  62197. ** This routine is usually quick, but can be N**2 in the worst case.
  62198. **
  62199. ** Hints: to match '*' or '?', put them in "[]". Like this:
  62200. **
  62201. ** abc[*]xyz Matches "abc*xyz" only
  62202. */
  62203. static int patternCompare(
  62204. const u8 *zPattern, /* The glob pattern */
  62205. const u8 *zString, /* The string to compare against the glob */
  62206. const struct compareInfo *pInfo, /* Information about how to do the compare */
  62207. const int esc /* The escape character */
  62208. ){
  62209. int c, c2;
  62210. int invert;
  62211. int seen;
  62212. u8 matchOne = pInfo->matchOne;
  62213. u8 matchAll = pInfo->matchAll;
  62214. u8 matchSet = pInfo->matchSet;
  62215. u8 noCase = pInfo->noCase;
  62216. int prevEscape = 0; /* True if the previous character was 'escape' */
  62217. while( (c = sqlite3Utf8Read(zPattern,0,&zPattern))!=0 ){
  62218. if( !prevEscape && c==matchAll ){
  62219. while( (c=sqlite3Utf8Read(zPattern,0,&zPattern)) == matchAll
  62220. || c == matchOne ){
  62221. if( c==matchOne && sqlite3Utf8Read(zString, 0, &zString)==0 ){
  62222. return 0;
  62223. }
  62224. }
  62225. if( c==0 ){
  62226. return 1;
  62227. }else if( c==esc ){
  62228. c = sqlite3Utf8Read(zPattern, 0, &zPattern);
  62229. if( c==0 ){
  62230. return 0;
  62231. }
  62232. }else if( c==matchSet ){
  62233. assert( esc==0 ); /* This is GLOB, not LIKE */
  62234. assert( matchSet<0x80 ); /* '[' is a single-byte character */
  62235. while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  62236. SQLITE_SKIP_UTF8(zString);
  62237. }
  62238. return *zString!=0;
  62239. }
  62240. while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){
  62241. if( noCase ){
  62242. GlogUpperToLower(c2);
  62243. GlogUpperToLower(c);
  62244. while( c2 != 0 && c2 != c ){
  62245. c2 = sqlite3Utf8Read(zString, 0, &zString);
  62246. GlogUpperToLower(c2);
  62247. }
  62248. }else{
  62249. while( c2 != 0 && c2 != c ){
  62250. c2 = sqlite3Utf8Read(zString, 0, &zString);
  62251. }
  62252. }
  62253. if( c2==0 ) return 0;
  62254. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  62255. }
  62256. return 0;
  62257. }else if( !prevEscape && c==matchOne ){
  62258. if( sqlite3Utf8Read(zString, 0, &zString)==0 ){
  62259. return 0;
  62260. }
  62261. }else if( c==matchSet ){
  62262. int prior_c = 0;
  62263. assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
  62264. seen = 0;
  62265. invert = 0;
  62266. c = sqlite3Utf8Read(zString, 0, &zString);
  62267. if( c==0 ) return 0;
  62268. c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
  62269. if( c2=='^' ){
  62270. invert = 1;
  62271. c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
  62272. }
  62273. if( c2==']' ){
  62274. if( c==']' ) seen = 1;
  62275. c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
  62276. }
  62277. while( c2 && c2!=']' ){
  62278. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  62279. c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
  62280. if( c>=prior_c && c<=c2 ) seen = 1;
  62281. prior_c = 0;
  62282. }else{
  62283. if( c==c2 ){
  62284. seen = 1;
  62285. }
  62286. prior_c = c2;
  62287. }
  62288. c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
  62289. }
  62290. if( c2==0 || (seen ^ invert)==0 ){
  62291. return 0;
  62292. }
  62293. }else if( esc==c && !prevEscape ){
  62294. prevEscape = 1;
  62295. }else{
  62296. c2 = sqlite3Utf8Read(zString, 0, &zString);
  62297. if( noCase ){
  62298. GlogUpperToLower(c);
  62299. GlogUpperToLower(c2);
  62300. }
  62301. if( c!=c2 ){
  62302. return 0;
  62303. }
  62304. prevEscape = 0;
  62305. }
  62306. }
  62307. return *zString==0;
  62308. }
  62309. /*
  62310. ** Count the number of times that the LIKE operator (or GLOB which is
  62311. ** just a variation of LIKE) gets called. This is used for testing
  62312. ** only.
  62313. */
  62314. #ifdef SQLITE_TEST
  62315. SQLITE_API int sqlite3_like_count = 0;
  62316. #endif
  62317. /*
  62318. ** Implementation of the like() SQL function. This function implements
  62319. ** the build-in LIKE operator. The first argument to the function is the
  62320. ** pattern and the second argument is the string. So, the SQL statements:
  62321. **
  62322. ** A LIKE B
  62323. **
  62324. ** is implemented as like(B,A).
  62325. **
  62326. ** This same function (with a different compareInfo structure) computes
  62327. ** the GLOB operator.
  62328. */
  62329. static void likeFunc(
  62330. sqlite3_context *context,
  62331. int argc,
  62332. sqlite3_value **argv
  62333. ){
  62334. const unsigned char *zA, *zB;
  62335. int escape = 0;
  62336. sqlite3 *db = sqlite3_context_db_handle(context);
  62337. zB = sqlite3_value_text(argv[0]);
  62338. zA = sqlite3_value_text(argv[1]);
  62339. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  62340. ** of deep recursion and N*N behavior in patternCompare().
  62341. */
  62342. if( sqlite3_value_bytes(argv[0]) >
  62343. db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  62344. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  62345. return;
  62346. }
  62347. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  62348. if( argc==3 ){
  62349. /* The escape character string must consist of a single UTF-8 character.
  62350. ** Otherwise, return an error.
  62351. */
  62352. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  62353. if( zEsc==0 ) return;
  62354. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  62355. sqlite3_result_error(context,
  62356. "ESCAPE expression must be a single character", -1);
  62357. return;
  62358. }
  62359. escape = sqlite3Utf8Read(zEsc, 0, &zEsc);
  62360. }
  62361. if( zA && zB ){
  62362. struct compareInfo *pInfo = sqlite3_user_data(context);
  62363. #ifdef SQLITE_TEST
  62364. sqlite3_like_count++;
  62365. #endif
  62366. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  62367. }
  62368. }
  62369. /*
  62370. ** Implementation of the NULLIF(x,y) function. The result is the first
  62371. ** argument if the arguments are different. The result is NULL if the
  62372. ** arguments are equal to each other.
  62373. */
  62374. static void nullifFunc(
  62375. sqlite3_context *context,
  62376. int NotUsed,
  62377. sqlite3_value **argv
  62378. ){
  62379. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  62380. UNUSED_PARAMETER(NotUsed);
  62381. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  62382. sqlite3_result_value(context, argv[0]);
  62383. }
  62384. }
  62385. /*
  62386. ** Implementation of the VERSION(*) function. The result is the version
  62387. ** of the SQLite library that is running.
  62388. */
  62389. static void versionFunc(
  62390. sqlite3_context *context,
  62391. int NotUsed,
  62392. sqlite3_value **NotUsed2
  62393. ){
  62394. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  62395. sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
  62396. }
  62397. /* Array for converting from half-bytes (nybbles) into ASCII hex
  62398. ** digits. */
  62399. static const char hexdigits[] = {
  62400. '0', '1', '2', '3', '4', '5', '6', '7',
  62401. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  62402. };
  62403. /*
  62404. ** EXPERIMENTAL - This is not an official function. The interface may
  62405. ** change. This function may disappear. Do not write code that depends
  62406. ** on this function.
  62407. **
  62408. ** Implementation of the QUOTE() function. This function takes a single
  62409. ** argument. If the argument is numeric, the return value is the same as
  62410. ** the argument. If the argument is NULL, the return value is the string
  62411. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  62412. ** single-quote escapes.
  62413. */
  62414. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  62415. if( argc<1 ) return;
  62416. switch( sqlite3_value_type(argv[0]) ){
  62417. case SQLITE_NULL: {
  62418. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  62419. break;
  62420. }
  62421. case SQLITE_INTEGER:
  62422. case SQLITE_FLOAT: {
  62423. sqlite3_result_value(context, argv[0]);
  62424. break;
  62425. }
  62426. case SQLITE_BLOB: {
  62427. char *zText = 0;
  62428. char const *zBlob = sqlite3_value_blob(argv[0]);
  62429. int nBlob = sqlite3_value_bytes(argv[0]);
  62430. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  62431. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  62432. if( zText ){
  62433. int i;
  62434. for(i=0; i<nBlob; i++){
  62435. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  62436. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  62437. }
  62438. zText[(nBlob*2)+2] = '\'';
  62439. zText[(nBlob*2)+3] = '\0';
  62440. zText[0] = 'X';
  62441. zText[1] = '\'';
  62442. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  62443. sqlite3_free(zText);
  62444. }
  62445. break;
  62446. }
  62447. case SQLITE_TEXT: {
  62448. int i,j;
  62449. u64 n;
  62450. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  62451. char *z;
  62452. if( zArg==0 ) return;
  62453. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  62454. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  62455. if( z ){
  62456. z[0] = '\'';
  62457. for(i=0, j=1; zArg[i]; i++){
  62458. z[j++] = zArg[i];
  62459. if( zArg[i]=='\'' ){
  62460. z[j++] = '\'';
  62461. }
  62462. }
  62463. z[j++] = '\'';
  62464. z[j] = 0;
  62465. sqlite3_result_text(context, z, j, sqlite3_free);
  62466. }
  62467. }
  62468. }
  62469. }
  62470. /*
  62471. ** The hex() function. Interpret the argument as a blob. Return
  62472. ** a hexadecimal rendering as text.
  62473. */
  62474. static void hexFunc(
  62475. sqlite3_context *context,
  62476. int argc,
  62477. sqlite3_value **argv
  62478. ){
  62479. int i, n;
  62480. const unsigned char *pBlob;
  62481. char *zHex, *z;
  62482. assert( argc==1 );
  62483. UNUSED_PARAMETER(argc);
  62484. pBlob = sqlite3_value_blob(argv[0]);
  62485. n = sqlite3_value_bytes(argv[0]);
  62486. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  62487. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  62488. if( zHex ){
  62489. for(i=0; i<n; i++, pBlob++){
  62490. unsigned char c = *pBlob;
  62491. *(z++) = hexdigits[(c>>4)&0xf];
  62492. *(z++) = hexdigits[c&0xf];
  62493. }
  62494. *z = 0;
  62495. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  62496. }
  62497. }
  62498. /*
  62499. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  62500. */
  62501. static void zeroblobFunc(
  62502. sqlite3_context *context,
  62503. int argc,
  62504. sqlite3_value **argv
  62505. ){
  62506. i64 n;
  62507. assert( argc==1 );
  62508. UNUSED_PARAMETER(argc);
  62509. n = sqlite3_value_int64(argv[0]);
  62510. if( n>SQLITE_MAX_LENGTH ){
  62511. sqlite3_result_error_toobig(context);
  62512. }else{
  62513. sqlite3_result_zeroblob(context, (int)n);
  62514. }
  62515. }
  62516. /*
  62517. ** The replace() function. Three arguments are all strings: call
  62518. ** them A, B, and C. The result is also a string which is derived
  62519. ** from A by replacing every occurance of B with C. The match
  62520. ** must be exact. Collating sequences are not used.
  62521. */
  62522. static void replaceFunc(
  62523. sqlite3_context *context,
  62524. int argc,
  62525. sqlite3_value **argv
  62526. ){
  62527. const unsigned char *zStr; /* The input string A */
  62528. const unsigned char *zPattern; /* The pattern string B */
  62529. const unsigned char *zRep; /* The replacement string C */
  62530. unsigned char *zOut; /* The output */
  62531. int nStr; /* Size of zStr */
  62532. int nPattern; /* Size of zPattern */
  62533. int nRep; /* Size of zRep */
  62534. i64 nOut; /* Maximum size of zOut */
  62535. int loopLimit; /* Last zStr[] that might match zPattern[] */
  62536. int i, j; /* Loop counters */
  62537. assert( argc==3 );
  62538. UNUSED_PARAMETER(argc);
  62539. zStr = sqlite3_value_text(argv[0]);
  62540. if( zStr==0 ) return;
  62541. nStr = sqlite3_value_bytes(argv[0]);
  62542. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  62543. zPattern = sqlite3_value_text(argv[1]);
  62544. if( zPattern==0 || zPattern[0]==0 ) return;
  62545. nPattern = sqlite3_value_bytes(argv[1]);
  62546. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  62547. zRep = sqlite3_value_text(argv[2]);
  62548. if( zRep==0 ) return;
  62549. nRep = sqlite3_value_bytes(argv[2]);
  62550. assert( zRep==sqlite3_value_text(argv[2]) );
  62551. nOut = nStr + 1;
  62552. assert( nOut<SQLITE_MAX_LENGTH );
  62553. zOut = contextMalloc(context, (i64)nOut);
  62554. if( zOut==0 ){
  62555. return;
  62556. }
  62557. loopLimit = nStr - nPattern;
  62558. for(i=j=0; i<=loopLimit; i++){
  62559. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  62560. zOut[j++] = zStr[i];
  62561. }else{
  62562. u8 *zOld;
  62563. sqlite3 *db = sqlite3_context_db_handle(context);
  62564. nOut += nRep - nPattern;
  62565. if( nOut>=db->aLimit[SQLITE_LIMIT_LENGTH] ){
  62566. sqlite3_result_error_toobig(context);
  62567. sqlite3DbFree(db, zOut);
  62568. return;
  62569. }
  62570. zOld = zOut;
  62571. zOut = sqlite3_realloc(zOut, (int)nOut);
  62572. if( zOut==0 ){
  62573. sqlite3_result_error_nomem(context);
  62574. sqlite3DbFree(db, zOld);
  62575. return;
  62576. }
  62577. memcpy(&zOut[j], zRep, nRep);
  62578. j += nRep;
  62579. i += nPattern-1;
  62580. }
  62581. }
  62582. assert( j+nStr-i+1==nOut );
  62583. memcpy(&zOut[j], &zStr[i], nStr-i);
  62584. j += nStr - i;
  62585. assert( j<=nOut );
  62586. zOut[j] = 0;
  62587. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  62588. }
  62589. /*
  62590. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  62591. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  62592. */
  62593. static void trimFunc(
  62594. sqlite3_context *context,
  62595. int argc,
  62596. sqlite3_value **argv
  62597. ){
  62598. const unsigned char *zIn; /* Input string */
  62599. const unsigned char *zCharSet; /* Set of characters to trim */
  62600. int nIn; /* Number of bytes in input */
  62601. int flags; /* 1: trimleft 2: trimright 3: trim */
  62602. int i; /* Loop counter */
  62603. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  62604. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  62605. int nChar; /* Number of characters in zCharSet */
  62606. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  62607. return;
  62608. }
  62609. zIn = sqlite3_value_text(argv[0]);
  62610. if( zIn==0 ) return;
  62611. nIn = sqlite3_value_bytes(argv[0]);
  62612. assert( zIn==sqlite3_value_text(argv[0]) );
  62613. if( argc==1 ){
  62614. static const unsigned char lenOne[] = { 1 };
  62615. static unsigned char * const azOne[] = { (u8*)" " };
  62616. nChar = 1;
  62617. aLen = (u8*)lenOne;
  62618. azChar = (unsigned char **)azOne;
  62619. zCharSet = 0;
  62620. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  62621. return;
  62622. }else{
  62623. const unsigned char *z;
  62624. for(z=zCharSet, nChar=0; *z; nChar++){
  62625. SQLITE_SKIP_UTF8(z);
  62626. }
  62627. if( nChar>0 ){
  62628. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  62629. if( azChar==0 ){
  62630. return;
  62631. }
  62632. aLen = (unsigned char*)&azChar[nChar];
  62633. for(z=zCharSet, nChar=0; *z; nChar++){
  62634. azChar[nChar] = (unsigned char *)z;
  62635. SQLITE_SKIP_UTF8(z);
  62636. aLen[nChar] = (u8)(z - azChar[nChar]);
  62637. }
  62638. }
  62639. }
  62640. if( nChar>0 ){
  62641. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  62642. if( flags & 1 ){
  62643. while( nIn>0 ){
  62644. int len = 0;
  62645. for(i=0; i<nChar; i++){
  62646. len = aLen[i];
  62647. if( memcmp(zIn, azChar[i], len)==0 ) break;
  62648. }
  62649. if( i>=nChar ) break;
  62650. zIn += len;
  62651. nIn -= len;
  62652. }
  62653. }
  62654. if( flags & 2 ){
  62655. while( nIn>0 ){
  62656. int len = 0;
  62657. for(i=0; i<nChar; i++){
  62658. len = aLen[i];
  62659. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  62660. }
  62661. if( i>=nChar ) break;
  62662. nIn -= len;
  62663. }
  62664. }
  62665. if( zCharSet ){
  62666. sqlite3_free(azChar);
  62667. }
  62668. }
  62669. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  62670. }
  62671. #ifdef SQLITE_SOUNDEX
  62672. /*
  62673. ** Compute the soundex encoding of a word.
  62674. */
  62675. static void soundexFunc(
  62676. sqlite3_context *context,
  62677. int argc,
  62678. sqlite3_value **argv
  62679. ){
  62680. char zResult[8];
  62681. const u8 *zIn;
  62682. int i, j;
  62683. static const unsigned char iCode[] = {
  62684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  62685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  62686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  62687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  62688. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  62689. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  62690. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  62691. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  62692. };
  62693. assert( argc==1 );
  62694. zIn = (u8*)sqlite3_value_text(argv[0]);
  62695. if( zIn==0 ) zIn = (u8*)"";
  62696. for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
  62697. if( zIn[i] ){
  62698. u8 prevcode = iCode[zIn[i]&0x7f];
  62699. zResult[0] = toupper(zIn[i]);
  62700. for(j=1; j<4 && zIn[i]; i++){
  62701. int code = iCode[zIn[i]&0x7f];
  62702. if( code>0 ){
  62703. if( code!=prevcode ){
  62704. prevcode = code;
  62705. zResult[j++] = code + '0';
  62706. }
  62707. }else{
  62708. prevcode = 0;
  62709. }
  62710. }
  62711. while( j<4 ){
  62712. zResult[j++] = '0';
  62713. }
  62714. zResult[j] = 0;
  62715. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  62716. }else{
  62717. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  62718. }
  62719. }
  62720. #endif
  62721. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  62722. /*
  62723. ** A function that loads a shared-library extension then returns NULL.
  62724. */
  62725. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  62726. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  62727. const char *zProc;
  62728. sqlite3 *db = sqlite3_context_db_handle(context);
  62729. char *zErrMsg = 0;
  62730. if( argc==2 ){
  62731. zProc = (const char *)sqlite3_value_text(argv[1]);
  62732. }else{
  62733. zProc = 0;
  62734. }
  62735. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  62736. sqlite3_result_error(context, zErrMsg, -1);
  62737. sqlite3_free(zErrMsg);
  62738. }
  62739. }
  62740. #endif
  62741. /*
  62742. ** An instance of the following structure holds the context of a
  62743. ** sum() or avg() aggregate computation.
  62744. */
  62745. typedef struct SumCtx SumCtx;
  62746. struct SumCtx {
  62747. double rSum; /* Floating point sum */
  62748. i64 iSum; /* Integer sum */
  62749. i64 cnt; /* Number of elements summed */
  62750. u8 overflow; /* True if integer overflow seen */
  62751. u8 approx; /* True if non-integer value was input to the sum */
  62752. };
  62753. /*
  62754. ** Routines used to compute the sum, average, and total.
  62755. **
  62756. ** The SUM() function follows the (broken) SQL standard which means
  62757. ** that it returns NULL if it sums over no inputs. TOTAL returns
  62758. ** 0.0 in that case. In addition, TOTAL always returns a float where
  62759. ** SUM might return an integer if it never encounters a floating point
  62760. ** value. TOTAL never fails, but SUM might through an exception if
  62761. ** it overflows an integer.
  62762. */
  62763. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  62764. SumCtx *p;
  62765. int type;
  62766. assert( argc==1 );
  62767. UNUSED_PARAMETER(argc);
  62768. p = sqlite3_aggregate_context(context, sizeof(*p));
  62769. type = sqlite3_value_numeric_type(argv[0]);
  62770. if( p && type!=SQLITE_NULL ){
  62771. p->cnt++;
  62772. if( type==SQLITE_INTEGER ){
  62773. i64 v = sqlite3_value_int64(argv[0]);
  62774. p->rSum += v;
  62775. if( (p->approx|p->overflow)==0 ){
  62776. i64 iNewSum = p->iSum + v;
  62777. int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
  62778. int s2 = (int)(v >> (sizeof(i64)*8-1));
  62779. int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
  62780. p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
  62781. p->iSum = iNewSum;
  62782. }
  62783. }else{
  62784. p->rSum += sqlite3_value_double(argv[0]);
  62785. p->approx = 1;
  62786. }
  62787. }
  62788. }
  62789. static void sumFinalize(sqlite3_context *context){
  62790. SumCtx *p;
  62791. p = sqlite3_aggregate_context(context, 0);
  62792. if( p && p->cnt>0 ){
  62793. if( p->overflow ){
  62794. sqlite3_result_error(context,"integer overflow",-1);
  62795. }else if( p->approx ){
  62796. sqlite3_result_double(context, p->rSum);
  62797. }else{
  62798. sqlite3_result_int64(context, p->iSum);
  62799. }
  62800. }
  62801. }
  62802. static void avgFinalize(sqlite3_context *context){
  62803. SumCtx *p;
  62804. p = sqlite3_aggregate_context(context, 0);
  62805. if( p && p->cnt>0 ){
  62806. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  62807. }
  62808. }
  62809. static void totalFinalize(sqlite3_context *context){
  62810. SumCtx *p;
  62811. p = sqlite3_aggregate_context(context, 0);
  62812. sqlite3_result_double(context, p ? p->rSum : 0.0);
  62813. }
  62814. /*
  62815. ** The following structure keeps track of state information for the
  62816. ** count() aggregate function.
  62817. */
  62818. typedef struct CountCtx CountCtx;
  62819. struct CountCtx {
  62820. i64 n;
  62821. };
  62822. /*
  62823. ** Routines to implement the count() aggregate function.
  62824. */
  62825. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  62826. CountCtx *p;
  62827. p = sqlite3_aggregate_context(context, sizeof(*p));
  62828. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  62829. p->n++;
  62830. }
  62831. }
  62832. static void countFinalize(sqlite3_context *context){
  62833. CountCtx *p;
  62834. p = sqlite3_aggregate_context(context, 0);
  62835. sqlite3_result_int64(context, p ? p->n : 0);
  62836. }
  62837. /*
  62838. ** Routines to implement min() and max() aggregate functions.
  62839. */
  62840. static void minmaxStep(
  62841. sqlite3_context *context,
  62842. int NotUsed,
  62843. sqlite3_value **argv
  62844. ){
  62845. Mem *pArg = (Mem *)argv[0];
  62846. Mem *pBest;
  62847. UNUSED_PARAMETER(NotUsed);
  62848. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  62849. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  62850. if( !pBest ) return;
  62851. if( pBest->flags ){
  62852. int max;
  62853. int cmp;
  62854. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  62855. /* This step function is used for both the min() and max() aggregates,
  62856. ** the only difference between the two being that the sense of the
  62857. ** comparison is inverted. For the max() aggregate, the
  62858. ** sqlite3_user_data() function returns (void *)-1. For min() it
  62859. ** returns (void *)db, where db is the sqlite3* database pointer.
  62860. ** Therefore the next statement sets variable 'max' to 1 for the max()
  62861. ** aggregate, or 0 for min().
  62862. */
  62863. max = sqlite3_user_data(context)!=0;
  62864. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  62865. if( (max && cmp<0) || (!max && cmp>0) ){
  62866. sqlite3VdbeMemCopy(pBest, pArg);
  62867. }
  62868. }else{
  62869. sqlite3VdbeMemCopy(pBest, pArg);
  62870. }
  62871. }
  62872. static void minMaxFinalize(sqlite3_context *context){
  62873. sqlite3_value *pRes;
  62874. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  62875. if( pRes ){
  62876. if( pRes->flags ){
  62877. sqlite3_result_value(context, pRes);
  62878. }
  62879. sqlite3VdbeMemRelease(pRes);
  62880. }
  62881. }
  62882. /*
  62883. ** group_concat(EXPR, ?SEPARATOR?)
  62884. */
  62885. static void groupConcatStep(
  62886. sqlite3_context *context,
  62887. int argc,
  62888. sqlite3_value **argv
  62889. ){
  62890. const char *zVal;
  62891. StrAccum *pAccum;
  62892. const char *zSep;
  62893. int nVal, nSep, i;
  62894. if( argc==0 || sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  62895. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  62896. if( pAccum ){
  62897. sqlite3 *db = sqlite3_context_db_handle(context);
  62898. pAccum->useMalloc = 1;
  62899. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  62900. if( pAccum->nChar ){
  62901. if( argc>1 ){
  62902. zSep = (char*)sqlite3_value_text(argv[argc-1]);
  62903. nSep = sqlite3_value_bytes(argv[argc-1]);
  62904. }else{
  62905. zSep = ",";
  62906. nSep = 1;
  62907. }
  62908. sqlite3StrAccumAppend(pAccum, zSep, nSep);
  62909. }
  62910. i = 0;
  62911. do{
  62912. zVal = (char*)sqlite3_value_text(argv[i]);
  62913. nVal = sqlite3_value_bytes(argv[i]);
  62914. sqlite3StrAccumAppend(pAccum, zVal, nVal);
  62915. i++;
  62916. }while( i<argc-1 );
  62917. }
  62918. }
  62919. static void groupConcatFinalize(sqlite3_context *context){
  62920. StrAccum *pAccum;
  62921. pAccum = sqlite3_aggregate_context(context, 0);
  62922. if( pAccum ){
  62923. if( pAccum->tooBig ){
  62924. sqlite3_result_error_toobig(context);
  62925. }else if( pAccum->mallocFailed ){
  62926. sqlite3_result_error_nomem(context);
  62927. }else{
  62928. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  62929. sqlite3_free);
  62930. }
  62931. }
  62932. }
  62933. /*
  62934. ** This function registered all of the above C functions as SQL
  62935. ** functions. This should be the only routine in this file with
  62936. ** external linkage.
  62937. */
  62938. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  62939. #ifndef SQLITE_OMIT_ALTERTABLE
  62940. sqlite3AlterFunctions(db);
  62941. #endif
  62942. if( !db->mallocFailed ){
  62943. int rc = sqlite3_overload_function(db, "MATCH", 2);
  62944. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  62945. if( rc==SQLITE_NOMEM ){
  62946. db->mallocFailed = 1;
  62947. }
  62948. }
  62949. #ifdef SQLITE_SSE
  62950. (void)sqlite3SseFunctions(db);
  62951. #endif
  62952. }
  62953. /*
  62954. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  62955. */
  62956. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  62957. FuncDef *pDef;
  62958. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  62959. 2, SQLITE_UTF8, 0);
  62960. if( pDef ){
  62961. pDef->flags = flagVal;
  62962. }
  62963. }
  62964. /*
  62965. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  62966. ** parameter determines whether or not the LIKE operator is case
  62967. ** sensitive. GLOB is always case sensitive.
  62968. */
  62969. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  62970. struct compareInfo *pInfo;
  62971. if( caseSensitive ){
  62972. pInfo = (struct compareInfo*)&likeInfoAlt;
  62973. }else{
  62974. pInfo = (struct compareInfo*)&likeInfoNorm;
  62975. }
  62976. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
  62977. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
  62978. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  62979. (struct compareInfo*)&globInfo, likeFunc, 0,0);
  62980. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  62981. setLikeOptFlag(db, "like",
  62982. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  62983. }
  62984. /*
  62985. ** pExpr points to an expression which implements a function. If
  62986. ** it is appropriate to apply the LIKE optimization to that function
  62987. ** then set aWc[0] through aWc[2] to the wildcard characters and
  62988. ** return TRUE. If the function is not a LIKE-style function then
  62989. ** return FALSE.
  62990. */
  62991. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  62992. FuncDef *pDef;
  62993. if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
  62994. return 0;
  62995. }
  62996. if( pExpr->pList->nExpr!=2 ){
  62997. return 0;
  62998. }
  62999. pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
  63000. SQLITE_UTF8, 0);
  63001. if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
  63002. return 0;
  63003. }
  63004. /* The memcpy() statement assumes that the wildcard characters are
  63005. ** the first three statements in the compareInfo structure. The
  63006. ** asserts() that follow verify that assumption
  63007. */
  63008. memcpy(aWc, pDef->pUserData, 3);
  63009. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  63010. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  63011. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  63012. *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
  63013. return 1;
  63014. }
  63015. /*
  63016. ** All all of the FuncDef structures in the aBuiltinFunc[] array above
  63017. ** to the global function hash table. This occurs at start-time (as
  63018. ** a consequence of calling sqlite3_initialize()).
  63019. **
  63020. ** After this routine runs
  63021. */
  63022. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  63023. /*
  63024. ** The following array holds FuncDef structures for all of the functions
  63025. ** defined in this file.
  63026. **
  63027. ** The array cannot be constant since changes are made to the
  63028. ** FuncDef.pHash elements at start-time. The elements of this array
  63029. ** are read-only after initialization is complete.
  63030. */
  63031. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  63032. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  63033. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  63034. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  63035. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  63036. FUNCTION(trim, 1, 3, 0, trimFunc ),
  63037. FUNCTION(trim, 2, 3, 0, trimFunc ),
  63038. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  63039. FUNCTION(min, 0, 0, 1, 0 ),
  63040. AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
  63041. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  63042. FUNCTION(max, 0, 1, 1, 0 ),
  63043. AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
  63044. FUNCTION(typeof, 1, 0, 0, typeofFunc ),
  63045. FUNCTION(length, 1, 0, 0, lengthFunc ),
  63046. FUNCTION(substr, 2, 0, 0, substrFunc ),
  63047. FUNCTION(substr, 3, 0, 0, substrFunc ),
  63048. FUNCTION(abs, 1, 0, 0, absFunc ),
  63049. FUNCTION(round, 1, 0, 0, roundFunc ),
  63050. FUNCTION(round, 2, 0, 0, roundFunc ),
  63051. FUNCTION(upper, 1, 0, 0, upperFunc ),
  63052. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  63053. FUNCTION(coalesce, 1, 0, 0, 0 ),
  63054. FUNCTION(coalesce, -1, 0, 0, ifnullFunc ),
  63055. FUNCTION(coalesce, 0, 0, 0, 0 ),
  63056. FUNCTION(hex, 1, 0, 0, hexFunc ),
  63057. FUNCTION(ifnull, 2, 0, 1, ifnullFunc ),
  63058. FUNCTION(random, -1, 0, 0, randomFunc ),
  63059. FUNCTION(randomblob, 1, 0, 0, randomBlob ),
  63060. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  63061. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  63062. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  63063. FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  63064. FUNCTION(changes, 0, 0, 0, changes ),
  63065. FUNCTION(total_changes, 0, 0, 0, total_changes ),
  63066. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  63067. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  63068. #ifdef SQLITE_SOUNDEX
  63069. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  63070. #endif
  63071. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  63072. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  63073. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  63074. #endif
  63075. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  63076. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  63077. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  63078. AGGREGATE(count, 0, 0, 0, countStep, countFinalize ),
  63079. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  63080. AGGREGATE(group_concat, -1, 0, 0, groupConcatStep, groupConcatFinalize),
  63081. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  63082. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  63083. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  63084. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  63085. #else
  63086. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  63087. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  63088. #endif
  63089. };
  63090. int i;
  63091. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  63092. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  63093. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  63094. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  63095. }
  63096. sqlite3RegisterDateTimeFunctions();
  63097. }
  63098. /************** End of func.c ************************************************/
  63099. /************** Begin file insert.c ******************************************/
  63100. /*
  63101. ** 2001 September 15
  63102. **
  63103. ** The author disclaims copyright to this source code. In place of
  63104. ** a legal notice, here is a blessing:
  63105. **
  63106. ** May you do good and not evil.
  63107. ** May you find forgiveness for yourself and forgive others.
  63108. ** May you share freely, never taking more than you give.
  63109. **
  63110. *************************************************************************
  63111. ** This file contains C code routines that are called by the parser
  63112. ** to handle INSERT statements in SQLite.
  63113. **
  63114. ** $Id: insert.c,v 1.256 2008/12/10 21:19:57 drh Exp $
  63115. */
  63116. /*
  63117. ** Set P4 of the most recently inserted opcode to a column affinity
  63118. ** string for index pIdx. A column affinity string has one character
  63119. ** for each column in the table, according to the affinity of the column:
  63120. **
  63121. ** Character Column affinity
  63122. ** ------------------------------
  63123. ** 'a' TEXT
  63124. ** 'b' NONE
  63125. ** 'c' NUMERIC
  63126. ** 'd' INTEGER
  63127. ** 'e' REAL
  63128. **
  63129. ** An extra 'b' is appended to the end of the string to cover the
  63130. ** rowid that appears as the last column in every index.
  63131. */
  63132. SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  63133. if( !pIdx->zColAff ){
  63134. /* The first time a column affinity string for a particular index is
  63135. ** required, it is allocated and populated here. It is then stored as
  63136. ** a member of the Index structure for subsequent use.
  63137. **
  63138. ** The column affinity string will eventually be deleted by
  63139. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  63140. ** up.
  63141. */
  63142. int n;
  63143. Table *pTab = pIdx->pTable;
  63144. sqlite3 *db = sqlite3VdbeDb(v);
  63145. pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
  63146. if( !pIdx->zColAff ){
  63147. db->mallocFailed = 1;
  63148. return;
  63149. }
  63150. for(n=0; n<pIdx->nColumn; n++){
  63151. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  63152. }
  63153. pIdx->zColAff[n++] = SQLITE_AFF_NONE;
  63154. pIdx->zColAff[n] = 0;
  63155. }
  63156. sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
  63157. }
  63158. /*
  63159. ** Set P4 of the most recently inserted opcode to a column affinity
  63160. ** string for table pTab. A column affinity string has one character
  63161. ** for each column indexed by the index, according to the affinity of the
  63162. ** column:
  63163. **
  63164. ** Character Column affinity
  63165. ** ------------------------------
  63166. ** 'a' TEXT
  63167. ** 'b' NONE
  63168. ** 'c' NUMERIC
  63169. ** 'd' INTEGER
  63170. ** 'e' REAL
  63171. */
  63172. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  63173. /* The first time a column affinity string for a particular table
  63174. ** is required, it is allocated and populated here. It is then
  63175. ** stored as a member of the Table structure for subsequent use.
  63176. **
  63177. ** The column affinity string will eventually be deleted by
  63178. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  63179. */
  63180. if( !pTab->zColAff ){
  63181. char *zColAff;
  63182. int i;
  63183. sqlite3 *db = sqlite3VdbeDb(v);
  63184. zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
  63185. if( !zColAff ){
  63186. db->mallocFailed = 1;
  63187. return;
  63188. }
  63189. for(i=0; i<pTab->nCol; i++){
  63190. zColAff[i] = pTab->aCol[i].affinity;
  63191. }
  63192. zColAff[pTab->nCol] = '\0';
  63193. pTab->zColAff = zColAff;
  63194. }
  63195. sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
  63196. }
  63197. /*
  63198. ** Return non-zero if the table pTab in database iDb or any of its indices
  63199. ** have been opened at any point in the VDBE program beginning at location
  63200. ** iStartAddr throught the end of the program. This is used to see if
  63201. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  63202. ** run without using temporary table for the results of the SELECT.
  63203. */
  63204. static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
  63205. int i;
  63206. int iEnd = sqlite3VdbeCurrentAddr(v);
  63207. for(i=iStartAddr; i<iEnd; i++){
  63208. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  63209. assert( pOp!=0 );
  63210. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  63211. Index *pIndex;
  63212. int tnum = pOp->p2;
  63213. if( tnum==pTab->tnum ){
  63214. return 1;
  63215. }
  63216. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  63217. if( tnum==pIndex->tnum ){
  63218. return 1;
  63219. }
  63220. }
  63221. }
  63222. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63223. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
  63224. assert( pOp->p4.pVtab!=0 );
  63225. assert( pOp->p4type==P4_VTAB );
  63226. return 1;
  63227. }
  63228. #endif
  63229. }
  63230. return 0;
  63231. }
  63232. #ifndef SQLITE_OMIT_AUTOINCREMENT
  63233. /*
  63234. ** Write out code to initialize the autoincrement logic. This code
  63235. ** looks up the current autoincrement value in the sqlite_sequence
  63236. ** table and stores that value in a register. Code generated by
  63237. ** autoIncStep() will keep that register holding the largest
  63238. ** rowid value. Code generated by autoIncEnd() will write the new
  63239. ** largest value of the counter back into the sqlite_sequence table.
  63240. **
  63241. ** This routine returns the index of the mem[] cell that contains
  63242. ** the maximum rowid counter.
  63243. **
  63244. ** Three consecutive registers are allocated by this routine. The
  63245. ** first two hold the name of the target table and the maximum rowid
  63246. ** inserted into the target table, respectively.
  63247. ** The third holds the rowid in sqlite_sequence where we will
  63248. ** write back the revised maximum rowid. This routine returns the
  63249. ** index of the second of these three registers.
  63250. */
  63251. static int autoIncBegin(
  63252. Parse *pParse, /* Parsing context */
  63253. int iDb, /* Index of the database holding pTab */
  63254. Table *pTab /* The table we are writing to */
  63255. ){
  63256. int memId = 0; /* Register holding maximum rowid */
  63257. if( pTab->tabFlags & TF_Autoincrement ){
  63258. Vdbe *v = pParse->pVdbe;
  63259. Db *pDb = &pParse->db->aDb[iDb];
  63260. int iCur = pParse->nTab;
  63261. int addr; /* Address of the top of the loop */
  63262. assert( v );
  63263. pParse->nMem++; /* Holds name of table */
  63264. memId = ++pParse->nMem;
  63265. pParse->nMem++;
  63266. sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  63267. addr = sqlite3VdbeCurrentAddr(v);
  63268. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
  63269. sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
  63270. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
  63271. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
  63272. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  63273. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
  63274. sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
  63275. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  63276. sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
  63277. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  63278. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  63279. }
  63280. return memId;
  63281. }
  63282. /*
  63283. ** Update the maximum rowid for an autoincrement calculation.
  63284. **
  63285. ** This routine should be called when the top of the stack holds a
  63286. ** new rowid that is about to be inserted. If that new rowid is
  63287. ** larger than the maximum rowid in the memId memory cell, then the
  63288. ** memory cell is updated. The stack is unchanged.
  63289. */
  63290. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  63291. if( memId>0 ){
  63292. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  63293. }
  63294. }
  63295. /*
  63296. ** After doing one or more inserts, the maximum rowid is stored
  63297. ** in reg[memId]. Generate code to write this value back into the
  63298. ** the sqlite_sequence table.
  63299. */
  63300. static void autoIncEnd(
  63301. Parse *pParse, /* The parsing context */
  63302. int iDb, /* Index of the database holding pTab */
  63303. Table *pTab, /* Table we are inserting into */
  63304. int memId /* Memory cell holding the maximum rowid */
  63305. ){
  63306. if( pTab->tabFlags & TF_Autoincrement ){
  63307. int iCur = pParse->nTab;
  63308. Vdbe *v = pParse->pVdbe;
  63309. Db *pDb = &pParse->db->aDb[iDb];
  63310. int j1;
  63311. int iRec = ++pParse->nMem; /* Memory cell used for record */
  63312. assert( v );
  63313. sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  63314. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
  63315. sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
  63316. sqlite3VdbeJumpHere(v, j1);
  63317. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  63318. sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
  63319. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  63320. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  63321. }
  63322. }
  63323. #else
  63324. /*
  63325. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  63326. ** above are all no-ops
  63327. */
  63328. # define autoIncBegin(A,B,C) (0)
  63329. # define autoIncStep(A,B,C)
  63330. # define autoIncEnd(A,B,C,D)
  63331. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  63332. /* Forward declaration */
  63333. static int xferOptimization(
  63334. Parse *pParse, /* Parser context */
  63335. Table *pDest, /* The table we are inserting into */
  63336. Select *pSelect, /* A SELECT statement to use as the data source */
  63337. int onError, /* How to handle constraint errors */
  63338. int iDbDest /* The database of pDest */
  63339. );
  63340. /*
  63341. ** This routine is call to handle SQL of the following forms:
  63342. **
  63343. ** insert into TABLE (IDLIST) values(EXPRLIST)
  63344. ** insert into TABLE (IDLIST) select
  63345. **
  63346. ** The IDLIST following the table name is always optional. If omitted,
  63347. ** then a list of all columns for the table is substituted. The IDLIST
  63348. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  63349. **
  63350. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  63351. ** statement above, and pSelect is NULL. For the second form, pList is
  63352. ** NULL and pSelect is a pointer to the select statement used to generate
  63353. ** data for the insert.
  63354. **
  63355. ** The code generated follows one of four templates. For a simple
  63356. ** select with data coming from a VALUES clause, the code executes
  63357. ** once straight down through. Pseudo-code follows (we call this
  63358. ** the "1st template"):
  63359. **
  63360. ** open write cursor to <table> and its indices
  63361. ** puts VALUES clause expressions onto the stack
  63362. ** write the resulting record into <table>
  63363. ** cleanup
  63364. **
  63365. ** The three remaining templates assume the statement is of the form
  63366. **
  63367. ** INSERT INTO <table> SELECT ...
  63368. **
  63369. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  63370. ** in other words if the SELECT pulls all columns from a single table
  63371. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  63372. ** if <table2> and <table1> are distinct tables but have identical
  63373. ** schemas, including all the same indices, then a special optimization
  63374. ** is invoked that copies raw records from <table2> over to <table1>.
  63375. ** See the xferOptimization() function for the implementation of this
  63376. ** template. This is the 2nd template.
  63377. **
  63378. ** open a write cursor to <table>
  63379. ** open read cursor on <table2>
  63380. ** transfer all records in <table2> over to <table>
  63381. ** close cursors
  63382. ** foreach index on <table>
  63383. ** open a write cursor on the <table> index
  63384. ** open a read cursor on the corresponding <table2> index
  63385. ** transfer all records from the read to the write cursors
  63386. ** close cursors
  63387. ** end foreach
  63388. **
  63389. ** The 3rd template is for when the second template does not apply
  63390. ** and the SELECT clause does not read from <table> at any time.
  63391. ** The generated code follows this template:
  63392. **
  63393. ** EOF <- 0
  63394. ** X <- A
  63395. ** goto B
  63396. ** A: setup for the SELECT
  63397. ** loop over the rows in the SELECT
  63398. ** load values into registers R..R+n
  63399. ** yield X
  63400. ** end loop
  63401. ** cleanup after the SELECT
  63402. ** EOF <- 1
  63403. ** yield X
  63404. ** goto A
  63405. ** B: open write cursor to <table> and its indices
  63406. ** C: yield X
  63407. ** if EOF goto D
  63408. ** insert the select result into <table> from R..R+n
  63409. ** goto C
  63410. ** D: cleanup
  63411. **
  63412. ** The 4th template is used if the insert statement takes its
  63413. ** values from a SELECT but the data is being inserted into a table
  63414. ** that is also read as part of the SELECT. In the third form,
  63415. ** we have to use a intermediate table to store the results of
  63416. ** the select. The template is like this:
  63417. **
  63418. ** EOF <- 0
  63419. ** X <- A
  63420. ** goto B
  63421. ** A: setup for the SELECT
  63422. ** loop over the tables in the SELECT
  63423. ** load value into register R..R+n
  63424. ** yield X
  63425. ** end loop
  63426. ** cleanup after the SELECT
  63427. ** EOF <- 1
  63428. ** yield X
  63429. ** halt-error
  63430. ** B: open temp table
  63431. ** L: yield X
  63432. ** if EOF goto M
  63433. ** insert row from R..R+n into temp table
  63434. ** goto L
  63435. ** M: open write cursor to <table> and its indices
  63436. ** rewind temp table
  63437. ** C: loop over rows of intermediate table
  63438. ** transfer values form intermediate table into <table>
  63439. ** end loop
  63440. ** D: cleanup
  63441. */
  63442. SQLITE_PRIVATE void sqlite3Insert(
  63443. Parse *pParse, /* Parser context */
  63444. SrcList *pTabList, /* Name of table into which we are inserting */
  63445. ExprList *pList, /* List of values to be inserted */
  63446. Select *pSelect, /* A SELECT statement to use as the data source */
  63447. IdList *pColumn, /* Column names corresponding to IDLIST. */
  63448. int onError /* How to handle constraint errors */
  63449. ){
  63450. sqlite3 *db; /* The main database structure */
  63451. Table *pTab; /* The table to insert into. aka TABLE */
  63452. char *zTab; /* Name of the table into which we are inserting */
  63453. const char *zDb; /* Name of the database holding this table */
  63454. int i, j, idx; /* Loop counters */
  63455. Vdbe *v; /* Generate code into this virtual machine */
  63456. Index *pIdx; /* For looping over indices of the table */
  63457. int nColumn; /* Number of columns in the data */
  63458. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  63459. int baseCur = 0; /* VDBE Cursor number for pTab */
  63460. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  63461. int endOfLoop; /* Label for the end of the insertion loop */
  63462. int useTempTable = 0; /* Store SELECT results in intermediate table */
  63463. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  63464. int addrInsTop = 0; /* Jump to label "D" */
  63465. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  63466. int addrSelect = 0; /* Address of coroutine that implements the SELECT */
  63467. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  63468. int newIdx = -1; /* Cursor for the NEW pseudo-table */
  63469. int iDb; /* Index of database holding TABLE */
  63470. Db *pDb; /* The database containing table being inserted into */
  63471. int appendFlag = 0; /* True if the insert is likely to be an append */
  63472. /* Register allocations */
  63473. int regFromSelect = 0;/* Base register for data coming from SELECT */
  63474. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  63475. int regRowCount = 0; /* Memory cell used for the row counter */
  63476. int regIns; /* Block of regs holding rowid+data being inserted */
  63477. int regRowid; /* registers holding insert rowid */
  63478. int regData; /* register holding first column to insert */
  63479. int regRecord; /* Holds the assemblied row record */
  63480. int regEof = 0; /* Register recording end of SELECT data */
  63481. int *aRegIdx = 0; /* One register allocated to each index */
  63482. #ifndef SQLITE_OMIT_TRIGGER
  63483. int isView; /* True if attempting to insert into a view */
  63484. int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
  63485. #endif
  63486. db = pParse->db;
  63487. memset(&dest, 0, sizeof(dest));
  63488. if( pParse->nErr || db->mallocFailed ){
  63489. goto insert_cleanup;
  63490. }
  63491. /* Locate the table into which we will be inserting new information.
  63492. */
  63493. assert( pTabList->nSrc==1 );
  63494. zTab = pTabList->a[0].zName;
  63495. if( zTab==0 ) goto insert_cleanup;
  63496. pTab = sqlite3SrcListLookup(pParse, pTabList);
  63497. if( pTab==0 ){
  63498. goto insert_cleanup;
  63499. }
  63500. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  63501. assert( iDb<db->nDb );
  63502. pDb = &db->aDb[iDb];
  63503. zDb = pDb->zName;
  63504. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  63505. goto insert_cleanup;
  63506. }
  63507. /* Figure out if we have any triggers and if the table being
  63508. ** inserted into is a view
  63509. */
  63510. #ifndef SQLITE_OMIT_TRIGGER
  63511. triggers_exist = sqlite3TriggersExist(pTab, TK_INSERT, 0);
  63512. isView = pTab->pSelect!=0;
  63513. #else
  63514. # define triggers_exist 0
  63515. # define isView 0
  63516. #endif
  63517. #ifdef SQLITE_OMIT_VIEW
  63518. # undef isView
  63519. # define isView 0
  63520. #endif
  63521. /* Ensure that:
  63522. * (a) the table is not read-only,
  63523. * (b) that if it is a view then ON INSERT triggers exist
  63524. */
  63525. if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
  63526. goto insert_cleanup;
  63527. }
  63528. assert( pTab!=0 );
  63529. /* If pTab is really a view, make sure it has been initialized.
  63530. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  63531. ** module table).
  63532. */
  63533. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  63534. goto insert_cleanup;
  63535. }
  63536. /* Allocate a VDBE
  63537. */
  63538. v = sqlite3GetVdbe(pParse);
  63539. if( v==0 ) goto insert_cleanup;
  63540. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  63541. sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
  63542. /* if there are row triggers, allocate a temp table for new.* references. */
  63543. if( triggers_exist ){
  63544. newIdx = pParse->nTab++;
  63545. }
  63546. #ifndef SQLITE_OMIT_XFER_OPT
  63547. /* If the statement is of the form
  63548. **
  63549. ** INSERT INTO <table1> SELECT * FROM <table2>;
  63550. **
  63551. ** Then special optimizations can be applied that make the transfer
  63552. ** very fast and which reduce fragmentation of indices.
  63553. **
  63554. ** This is the 2nd template.
  63555. */
  63556. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  63557. assert( !triggers_exist );
  63558. assert( pList==0 );
  63559. goto insert_cleanup;
  63560. }
  63561. #endif /* SQLITE_OMIT_XFER_OPT */
  63562. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  63563. ** sqlite_sequence table and store it in memory cell regAutoinc.
  63564. */
  63565. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  63566. /* Figure out how many columns of data are supplied. If the data
  63567. ** is coming from a SELECT statement, then generate a co-routine that
  63568. ** produces a single row of the SELECT on each invocation. The
  63569. ** co-routine is the common header to the 3rd and 4th templates.
  63570. */
  63571. if( pSelect ){
  63572. /* Data is coming from a SELECT. Generate code to implement that SELECT
  63573. ** as a co-routine. The code is common to both the 3rd and 4th
  63574. ** templates:
  63575. **
  63576. ** EOF <- 0
  63577. ** X <- A
  63578. ** goto B
  63579. ** A: setup for the SELECT
  63580. ** loop over the tables in the SELECT
  63581. ** load value into register R..R+n
  63582. ** yield X
  63583. ** end loop
  63584. ** cleanup after the SELECT
  63585. ** EOF <- 1
  63586. ** yield X
  63587. ** halt-error
  63588. **
  63589. ** On each invocation of the co-routine, it puts a single row of the
  63590. ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
  63591. ** (These output registers are allocated by sqlite3Select().) When
  63592. ** the SELECT completes, it sets the EOF flag stored in regEof.
  63593. */
  63594. int rc, j1;
  63595. regEof = ++pParse->nMem;
  63596. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
  63597. VdbeComment((v, "SELECT eof flag"));
  63598. sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
  63599. addrSelect = sqlite3VdbeCurrentAddr(v)+2;
  63600. sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
  63601. j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  63602. VdbeComment((v, "Jump over SELECT coroutine"));
  63603. /* Resolve the expressions in the SELECT statement and execute it. */
  63604. rc = sqlite3Select(pParse, pSelect, &dest);
  63605. if( rc || pParse->nErr || db->mallocFailed ){
  63606. goto insert_cleanup;
  63607. }
  63608. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
  63609. sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
  63610. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
  63611. VdbeComment((v, "End of SELECT coroutine"));
  63612. sqlite3VdbeJumpHere(v, j1); /* label B: */
  63613. regFromSelect = dest.iMem;
  63614. assert( pSelect->pEList );
  63615. nColumn = pSelect->pEList->nExpr;
  63616. assert( dest.nMem==nColumn );
  63617. /* Set useTempTable to TRUE if the result of the SELECT statement
  63618. ** should be written into a temporary table (template 4). Set to
  63619. ** FALSE if each* row of the SELECT can be written directly into
  63620. ** the destination table (template 3).
  63621. **
  63622. ** A temp table must be used if the table being updated is also one
  63623. ** of the tables being read by the SELECT statement. Also use a
  63624. ** temp table in the case of row triggers.
  63625. */
  63626. if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
  63627. useTempTable = 1;
  63628. }
  63629. if( useTempTable ){
  63630. /* Invoke the coroutine to extract information from the SELECT
  63631. ** and add it to a transient table srcTab. The code generated
  63632. ** here is from the 4th template:
  63633. **
  63634. ** B: open temp table
  63635. ** L: yield X
  63636. ** if EOF goto M
  63637. ** insert row from R..R+n into temp table
  63638. ** goto L
  63639. ** M: ...
  63640. */
  63641. int regRec; /* Register to hold packed record */
  63642. int regTempRowid; /* Register to hold temp table ROWID */
  63643. int addrTop; /* Label "L" */
  63644. int addrIf; /* Address of jump to M */
  63645. srcTab = pParse->nTab++;
  63646. regRec = sqlite3GetTempReg(pParse);
  63647. regTempRowid = sqlite3GetTempReg(pParse);
  63648. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  63649. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
  63650. addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
  63651. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  63652. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  63653. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  63654. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  63655. sqlite3VdbeJumpHere(v, addrIf);
  63656. sqlite3ReleaseTempReg(pParse, regRec);
  63657. sqlite3ReleaseTempReg(pParse, regTempRowid);
  63658. }
  63659. }else{
  63660. /* This is the case if the data for the INSERT is coming from a VALUES
  63661. ** clause
  63662. */
  63663. NameContext sNC;
  63664. memset(&sNC, 0, sizeof(sNC));
  63665. sNC.pParse = pParse;
  63666. srcTab = -1;
  63667. assert( useTempTable==0 );
  63668. nColumn = pList ? pList->nExpr : 0;
  63669. for(i=0; i<nColumn; i++){
  63670. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  63671. goto insert_cleanup;
  63672. }
  63673. }
  63674. }
  63675. /* Make sure the number of columns in the source data matches the number
  63676. ** of columns to be inserted into the table.
  63677. */
  63678. if( IsVirtual(pTab) ){
  63679. for(i=0; i<pTab->nCol; i++){
  63680. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  63681. }
  63682. }
  63683. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  63684. sqlite3ErrorMsg(pParse,
  63685. "table %S has %d columns but %d values were supplied",
  63686. pTabList, 0, pTab->nCol, nColumn);
  63687. goto insert_cleanup;
  63688. }
  63689. if( pColumn!=0 && nColumn!=pColumn->nId ){
  63690. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  63691. goto insert_cleanup;
  63692. }
  63693. /* If the INSERT statement included an IDLIST term, then make sure
  63694. ** all elements of the IDLIST really are columns of the table and
  63695. ** remember the column indices.
  63696. **
  63697. ** If the table has an INTEGER PRIMARY KEY column and that column
  63698. ** is named in the IDLIST, then record in the keyColumn variable
  63699. ** the index into IDLIST of the primary key column. keyColumn is
  63700. ** the index of the primary key as it appears in IDLIST, not as
  63701. ** is appears in the original table. (The index of the primary
  63702. ** key in the original table is pTab->iPKey.)
  63703. */
  63704. if( pColumn ){
  63705. for(i=0; i<pColumn->nId; i++){
  63706. pColumn->a[i].idx = -1;
  63707. }
  63708. for(i=0; i<pColumn->nId; i++){
  63709. for(j=0; j<pTab->nCol; j++){
  63710. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  63711. pColumn->a[i].idx = j;
  63712. if( j==pTab->iPKey ){
  63713. keyColumn = i;
  63714. }
  63715. break;
  63716. }
  63717. }
  63718. if( j>=pTab->nCol ){
  63719. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  63720. keyColumn = i;
  63721. }else{
  63722. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  63723. pTabList, 0, pColumn->a[i].zName);
  63724. pParse->nErr++;
  63725. goto insert_cleanup;
  63726. }
  63727. }
  63728. }
  63729. }
  63730. /* If there is no IDLIST term but the table has an integer primary
  63731. ** key, the set the keyColumn variable to the primary key column index
  63732. ** in the original table definition.
  63733. */
  63734. if( pColumn==0 && nColumn>0 ){
  63735. keyColumn = pTab->iPKey;
  63736. }
  63737. /* Open the temp table for FOR EACH ROW triggers
  63738. */
  63739. if( triggers_exist ){
  63740. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
  63741. sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
  63742. }
  63743. /* Initialize the count of rows to be inserted
  63744. */
  63745. if( db->flags & SQLITE_CountRows ){
  63746. regRowCount = ++pParse->nMem;
  63747. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  63748. }
  63749. /* If this is not a view, open the table and and all indices */
  63750. if( !isView ){
  63751. int nIdx;
  63752. baseCur = pParse->nTab;
  63753. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
  63754. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  63755. if( aRegIdx==0 ){
  63756. goto insert_cleanup;
  63757. }
  63758. for(i=0; i<nIdx; i++){
  63759. aRegIdx[i] = ++pParse->nMem;
  63760. }
  63761. }
  63762. /* This is the top of the main insertion loop */
  63763. if( useTempTable ){
  63764. /* This block codes the top of loop only. The complete loop is the
  63765. ** following pseudocode (template 4):
  63766. **
  63767. ** rewind temp table
  63768. ** C: loop over rows of intermediate table
  63769. ** transfer values form intermediate table into <table>
  63770. ** end loop
  63771. ** D: ...
  63772. */
  63773. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
  63774. addrCont = sqlite3VdbeCurrentAddr(v);
  63775. }else if( pSelect ){
  63776. /* This block codes the top of loop only. The complete loop is the
  63777. ** following pseudocode (template 3):
  63778. **
  63779. ** C: yield X
  63780. ** if EOF goto D
  63781. ** insert the select result into <table> from R..R+n
  63782. ** goto C
  63783. ** D: ...
  63784. */
  63785. addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
  63786. addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  63787. }
  63788. /* Allocate registers for holding the rowid of the new row,
  63789. ** the content of the new row, and the assemblied row record.
  63790. */
  63791. regRecord = ++pParse->nMem;
  63792. regRowid = regIns = pParse->nMem+1;
  63793. pParse->nMem += pTab->nCol + 1;
  63794. if( IsVirtual(pTab) ){
  63795. regRowid++;
  63796. pParse->nMem++;
  63797. }
  63798. regData = regRowid+1;
  63799. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  63800. */
  63801. endOfLoop = sqlite3VdbeMakeLabel(v);
  63802. if( triggers_exist & TRIGGER_BEFORE ){
  63803. int regTrigRowid;
  63804. int regCols;
  63805. int regRec;
  63806. /* build the NEW.* reference row. Note that if there is an INTEGER
  63807. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  63808. ** translated into a unique ID for the row. But on a BEFORE trigger,
  63809. ** we do not know what the unique ID will be (because the insert has
  63810. ** not happened yet) so we substitute a rowid of -1
  63811. */
  63812. regTrigRowid = sqlite3GetTempReg(pParse);
  63813. if( keyColumn<0 ){
  63814. sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
  63815. }else if( useTempTable ){
  63816. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
  63817. }else{
  63818. int j1;
  63819. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  63820. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
  63821. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
  63822. sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
  63823. sqlite3VdbeJumpHere(v, j1);
  63824. sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
  63825. }
  63826. /* Cannot have triggers on a virtual table. If it were possible,
  63827. ** this block would have to account for hidden column.
  63828. */
  63829. assert(!IsVirtual(pTab));
  63830. /* Create the new column data
  63831. */
  63832. regCols = sqlite3GetTempRange(pParse, pTab->nCol);
  63833. for(i=0; i<pTab->nCol; i++){
  63834. if( pColumn==0 ){
  63835. j = i;
  63836. }else{
  63837. for(j=0; j<pColumn->nId; j++){
  63838. if( pColumn->a[j].idx==i ) break;
  63839. }
  63840. }
  63841. if( pColumn && j>=pColumn->nId ){
  63842. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
  63843. }else if( useTempTable ){
  63844. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
  63845. }else{
  63846. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  63847. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
  63848. }
  63849. }
  63850. regRec = sqlite3GetTempReg(pParse);
  63851. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
  63852. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  63853. ** do not attempt any conversions before assembling the record.
  63854. ** If this is a real table, attempt conversions as required by the
  63855. ** table column affinities.
  63856. */
  63857. if( !isView ){
  63858. sqlite3TableAffinityStr(v, pTab);
  63859. }
  63860. sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regTrigRowid);
  63861. sqlite3ReleaseTempReg(pParse, regRec);
  63862. sqlite3ReleaseTempReg(pParse, regTrigRowid);
  63863. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
  63864. /* Fire BEFORE or INSTEAD OF triggers */
  63865. if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
  63866. newIdx, -1, onError, endOfLoop, 0, 0) ){
  63867. goto insert_cleanup;
  63868. }
  63869. }
  63870. /* Push the record number for the new entry onto the stack. The
  63871. ** record number is a randomly generate integer created by NewRowid
  63872. ** except when the table has an INTEGER PRIMARY KEY column, in which
  63873. ** case the record number is the same as that column.
  63874. */
  63875. if( !isView ){
  63876. if( IsVirtual(pTab) ){
  63877. /* The row that the VUpdate opcode will delete: none */
  63878. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  63879. }
  63880. if( keyColumn>=0 ){
  63881. if( useTempTable ){
  63882. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
  63883. }else if( pSelect ){
  63884. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
  63885. }else{
  63886. VdbeOp *pOp;
  63887. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
  63888. pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
  63889. if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  63890. appendFlag = 1;
  63891. pOp->opcode = OP_NewRowid;
  63892. pOp->p1 = baseCur;
  63893. pOp->p2 = regRowid;
  63894. pOp->p3 = regAutoinc;
  63895. }
  63896. }
  63897. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  63898. ** to generate a unique primary key value.
  63899. */
  63900. if( !appendFlag ){
  63901. int j1;
  63902. if( !IsVirtual(pTab) ){
  63903. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
  63904. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  63905. sqlite3VdbeJumpHere(v, j1);
  63906. }else{
  63907. j1 = sqlite3VdbeCurrentAddr(v);
  63908. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
  63909. }
  63910. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  63911. }
  63912. }else if( IsVirtual(pTab) ){
  63913. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  63914. }else{
  63915. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  63916. appendFlag = 1;
  63917. }
  63918. autoIncStep(pParse, regAutoinc, regRowid);
  63919. /* Push onto the stack, data for all columns of the new entry, beginning
  63920. ** with the first column.
  63921. */
  63922. nHidden = 0;
  63923. for(i=0; i<pTab->nCol; i++){
  63924. int iRegStore = regRowid+1+i;
  63925. if( i==pTab->iPKey ){
  63926. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  63927. ** Whenever this column is read, the record number will be substituted
  63928. ** in its place. So will fill this column with a NULL to avoid
  63929. ** taking up data space with information that will never be used. */
  63930. sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
  63931. continue;
  63932. }
  63933. if( pColumn==0 ){
  63934. if( IsHiddenColumn(&pTab->aCol[i]) ){
  63935. assert( IsVirtual(pTab) );
  63936. j = -1;
  63937. nHidden++;
  63938. }else{
  63939. j = i - nHidden;
  63940. }
  63941. }else{
  63942. for(j=0; j<pColumn->nId; j++){
  63943. if( pColumn->a[j].idx==i ) break;
  63944. }
  63945. }
  63946. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  63947. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
  63948. }else if( useTempTable ){
  63949. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  63950. }else if( pSelect ){
  63951. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  63952. }else{
  63953. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  63954. }
  63955. }
  63956. /* Generate code to check constraints and generate index keys and
  63957. ** do the insertion.
  63958. */
  63959. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63960. if( IsVirtual(pTab) ){
  63961. sqlite3VtabMakeWritable(pParse, pTab);
  63962. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
  63963. (const char*)pTab->pVtab, P4_VTAB);
  63964. }else
  63965. #endif
  63966. {
  63967. sqlite3GenerateConstraintChecks(
  63968. pParse,
  63969. pTab,
  63970. baseCur,
  63971. regIns,
  63972. aRegIdx,
  63973. keyColumn>=0,
  63974. 0,
  63975. onError,
  63976. endOfLoop
  63977. );
  63978. sqlite3CompleteInsertion(
  63979. pParse,
  63980. pTab,
  63981. baseCur,
  63982. regIns,
  63983. aRegIdx,
  63984. 0,
  63985. (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
  63986. appendFlag
  63987. );
  63988. }
  63989. }
  63990. /* Update the count of rows that are inserted
  63991. */
  63992. if( (db->flags & SQLITE_CountRows)!=0 ){
  63993. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  63994. }
  63995. if( triggers_exist ){
  63996. /* Code AFTER triggers */
  63997. if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
  63998. newIdx, -1, onError, endOfLoop, 0, 0) ){
  63999. goto insert_cleanup;
  64000. }
  64001. }
  64002. /* The bottom of the main insertion loop, if the data source
  64003. ** is a SELECT statement.
  64004. */
  64005. sqlite3VdbeResolveLabel(v, endOfLoop);
  64006. if( useTempTable ){
  64007. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
  64008. sqlite3VdbeJumpHere(v, addrInsTop);
  64009. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  64010. }else if( pSelect ){
  64011. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  64012. sqlite3VdbeJumpHere(v, addrInsTop);
  64013. }
  64014. if( !IsVirtual(pTab) && !isView ){
  64015. /* Close all tables opened */
  64016. sqlite3VdbeAddOp1(v, OP_Close, baseCur);
  64017. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  64018. sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
  64019. }
  64020. }
  64021. /* Update the sqlite_sequence table by storing the content of the
  64022. ** counter value in memory regAutoinc back into the sqlite_sequence
  64023. ** table.
  64024. */
  64025. autoIncEnd(pParse, iDb, pTab, regAutoinc);
  64026. /*
  64027. ** Return the number of rows inserted. If this routine is
  64028. ** generating code because of a call to sqlite3NestedParse(), do not
  64029. ** invoke the callback function.
  64030. */
  64031. if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
  64032. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  64033. sqlite3VdbeSetNumCols(v, 1);
  64034. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  64035. }
  64036. insert_cleanup:
  64037. sqlite3SrcListDelete(db, pTabList);
  64038. sqlite3ExprListDelete(db, pList);
  64039. sqlite3SelectDelete(db, pSelect);
  64040. sqlite3IdListDelete(db, pColumn);
  64041. sqlite3DbFree(db, aRegIdx);
  64042. }
  64043. /*
  64044. ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  64045. **
  64046. ** The input is a range of consecutive registers as follows:
  64047. **
  64048. ** 1. The rowid of the row to be updated before the update. This
  64049. ** value is omitted unless we are doing an UPDATE that involves a
  64050. ** change to the record number or writing to a virtual table.
  64051. **
  64052. ** 2. The rowid of the row after the update.
  64053. **
  64054. ** 3. The data in the first column of the entry after the update.
  64055. **
  64056. ** i. Data from middle columns...
  64057. **
  64058. ** N. The data in the last column of the entry after the update.
  64059. **
  64060. ** The regRowid parameter is the index of the register containing (2).
  64061. **
  64062. ** The old rowid shown as entry (1) above is omitted unless both isUpdate
  64063. ** and rowidChng are 1. isUpdate is true for UPDATEs and false for
  64064. ** INSERTs. RowidChng means that the new rowid is explicitly specified by
  64065. ** the update or insert statement. If rowidChng is false, it means that
  64066. ** the rowid is computed automatically in an insert or that the rowid value
  64067. ** is not modified by the update.
  64068. **
  64069. ** The code generated by this routine store new index entries into
  64070. ** registers identified by aRegIdx[]. No index entry is created for
  64071. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  64072. ** the same as the order of indices on the linked list of indices
  64073. ** attached to the table.
  64074. **
  64075. ** This routine also generates code to check constraints. NOT NULL,
  64076. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  64077. ** then the appropriate action is performed. There are five possible
  64078. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  64079. **
  64080. ** Constraint type Action What Happens
  64081. ** --------------- ---------- ----------------------------------------
  64082. ** any ROLLBACK The current transaction is rolled back and
  64083. ** sqlite3_exec() returns immediately with a
  64084. ** return code of SQLITE_CONSTRAINT.
  64085. **
  64086. ** any ABORT Back out changes from the current command
  64087. ** only (do not do a complete rollback) then
  64088. ** cause sqlite3_exec() to return immediately
  64089. ** with SQLITE_CONSTRAINT.
  64090. **
  64091. ** any FAIL Sqlite_exec() returns immediately with a
  64092. ** return code of SQLITE_CONSTRAINT. The
  64093. ** transaction is not rolled back and any
  64094. ** prior changes are retained.
  64095. **
  64096. ** any IGNORE The record number and data is popped from
  64097. ** the stack and there is an immediate jump
  64098. ** to label ignoreDest.
  64099. **
  64100. ** NOT NULL REPLACE The NULL value is replace by the default
  64101. ** value for that column. If the default value
  64102. ** is NULL, the action is the same as ABORT.
  64103. **
  64104. ** UNIQUE REPLACE The other row that conflicts with the row
  64105. ** being inserted is removed.
  64106. **
  64107. ** CHECK REPLACE Illegal. The results in an exception.
  64108. **
  64109. ** Which action to take is determined by the overrideError parameter.
  64110. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  64111. ** is used. Or if pParse->onError==OE_Default then the onError value
  64112. ** for the constraint is used.
  64113. **
  64114. ** The calling routine must open a read/write cursor for pTab with
  64115. ** cursor number "baseCur". All indices of pTab must also have open
  64116. ** read/write cursors with cursor number baseCur+i for the i-th cursor.
  64117. ** Except, if there is no possibility of a REPLACE action then
  64118. ** cursors do not need to be open for indices where aRegIdx[i]==0.
  64119. */
  64120. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  64121. Parse *pParse, /* The parser context */
  64122. Table *pTab, /* the table into which we are inserting */
  64123. int baseCur, /* Index of a read/write cursor pointing at pTab */
  64124. int regRowid, /* Index of the range of input registers */
  64125. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  64126. int rowidChng, /* True if the rowid might collide with existing entry */
  64127. int isUpdate, /* True for UPDATE, False for INSERT */
  64128. int overrideError, /* Override onError to this if not OE_Default */
  64129. int ignoreDest /* Jump to this label on an OE_Ignore resolution */
  64130. ){
  64131. int i;
  64132. Vdbe *v;
  64133. int nCol;
  64134. int onError;
  64135. int j1; /* Addresss of jump instruction */
  64136. int j2 = 0, j3; /* Addresses of jump instructions */
  64137. int regData; /* Register containing first data column */
  64138. int iCur;
  64139. Index *pIdx;
  64140. int seenReplace = 0;
  64141. int hasTwoRowids = (isUpdate && rowidChng);
  64142. v = sqlite3GetVdbe(pParse);
  64143. assert( v!=0 );
  64144. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  64145. nCol = pTab->nCol;
  64146. regData = regRowid + 1;
  64147. /* Test all NOT NULL constraints.
  64148. */
  64149. for(i=0; i<nCol; i++){
  64150. if( i==pTab->iPKey ){
  64151. continue;
  64152. }
  64153. onError = pTab->aCol[i].notNull;
  64154. if( onError==OE_None ) continue;
  64155. if( overrideError!=OE_Default ){
  64156. onError = overrideError;
  64157. }else if( onError==OE_Default ){
  64158. onError = OE_Abort;
  64159. }
  64160. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  64161. onError = OE_Abort;
  64162. }
  64163. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
  64164. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  64165. || onError==OE_Ignore || onError==OE_Replace );
  64166. switch( onError ){
  64167. case OE_Rollback:
  64168. case OE_Abort:
  64169. case OE_Fail: {
  64170. char *zMsg;
  64171. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
  64172. zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
  64173. pTab->zName, pTab->aCol[i].zName);
  64174. sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
  64175. break;
  64176. }
  64177. case OE_Ignore: {
  64178. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  64179. break;
  64180. }
  64181. case OE_Replace: {
  64182. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
  64183. break;
  64184. }
  64185. }
  64186. sqlite3VdbeJumpHere(v, j1);
  64187. }
  64188. /* Test all CHECK constraints
  64189. */
  64190. #ifndef SQLITE_OMIT_CHECK
  64191. if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
  64192. int allOk = sqlite3VdbeMakeLabel(v);
  64193. pParse->ckBase = regData;
  64194. sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
  64195. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  64196. if( onError==OE_Ignore ){
  64197. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  64198. }else{
  64199. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
  64200. }
  64201. sqlite3VdbeResolveLabel(v, allOk);
  64202. }
  64203. #endif /* !defined(SQLITE_OMIT_CHECK) */
  64204. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  64205. ** of the new record does not previously exist. Except, if this
  64206. ** is an UPDATE and the primary key is not changing, that is OK.
  64207. */
  64208. if( rowidChng ){
  64209. onError = pTab->keyConf;
  64210. if( overrideError!=OE_Default ){
  64211. onError = overrideError;
  64212. }else if( onError==OE_Default ){
  64213. onError = OE_Abort;
  64214. }
  64215. if( onError!=OE_Replace || pTab->pIndex ){
  64216. if( isUpdate ){
  64217. j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
  64218. }
  64219. j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  64220. switch( onError ){
  64221. default: {
  64222. onError = OE_Abort;
  64223. /* Fall thru into the next case */
  64224. }
  64225. case OE_Rollback:
  64226. case OE_Abort:
  64227. case OE_Fail: {
  64228. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
  64229. "PRIMARY KEY must be unique", P4_STATIC);
  64230. break;
  64231. }
  64232. case OE_Replace: {
  64233. sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
  64234. seenReplace = 1;
  64235. break;
  64236. }
  64237. case OE_Ignore: {
  64238. assert( seenReplace==0 );
  64239. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  64240. break;
  64241. }
  64242. }
  64243. sqlite3VdbeJumpHere(v, j3);
  64244. if( isUpdate ){
  64245. sqlite3VdbeJumpHere(v, j2);
  64246. }
  64247. }
  64248. }
  64249. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  64250. ** index and making sure that duplicate entries do not already exist.
  64251. ** Add the new records to the indices as we go.
  64252. */
  64253. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  64254. int regIdx;
  64255. int regR;
  64256. if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
  64257. /* Create a key for accessing the index entry */
  64258. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  64259. for(i=0; i<pIdx->nColumn; i++){
  64260. int idx = pIdx->aiColumn[i];
  64261. if( idx==pTab->iPKey ){
  64262. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  64263. }else{
  64264. sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
  64265. }
  64266. }
  64267. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  64268. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
  64269. sqlite3IndexAffinityStr(v, pIdx);
  64270. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  64271. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  64272. /* Find out what action to take in case there is an indexing conflict */
  64273. onError = pIdx->onError;
  64274. if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
  64275. if( overrideError!=OE_Default ){
  64276. onError = overrideError;
  64277. }else if( onError==OE_Default ){
  64278. onError = OE_Abort;
  64279. }
  64280. if( seenReplace ){
  64281. if( onError==OE_Ignore ) onError = OE_Replace;
  64282. else if( onError==OE_Fail ) onError = OE_Abort;
  64283. }
  64284. /* Check to see if the new index entry will be unique */
  64285. j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
  64286. regR = sqlite3GetTempReg(pParse);
  64287. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
  64288. j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  64289. regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
  64290. P4_INT32);
  64291. /* Generate code that executes if the new index entry is not unique */
  64292. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  64293. || onError==OE_Ignore || onError==OE_Replace );
  64294. switch( onError ){
  64295. case OE_Rollback:
  64296. case OE_Abort:
  64297. case OE_Fail: {
  64298. int j, n1, n2;
  64299. char zErrMsg[200];
  64300. sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
  64301. pIdx->nColumn>1 ? "columns " : "column ");
  64302. n1 = sqlite3Strlen30(zErrMsg);
  64303. for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
  64304. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  64305. n2 = sqlite3Strlen30(zCol);
  64306. if( j>0 ){
  64307. sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
  64308. n1 += 2;
  64309. }
  64310. if( n1+n2>ArraySize(zErrMsg)-30 ){
  64311. sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
  64312. n1 += 3;
  64313. break;
  64314. }else{
  64315. sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
  64316. n1 += n2;
  64317. }
  64318. }
  64319. sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1],
  64320. pIdx->nColumn>1 ? " are not unique" : " is not unique");
  64321. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
  64322. break;
  64323. }
  64324. case OE_Ignore: {
  64325. assert( seenReplace==0 );
  64326. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  64327. break;
  64328. }
  64329. case OE_Replace: {
  64330. sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
  64331. seenReplace = 1;
  64332. break;
  64333. }
  64334. }
  64335. sqlite3VdbeJumpHere(v, j2);
  64336. sqlite3VdbeJumpHere(v, j3);
  64337. sqlite3ReleaseTempReg(pParse, regR);
  64338. }
  64339. }
  64340. /*
  64341. ** This routine generates code to finish the INSERT or UPDATE operation
  64342. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  64343. ** A consecutive range of registers starting at regRowid contains the
  64344. ** rowid and the content to be inserted.
  64345. **
  64346. ** The arguments to this routine should be the same as the first six
  64347. ** arguments to sqlite3GenerateConstraintChecks.
  64348. */
  64349. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  64350. Parse *pParse, /* The parser context */
  64351. Table *pTab, /* the table into which we are inserting */
  64352. int baseCur, /* Index of a read/write cursor pointing at pTab */
  64353. int regRowid, /* Range of content */
  64354. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  64355. int isUpdate, /* True for UPDATE, False for INSERT */
  64356. int newIdx, /* Index of NEW table for triggers. -1 if none */
  64357. int appendBias /* True if this is likely to be an append */
  64358. ){
  64359. int i;
  64360. Vdbe *v;
  64361. int nIdx;
  64362. Index *pIdx;
  64363. u8 pik_flags;
  64364. int regData;
  64365. int regRec;
  64366. v = sqlite3GetVdbe(pParse);
  64367. assert( v!=0 );
  64368. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  64369. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  64370. for(i=nIdx-1; i>=0; i--){
  64371. if( aRegIdx[i]==0 ) continue;
  64372. sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  64373. }
  64374. regData = regRowid + 1;
  64375. regRec = sqlite3GetTempReg(pParse);
  64376. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  64377. sqlite3TableAffinityStr(v, pTab);
  64378. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  64379. #ifndef SQLITE_OMIT_TRIGGER
  64380. if( newIdx>=0 ){
  64381. sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
  64382. }
  64383. #endif
  64384. if( pParse->nested ){
  64385. pik_flags = 0;
  64386. }else{
  64387. pik_flags = OPFLAG_NCHANGE;
  64388. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  64389. }
  64390. if( appendBias ){
  64391. pik_flags |= OPFLAG_APPEND;
  64392. }
  64393. sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  64394. if( !pParse->nested ){
  64395. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
  64396. }
  64397. sqlite3VdbeChangeP5(v, pik_flags);
  64398. }
  64399. /*
  64400. ** Generate code that will open cursors for a table and for all
  64401. ** indices of that table. The "baseCur" parameter is the cursor number used
  64402. ** for the table. Indices are opened on subsequent cursors.
  64403. **
  64404. ** Return the number of indices on the table.
  64405. */
  64406. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  64407. Parse *pParse, /* Parsing context */
  64408. Table *pTab, /* Table to be opened */
  64409. int baseCur, /* Cursor number assigned to the table */
  64410. int op /* OP_OpenRead or OP_OpenWrite */
  64411. ){
  64412. int i;
  64413. int iDb;
  64414. Index *pIdx;
  64415. Vdbe *v;
  64416. if( IsVirtual(pTab) ) return 0;
  64417. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  64418. v = sqlite3GetVdbe(pParse);
  64419. assert( v!=0 );
  64420. sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  64421. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  64422. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  64423. assert( pIdx->pSchema==pTab->pSchema );
  64424. sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
  64425. (char*)pKey, P4_KEYINFO_HANDOFF);
  64426. VdbeComment((v, "%s", pIdx->zName));
  64427. }
  64428. if( pParse->nTab<=baseCur+i ){
  64429. pParse->nTab = baseCur+i;
  64430. }
  64431. return i-1;
  64432. }
  64433. #ifdef SQLITE_TEST
  64434. /*
  64435. ** The following global variable is incremented whenever the
  64436. ** transfer optimization is used. This is used for testing
  64437. ** purposes only - to make sure the transfer optimization really
  64438. ** is happening when it is suppose to.
  64439. */
  64440. SQLITE_API int sqlite3_xferopt_count;
  64441. #endif /* SQLITE_TEST */
  64442. #ifndef SQLITE_OMIT_XFER_OPT
  64443. /*
  64444. ** Check to collation names to see if they are compatible.
  64445. */
  64446. static int xferCompatibleCollation(const char *z1, const char *z2){
  64447. if( z1==0 ){
  64448. return z2==0;
  64449. }
  64450. if( z2==0 ){
  64451. return 0;
  64452. }
  64453. return sqlite3StrICmp(z1, z2)==0;
  64454. }
  64455. /*
  64456. ** Check to see if index pSrc is compatible as a source of data
  64457. ** for index pDest in an insert transfer optimization. The rules
  64458. ** for a compatible index:
  64459. **
  64460. ** * The index is over the same set of columns
  64461. ** * The same DESC and ASC markings occurs on all columns
  64462. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  64463. ** * The same collating sequence on each column
  64464. */
  64465. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  64466. int i;
  64467. assert( pDest && pSrc );
  64468. assert( pDest->pTable!=pSrc->pTable );
  64469. if( pDest->nColumn!=pSrc->nColumn ){
  64470. return 0; /* Different number of columns */
  64471. }
  64472. if( pDest->onError!=pSrc->onError ){
  64473. return 0; /* Different conflict resolution strategies */
  64474. }
  64475. for(i=0; i<pSrc->nColumn; i++){
  64476. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  64477. return 0; /* Different columns indexed */
  64478. }
  64479. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  64480. return 0; /* Different sort orders */
  64481. }
  64482. if( pSrc->azColl[i]!=pDest->azColl[i] ){
  64483. return 0; /* Different collating sequences */
  64484. }
  64485. }
  64486. /* If no test above fails then the indices must be compatible */
  64487. return 1;
  64488. }
  64489. /*
  64490. ** Attempt the transfer optimization on INSERTs of the form
  64491. **
  64492. ** INSERT INTO tab1 SELECT * FROM tab2;
  64493. **
  64494. ** This optimization is only attempted if
  64495. **
  64496. ** (1) tab1 and tab2 have identical schemas including all the
  64497. ** same indices and constraints
  64498. **
  64499. ** (2) tab1 and tab2 are different tables
  64500. **
  64501. ** (3) There must be no triggers on tab1
  64502. **
  64503. ** (4) The result set of the SELECT statement is "*"
  64504. **
  64505. ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
  64506. ** or LIMIT clause.
  64507. **
  64508. ** (6) The SELECT statement is a simple (not a compound) select that
  64509. ** contains only tab2 in its FROM clause
  64510. **
  64511. ** This method for implementing the INSERT transfers raw records from
  64512. ** tab2 over to tab1. The columns are not decoded. Raw records from
  64513. ** the indices of tab2 are transfered to tab1 as well. In so doing,
  64514. ** the resulting tab1 has much less fragmentation.
  64515. **
  64516. ** This routine returns TRUE if the optimization is attempted. If any
  64517. ** of the conditions above fail so that the optimization should not
  64518. ** be attempted, then this routine returns FALSE.
  64519. */
  64520. static int xferOptimization(
  64521. Parse *pParse, /* Parser context */
  64522. Table *pDest, /* The table we are inserting into */
  64523. Select *pSelect, /* A SELECT statement to use as the data source */
  64524. int onError, /* How to handle constraint errors */
  64525. int iDbDest /* The database of pDest */
  64526. ){
  64527. ExprList *pEList; /* The result set of the SELECT */
  64528. Table *pSrc; /* The table in the FROM clause of SELECT */
  64529. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  64530. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  64531. int i; /* Loop counter */
  64532. int iDbSrc; /* The database of pSrc */
  64533. int iSrc, iDest; /* Cursors from source and destination */
  64534. int addr1, addr2; /* Loop addresses */
  64535. int emptyDestTest; /* Address of test for empty pDest */
  64536. int emptySrcTest; /* Address of test for empty pSrc */
  64537. Vdbe *v; /* The VDBE we are building */
  64538. KeyInfo *pKey; /* Key information for an index */
  64539. int regAutoinc; /* Memory register used by AUTOINC */
  64540. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  64541. int regData, regRowid; /* Registers holding data and rowid */
  64542. if( pSelect==0 ){
  64543. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  64544. }
  64545. if( pDest->pTrigger ){
  64546. return 0; /* tab1 must not have triggers */
  64547. }
  64548. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64549. if( pDest->tabFlags & TF_Virtual ){
  64550. return 0; /* tab1 must not be a virtual table */
  64551. }
  64552. #endif
  64553. if( onError==OE_Default ){
  64554. onError = OE_Abort;
  64555. }
  64556. if( onError!=OE_Abort && onError!=OE_Rollback ){
  64557. return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
  64558. }
  64559. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  64560. if( pSelect->pSrc->nSrc!=1 ){
  64561. return 0; /* FROM clause must have exactly one term */
  64562. }
  64563. if( pSelect->pSrc->a[0].pSelect ){
  64564. return 0; /* FROM clause cannot contain a subquery */
  64565. }
  64566. if( pSelect->pWhere ){
  64567. return 0; /* SELECT may not have a WHERE clause */
  64568. }
  64569. if( pSelect->pOrderBy ){
  64570. return 0; /* SELECT may not have an ORDER BY clause */
  64571. }
  64572. /* Do not need to test for a HAVING clause. If HAVING is present but
  64573. ** there is no ORDER BY, we will get an error. */
  64574. if( pSelect->pGroupBy ){
  64575. return 0; /* SELECT may not have a GROUP BY clause */
  64576. }
  64577. if( pSelect->pLimit ){
  64578. return 0; /* SELECT may not have a LIMIT clause */
  64579. }
  64580. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  64581. if( pSelect->pPrior ){
  64582. return 0; /* SELECT may not be a compound query */
  64583. }
  64584. if( pSelect->selFlags & SF_Distinct ){
  64585. return 0; /* SELECT may not be DISTINCT */
  64586. }
  64587. pEList = pSelect->pEList;
  64588. assert( pEList!=0 );
  64589. if( pEList->nExpr!=1 ){
  64590. return 0; /* The result set must have exactly one column */
  64591. }
  64592. assert( pEList->a[0].pExpr );
  64593. if( pEList->a[0].pExpr->op!=TK_ALL ){
  64594. return 0; /* The result set must be the special operator "*" */
  64595. }
  64596. /* At this point we have established that the statement is of the
  64597. ** correct syntactic form to participate in this optimization. Now
  64598. ** we have to check the semantics.
  64599. */
  64600. pItem = pSelect->pSrc->a;
  64601. pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
  64602. if( pSrc==0 ){
  64603. return 0; /* FROM clause does not contain a real table */
  64604. }
  64605. if( pSrc==pDest ){
  64606. return 0; /* tab1 and tab2 may not be the same table */
  64607. }
  64608. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64609. if( pSrc->tabFlags & TF_Virtual ){
  64610. return 0; /* tab2 must not be a virtual table */
  64611. }
  64612. #endif
  64613. if( pSrc->pSelect ){
  64614. return 0; /* tab2 may not be a view */
  64615. }
  64616. if( pDest->nCol!=pSrc->nCol ){
  64617. return 0; /* Number of columns must be the same in tab1 and tab2 */
  64618. }
  64619. if( pDest->iPKey!=pSrc->iPKey ){
  64620. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  64621. }
  64622. for(i=0; i<pDest->nCol; i++){
  64623. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  64624. return 0; /* Affinity must be the same on all columns */
  64625. }
  64626. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  64627. return 0; /* Collating sequence must be the same on all columns */
  64628. }
  64629. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  64630. return 0; /* tab2 must be NOT NULL if tab1 is */
  64631. }
  64632. }
  64633. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  64634. if( pDestIdx->onError!=OE_None ){
  64635. destHasUniqueIdx = 1;
  64636. }
  64637. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  64638. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  64639. }
  64640. if( pSrcIdx==0 ){
  64641. return 0; /* pDestIdx has no corresponding index in pSrc */
  64642. }
  64643. }
  64644. #ifndef SQLITE_OMIT_CHECK
  64645. if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
  64646. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  64647. }
  64648. #endif
  64649. /* If we get this far, it means either:
  64650. **
  64651. ** * We can always do the transfer if the table contains an
  64652. ** an integer primary key
  64653. **
  64654. ** * We can conditionally do the transfer if the destination
  64655. ** table is empty.
  64656. */
  64657. #ifdef SQLITE_TEST
  64658. sqlite3_xferopt_count++;
  64659. #endif
  64660. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  64661. v = sqlite3GetVdbe(pParse);
  64662. sqlite3CodeVerifySchema(pParse, iDbSrc);
  64663. iSrc = pParse->nTab++;
  64664. iDest = pParse->nTab++;
  64665. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  64666. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  64667. if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
  64668. /* If tables do not have an INTEGER PRIMARY KEY and there
  64669. ** are indices to be copied and the destination is not empty,
  64670. ** we have to disallow the transfer optimization because the
  64671. ** the rowids might change which will mess up indexing.
  64672. **
  64673. ** Or if the destination has a UNIQUE index and is not empty,
  64674. ** we also disallow the transfer optimization because we cannot
  64675. ** insure that all entries in the union of DEST and SRC will be
  64676. ** unique.
  64677. */
  64678. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  64679. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  64680. sqlite3VdbeJumpHere(v, addr1);
  64681. }else{
  64682. emptyDestTest = 0;
  64683. }
  64684. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  64685. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  64686. regData = sqlite3GetTempReg(pParse);
  64687. regRowid = sqlite3GetTempReg(pParse);
  64688. if( pDest->iPKey>=0 ){
  64689. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  64690. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  64691. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
  64692. "PRIMARY KEY must be unique", P4_STATIC);
  64693. sqlite3VdbeJumpHere(v, addr2);
  64694. autoIncStep(pParse, regAutoinc, regRowid);
  64695. }else if( pDest->pIndex==0 ){
  64696. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  64697. }else{
  64698. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  64699. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  64700. }
  64701. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  64702. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  64703. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  64704. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  64705. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  64706. autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
  64707. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  64708. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  64709. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  64710. }
  64711. assert( pSrcIdx );
  64712. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  64713. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  64714. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  64715. sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
  64716. (char*)pKey, P4_KEYINFO_HANDOFF);
  64717. VdbeComment((v, "%s", pSrcIdx->zName));
  64718. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  64719. sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
  64720. (char*)pKey, P4_KEYINFO_HANDOFF);
  64721. VdbeComment((v, "%s", pDestIdx->zName));
  64722. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  64723. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  64724. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  64725. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
  64726. sqlite3VdbeJumpHere(v, addr1);
  64727. }
  64728. sqlite3VdbeJumpHere(v, emptySrcTest);
  64729. sqlite3ReleaseTempReg(pParse, regRowid);
  64730. sqlite3ReleaseTempReg(pParse, regData);
  64731. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  64732. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  64733. if( emptyDestTest ){
  64734. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  64735. sqlite3VdbeJumpHere(v, emptyDestTest);
  64736. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  64737. return 0;
  64738. }else{
  64739. return 1;
  64740. }
  64741. }
  64742. #endif /* SQLITE_OMIT_XFER_OPT */
  64743. /* Make sure "isView" gets undefined in case this file becomes part of
  64744. ** the amalgamation - so that subsequent files do not see isView as a
  64745. ** macro. */
  64746. #undef isView
  64747. /************** End of insert.c **********************************************/
  64748. /************** Begin file legacy.c ******************************************/
  64749. /*
  64750. ** 2001 September 15
  64751. **
  64752. ** The author disclaims copyright to this source code. In place of
  64753. ** a legal notice, here is a blessing:
  64754. **
  64755. ** May you do good and not evil.
  64756. ** May you find forgiveness for yourself and forgive others.
  64757. ** May you share freely, never taking more than you give.
  64758. **
  64759. *************************************************************************
  64760. ** Main file for the SQLite library. The routines in this file
  64761. ** implement the programmer interface to the library. Routines in
  64762. ** other files are for internal use by SQLite and should not be
  64763. ** accessed by users of the library.
  64764. **
  64765. ** $Id: legacy.c,v 1.30 2008/12/10 19:26:24 drh Exp $
  64766. */
  64767. /*
  64768. ** Execute SQL code. Return one of the SQLITE_ success/failure
  64769. ** codes. Also write an error message into memory obtained from
  64770. ** malloc() and make *pzErrMsg point to that message.
  64771. **
  64772. ** If the SQL is a query, then for each row in the query result
  64773. ** the xCallback() function is called. pArg becomes the first
  64774. ** argument to xCallback(). If xCallback=NULL then no callback
  64775. ** is invoked, even for queries.
  64776. */
  64777. SQLITE_API int sqlite3_exec(
  64778. sqlite3 *db, /* The database on which the SQL executes */
  64779. const char *zSql, /* The SQL to be executed */
  64780. sqlite3_callback xCallback, /* Invoke this callback routine */
  64781. void *pArg, /* First argument to xCallback() */
  64782. char **pzErrMsg /* Write error messages here */
  64783. ){
  64784. int rc = SQLITE_OK;
  64785. const char *zLeftover;
  64786. sqlite3_stmt *pStmt = 0;
  64787. char **azCols = 0;
  64788. int nRetry = 0;
  64789. int nCallback;
  64790. if( zSql==0 ) zSql = "";
  64791. sqlite3_mutex_enter(db->mutex);
  64792. sqlite3Error(db, SQLITE_OK, 0);
  64793. while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
  64794. int nCol;
  64795. char **azVals = 0;
  64796. pStmt = 0;
  64797. rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
  64798. assert( rc==SQLITE_OK || pStmt==0 );
  64799. if( rc!=SQLITE_OK ){
  64800. continue;
  64801. }
  64802. if( !pStmt ){
  64803. /* this happens for a comment or white-space */
  64804. zSql = zLeftover;
  64805. continue;
  64806. }
  64807. nCallback = 0;
  64808. nCol = sqlite3_column_count(pStmt);
  64809. while( 1 ){
  64810. int i;
  64811. rc = sqlite3_step(pStmt);
  64812. /* Invoke the callback function if required */
  64813. if( xCallback && (SQLITE_ROW==rc ||
  64814. (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
  64815. if( 0==nCallback ){
  64816. if( azCols==0 ){
  64817. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  64818. if( azCols==0 ){
  64819. goto exec_out;
  64820. }
  64821. }
  64822. for(i=0; i<nCol; i++){
  64823. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  64824. /* sqlite3VdbeSetColName() installs column names as UTF8
  64825. ** strings so there is no way for sqlite3_column_name() to fail. */
  64826. assert( azCols[i]!=0 );
  64827. }
  64828. nCallback++;
  64829. }
  64830. if( rc==SQLITE_ROW ){
  64831. azVals = &azCols[nCol];
  64832. for(i=0; i<nCol; i++){
  64833. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  64834. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  64835. db->mallocFailed = 1;
  64836. goto exec_out;
  64837. }
  64838. }
  64839. }
  64840. if( xCallback(pArg, nCol, azVals, azCols) ){
  64841. rc = SQLITE_ABORT;
  64842. sqlite3_finalize(pStmt);
  64843. pStmt = 0;
  64844. sqlite3Error(db, SQLITE_ABORT, 0);
  64845. goto exec_out;
  64846. }
  64847. }
  64848. if( rc!=SQLITE_ROW ){
  64849. rc = sqlite3_finalize(pStmt);
  64850. pStmt = 0;
  64851. if( rc!=SQLITE_SCHEMA ){
  64852. nRetry = 0;
  64853. zSql = zLeftover;
  64854. while( isspace((unsigned char)zSql[0]) ) zSql++;
  64855. }
  64856. break;
  64857. }
  64858. }
  64859. sqlite3DbFree(db, azCols);
  64860. azCols = 0;
  64861. }
  64862. exec_out:
  64863. if( pStmt ) sqlite3_finalize(pStmt);
  64864. sqlite3DbFree(db, azCols);
  64865. rc = sqlite3ApiExit(db, rc);
  64866. if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
  64867. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  64868. *pzErrMsg = sqlite3Malloc(nErrMsg);
  64869. if( *pzErrMsg ){
  64870. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  64871. }
  64872. }else if( pzErrMsg ){
  64873. *pzErrMsg = 0;
  64874. }
  64875. assert( (rc&db->errMask)==rc );
  64876. sqlite3_mutex_leave(db->mutex);
  64877. return rc;
  64878. }
  64879. /************** End of legacy.c **********************************************/
  64880. /************** Begin file loadext.c *****************************************/
  64881. /*
  64882. ** 2006 June 7
  64883. **
  64884. ** The author disclaims copyright to this source code. In place of
  64885. ** a legal notice, here is a blessing:
  64886. **
  64887. ** May you do good and not evil.
  64888. ** May you find forgiveness for yourself and forgive others.
  64889. ** May you share freely, never taking more than you give.
  64890. **
  64891. *************************************************************************
  64892. ** This file contains code used to dynamically load extensions into
  64893. ** the SQLite library.
  64894. **
  64895. ** $Id: loadext.c,v 1.57 2008/12/08 18:19:18 drh Exp $
  64896. */
  64897. #ifndef SQLITE_CORE
  64898. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  64899. #endif
  64900. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  64901. /************** Begin file sqlite3ext.h **************************************/
  64902. /*
  64903. ** 2006 June 7
  64904. **
  64905. ** The author disclaims copyright to this source code. In place of
  64906. ** a legal notice, here is a blessing:
  64907. **
  64908. ** May you do good and not evil.
  64909. ** May you find forgiveness for yourself and forgive others.
  64910. ** May you share freely, never taking more than you give.
  64911. **
  64912. *************************************************************************
  64913. ** This header file defines the SQLite interface for use by
  64914. ** shared libraries that want to be imported as extensions into
  64915. ** an SQLite instance. Shared libraries that intend to be loaded
  64916. ** as extensions by SQLite should #include this file instead of
  64917. ** sqlite3.h.
  64918. **
  64919. ** @(#) $Id: sqlite3ext.h,v 1.25 2008/10/12 00:27:54 shane Exp $
  64920. */
  64921. #ifndef _SQLITE3EXT_H_
  64922. #define _SQLITE3EXT_H_
  64923. typedef struct sqlite3_api_routines sqlite3_api_routines;
  64924. /*
  64925. ** The following structure holds pointers to all of the SQLite API
  64926. ** routines.
  64927. **
  64928. ** WARNING: In order to maintain backwards compatibility, add new
  64929. ** interfaces to the end of this structure only. If you insert new
  64930. ** interfaces in the middle of this structure, then older different
  64931. ** versions of SQLite will not be able to load each others' shared
  64932. ** libraries!
  64933. */
  64934. struct sqlite3_api_routines {
  64935. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  64936. int (*aggregate_count)(sqlite3_context*);
  64937. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  64938. int (*bind_double)(sqlite3_stmt*,int,double);
  64939. int (*bind_int)(sqlite3_stmt*,int,int);
  64940. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  64941. int (*bind_null)(sqlite3_stmt*,int);
  64942. int (*bind_parameter_count)(sqlite3_stmt*);
  64943. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  64944. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  64945. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  64946. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  64947. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  64948. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  64949. int (*busy_timeout)(sqlite3*,int ms);
  64950. int (*changes)(sqlite3*);
  64951. int (*close)(sqlite3*);
  64952. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
  64953. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
  64954. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  64955. int (*column_bytes)(sqlite3_stmt*,int iCol);
  64956. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  64957. int (*column_count)(sqlite3_stmt*pStmt);
  64958. const char * (*column_database_name)(sqlite3_stmt*,int);
  64959. const void * (*column_database_name16)(sqlite3_stmt*,int);
  64960. const char * (*column_decltype)(sqlite3_stmt*,int i);
  64961. const void * (*column_decltype16)(sqlite3_stmt*,int);
  64962. double (*column_double)(sqlite3_stmt*,int iCol);
  64963. int (*column_int)(sqlite3_stmt*,int iCol);
  64964. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  64965. const char * (*column_name)(sqlite3_stmt*,int);
  64966. const void * (*column_name16)(sqlite3_stmt*,int);
  64967. const char * (*column_origin_name)(sqlite3_stmt*,int);
  64968. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  64969. const char * (*column_table_name)(sqlite3_stmt*,int);
  64970. const void * (*column_table_name16)(sqlite3_stmt*,int);
  64971. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  64972. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  64973. int (*column_type)(sqlite3_stmt*,int iCol);
  64974. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  64975. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  64976. int (*complete)(const char*sql);
  64977. int (*complete16)(const void*sql);
  64978. int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
  64979. int (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
  64980. int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
  64981. int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
  64982. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  64983. int (*data_count)(sqlite3_stmt*pStmt);
  64984. sqlite3 * (*db_handle)(sqlite3_stmt*);
  64985. int (*declare_vtab)(sqlite3*,const char*);
  64986. int (*enable_shared_cache)(int);
  64987. int (*errcode)(sqlite3*db);
  64988. const char * (*errmsg)(sqlite3*);
  64989. const void * (*errmsg16)(sqlite3*);
  64990. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  64991. int (*expired)(sqlite3_stmt*);
  64992. int (*finalize)(sqlite3_stmt*pStmt);
  64993. void (*free)(void*);
  64994. void (*free_table)(char**result);
  64995. int (*get_autocommit)(sqlite3*);
  64996. void * (*get_auxdata)(sqlite3_context*,int);
  64997. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  64998. int (*global_recover)(void);
  64999. void (*interruptx)(sqlite3*);
  65000. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  65001. const char * (*libversion)(void);
  65002. int (*libversion_number)(void);
  65003. void *(*malloc)(int);
  65004. char * (*mprintf)(const char*,...);
  65005. int (*open)(const char*,sqlite3**);
  65006. int (*open16)(const void*,sqlite3**);
  65007. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  65008. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  65009. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  65010. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  65011. void *(*realloc)(void*,int);
  65012. int (*reset)(sqlite3_stmt*pStmt);
  65013. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  65014. void (*result_double)(sqlite3_context*,double);
  65015. void (*result_error)(sqlite3_context*,const char*,int);
  65016. void (*result_error16)(sqlite3_context*,const void*,int);
  65017. void (*result_int)(sqlite3_context*,int);
  65018. void (*result_int64)(sqlite3_context*,sqlite_int64);
  65019. void (*result_null)(sqlite3_context*);
  65020. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  65021. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  65022. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  65023. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  65024. void (*result_value)(sqlite3_context*,sqlite3_value*);
  65025. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  65026. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
  65027. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  65028. char * (*snprintf)(int,char*,const char*,...);
  65029. int (*step)(sqlite3_stmt*);
  65030. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
  65031. void (*thread_cleanup)(void);
  65032. int (*total_changes)(sqlite3*);
  65033. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  65034. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  65035. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
  65036. void * (*user_data)(sqlite3_context*);
  65037. const void * (*value_blob)(sqlite3_value*);
  65038. int (*value_bytes)(sqlite3_value*);
  65039. int (*value_bytes16)(sqlite3_value*);
  65040. double (*value_double)(sqlite3_value*);
  65041. int (*value_int)(sqlite3_value*);
  65042. sqlite_int64 (*value_int64)(sqlite3_value*);
  65043. int (*value_numeric_type)(sqlite3_value*);
  65044. const unsigned char * (*value_text)(sqlite3_value*);
  65045. const void * (*value_text16)(sqlite3_value*);
  65046. const void * (*value_text16be)(sqlite3_value*);
  65047. const void * (*value_text16le)(sqlite3_value*);
  65048. int (*value_type)(sqlite3_value*);
  65049. char *(*vmprintf)(const char*,va_list);
  65050. /* Added ??? */
  65051. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  65052. /* Added by 3.3.13 */
  65053. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  65054. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  65055. int (*clear_bindings)(sqlite3_stmt*);
  65056. /* Added by 3.4.1 */
  65057. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
  65058. /* Added by 3.5.0 */
  65059. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  65060. int (*blob_bytes)(sqlite3_blob*);
  65061. int (*blob_close)(sqlite3_blob*);
  65062. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
  65063. int (*blob_read)(sqlite3_blob*,void*,int,int);
  65064. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  65065. int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
  65066. int (*file_control)(sqlite3*,const char*,int,void*);
  65067. sqlite3_int64 (*memory_highwater)(int);
  65068. sqlite3_int64 (*memory_used)(void);
  65069. sqlite3_mutex *(*mutex_alloc)(int);
  65070. void (*mutex_enter)(sqlite3_mutex*);
  65071. void (*mutex_free)(sqlite3_mutex*);
  65072. void (*mutex_leave)(sqlite3_mutex*);
  65073. int (*mutex_try)(sqlite3_mutex*);
  65074. int (*open_v2)(const char*,sqlite3**,int,const char*);
  65075. int (*release_memory)(int);
  65076. void (*result_error_nomem)(sqlite3_context*);
  65077. void (*result_error_toobig)(sqlite3_context*);
  65078. int (*sleep)(int);
  65079. void (*soft_heap_limit)(int);
  65080. sqlite3_vfs *(*vfs_find)(const char*);
  65081. int (*vfs_register)(sqlite3_vfs*,int);
  65082. int (*vfs_unregister)(sqlite3_vfs*);
  65083. int (*xthreadsafe)(void);
  65084. void (*result_zeroblob)(sqlite3_context*,int);
  65085. void (*result_error_code)(sqlite3_context*,int);
  65086. int (*test_control)(int, ...);
  65087. void (*randomness)(int,void*);
  65088. sqlite3 *(*context_db_handle)(sqlite3_context*);
  65089. int (*extended_result_codes)(sqlite3*,int);
  65090. int (*limit)(sqlite3*,int,int);
  65091. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  65092. const char *(*sql)(sqlite3_stmt*);
  65093. int (*status)(int,int*,int*,int);
  65094. };
  65095. /*
  65096. ** The following macros redefine the API routines so that they are
  65097. ** redirected throught the global sqlite3_api structure.
  65098. **
  65099. ** This header file is also used by the loadext.c source file
  65100. ** (part of the main SQLite library - not an extension) so that
  65101. ** it can get access to the sqlite3_api_routines structure
  65102. ** definition. But the main library does not want to redefine
  65103. ** the API. So the redefinition macros are only valid if the
  65104. ** SQLITE_CORE macros is undefined.
  65105. */
  65106. #ifndef SQLITE_CORE
  65107. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  65108. #ifndef SQLITE_OMIT_DEPRECATED
  65109. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  65110. #endif
  65111. #define sqlite3_bind_blob sqlite3_api->bind_blob
  65112. #define sqlite3_bind_double sqlite3_api->bind_double
  65113. #define sqlite3_bind_int sqlite3_api->bind_int
  65114. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  65115. #define sqlite3_bind_null sqlite3_api->bind_null
  65116. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  65117. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  65118. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  65119. #define sqlite3_bind_text sqlite3_api->bind_text
  65120. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  65121. #define sqlite3_bind_value sqlite3_api->bind_value
  65122. #define sqlite3_busy_handler sqlite3_api->busy_handler
  65123. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  65124. #define sqlite3_changes sqlite3_api->changes
  65125. #define sqlite3_close sqlite3_api->close
  65126. #define sqlite3_collation_needed sqlite3_api->collation_needed
  65127. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  65128. #define sqlite3_column_blob sqlite3_api->column_blob
  65129. #define sqlite3_column_bytes sqlite3_api->column_bytes
  65130. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  65131. #define sqlite3_column_count sqlite3_api->column_count
  65132. #define sqlite3_column_database_name sqlite3_api->column_database_name
  65133. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  65134. #define sqlite3_column_decltype sqlite3_api->column_decltype
  65135. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  65136. #define sqlite3_column_double sqlite3_api->column_double
  65137. #define sqlite3_column_int sqlite3_api->column_int
  65138. #define sqlite3_column_int64 sqlite3_api->column_int64
  65139. #define sqlite3_column_name sqlite3_api->column_name
  65140. #define sqlite3_column_name16 sqlite3_api->column_name16
  65141. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  65142. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  65143. #define sqlite3_column_table_name sqlite3_api->column_table_name
  65144. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  65145. #define sqlite3_column_text sqlite3_api->column_text
  65146. #define sqlite3_column_text16 sqlite3_api->column_text16
  65147. #define sqlite3_column_type sqlite3_api->column_type
  65148. #define sqlite3_column_value sqlite3_api->column_value
  65149. #define sqlite3_commit_hook sqlite3_api->commit_hook
  65150. #define sqlite3_complete sqlite3_api->complete
  65151. #define sqlite3_complete16 sqlite3_api->complete16
  65152. #define sqlite3_create_collation sqlite3_api->create_collation
  65153. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  65154. #define sqlite3_create_function sqlite3_api->create_function
  65155. #define sqlite3_create_function16 sqlite3_api->create_function16
  65156. #define sqlite3_create_module sqlite3_api->create_module
  65157. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  65158. #define sqlite3_data_count sqlite3_api->data_count
  65159. #define sqlite3_db_handle sqlite3_api->db_handle
  65160. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  65161. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  65162. #define sqlite3_errcode sqlite3_api->errcode
  65163. #define sqlite3_errmsg sqlite3_api->errmsg
  65164. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  65165. #define sqlite3_exec sqlite3_api->exec
  65166. #ifndef SQLITE_OMIT_DEPRECATED
  65167. #define sqlite3_expired sqlite3_api->expired
  65168. #endif
  65169. #define sqlite3_finalize sqlite3_api->finalize
  65170. #define sqlite3_free sqlite3_api->free
  65171. #define sqlite3_free_table sqlite3_api->free_table
  65172. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  65173. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  65174. #define sqlite3_get_table sqlite3_api->get_table
  65175. #ifndef SQLITE_OMIT_DEPRECATED
  65176. #define sqlite3_global_recover sqlite3_api->global_recover
  65177. #endif
  65178. #define sqlite3_interrupt sqlite3_api->interruptx
  65179. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  65180. #define sqlite3_libversion sqlite3_api->libversion
  65181. #define sqlite3_libversion_number sqlite3_api->libversion_number
  65182. #define sqlite3_malloc sqlite3_api->malloc
  65183. #define sqlite3_mprintf sqlite3_api->mprintf
  65184. #define sqlite3_open sqlite3_api->open
  65185. #define sqlite3_open16 sqlite3_api->open16
  65186. #define sqlite3_prepare sqlite3_api->prepare
  65187. #define sqlite3_prepare16 sqlite3_api->prepare16
  65188. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  65189. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  65190. #define sqlite3_profile sqlite3_api->profile
  65191. #define sqlite3_progress_handler sqlite3_api->progress_handler
  65192. #define sqlite3_realloc sqlite3_api->realloc
  65193. #define sqlite3_reset sqlite3_api->reset
  65194. #define sqlite3_result_blob sqlite3_api->result_blob
  65195. #define sqlite3_result_double sqlite3_api->result_double
  65196. #define sqlite3_result_error sqlite3_api->result_error
  65197. #define sqlite3_result_error16 sqlite3_api->result_error16
  65198. #define sqlite3_result_int sqlite3_api->result_int
  65199. #define sqlite3_result_int64 sqlite3_api->result_int64
  65200. #define sqlite3_result_null sqlite3_api->result_null
  65201. #define sqlite3_result_text sqlite3_api->result_text
  65202. #define sqlite3_result_text16 sqlite3_api->result_text16
  65203. #define sqlite3_result_text16be sqlite3_api->result_text16be
  65204. #define sqlite3_result_text16le sqlite3_api->result_text16le
  65205. #define sqlite3_result_value sqlite3_api->result_value
  65206. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  65207. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  65208. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  65209. #define sqlite3_snprintf sqlite3_api->snprintf
  65210. #define sqlite3_step sqlite3_api->step
  65211. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  65212. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  65213. #define sqlite3_total_changes sqlite3_api->total_changes
  65214. #define sqlite3_trace sqlite3_api->trace
  65215. #ifndef SQLITE_OMIT_DEPRECATED
  65216. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  65217. #endif
  65218. #define sqlite3_update_hook sqlite3_api->update_hook
  65219. #define sqlite3_user_data sqlite3_api->user_data
  65220. #define sqlite3_value_blob sqlite3_api->value_blob
  65221. #define sqlite3_value_bytes sqlite3_api->value_bytes
  65222. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  65223. #define sqlite3_value_double sqlite3_api->value_double
  65224. #define sqlite3_value_int sqlite3_api->value_int
  65225. #define sqlite3_value_int64 sqlite3_api->value_int64
  65226. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  65227. #define sqlite3_value_text sqlite3_api->value_text
  65228. #define sqlite3_value_text16 sqlite3_api->value_text16
  65229. #define sqlite3_value_text16be sqlite3_api->value_text16be
  65230. #define sqlite3_value_text16le sqlite3_api->value_text16le
  65231. #define sqlite3_value_type sqlite3_api->value_type
  65232. #define sqlite3_vmprintf sqlite3_api->vmprintf
  65233. #define sqlite3_overload_function sqlite3_api->overload_function
  65234. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  65235. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  65236. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  65237. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  65238. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  65239. #define sqlite3_blob_close sqlite3_api->blob_close
  65240. #define sqlite3_blob_open sqlite3_api->blob_open
  65241. #define sqlite3_blob_read sqlite3_api->blob_read
  65242. #define sqlite3_blob_write sqlite3_api->blob_write
  65243. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  65244. #define sqlite3_file_control sqlite3_api->file_control
  65245. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  65246. #define sqlite3_memory_used sqlite3_api->memory_used
  65247. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  65248. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  65249. #define sqlite3_mutex_free sqlite3_api->mutex_free
  65250. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  65251. #define sqlite3_mutex_try sqlite3_api->mutex_try
  65252. #define sqlite3_open_v2 sqlite3_api->open_v2
  65253. #define sqlite3_release_memory sqlite3_api->release_memory
  65254. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  65255. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  65256. #define sqlite3_sleep sqlite3_api->sleep
  65257. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  65258. #define sqlite3_vfs_find sqlite3_api->vfs_find
  65259. #define sqlite3_vfs_register sqlite3_api->vfs_register
  65260. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  65261. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  65262. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  65263. #define sqlite3_result_error_code sqlite3_api->result_error_code
  65264. #define sqlite3_test_control sqlite3_api->test_control
  65265. #define sqlite3_randomness sqlite3_api->randomness
  65266. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  65267. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  65268. #define sqlite3_limit sqlite3_api->limit
  65269. #define sqlite3_next_stmt sqlite3_api->next_stmt
  65270. #define sqlite3_sql sqlite3_api->sql
  65271. #define sqlite3_status sqlite3_api->status
  65272. #endif /* SQLITE_CORE */
  65273. #define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0;
  65274. #define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v;
  65275. #endif /* _SQLITE3EXT_H_ */
  65276. /************** End of sqlite3ext.h ******************************************/
  65277. /************** Continuing where we left off in loadext.c ********************/
  65278. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  65279. /*
  65280. ** Some API routines are omitted when various features are
  65281. ** excluded from a build of SQLite. Substitute a NULL pointer
  65282. ** for any missing APIs.
  65283. */
  65284. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  65285. # define sqlite3_column_database_name 0
  65286. # define sqlite3_column_database_name16 0
  65287. # define sqlite3_column_table_name 0
  65288. # define sqlite3_column_table_name16 0
  65289. # define sqlite3_column_origin_name 0
  65290. # define sqlite3_column_origin_name16 0
  65291. # define sqlite3_table_column_metadata 0
  65292. #endif
  65293. #ifdef SQLITE_OMIT_AUTHORIZATION
  65294. # define sqlite3_set_authorizer 0
  65295. #endif
  65296. #ifdef SQLITE_OMIT_UTF16
  65297. # define sqlite3_bind_text16 0
  65298. # define sqlite3_collation_needed16 0
  65299. # define sqlite3_column_decltype16 0
  65300. # define sqlite3_column_name16 0
  65301. # define sqlite3_column_text16 0
  65302. # define sqlite3_complete16 0
  65303. # define sqlite3_create_collation16 0
  65304. # define sqlite3_create_function16 0
  65305. # define sqlite3_errmsg16 0
  65306. # define sqlite3_open16 0
  65307. # define sqlite3_prepare16 0
  65308. # define sqlite3_prepare16_v2 0
  65309. # define sqlite3_result_error16 0
  65310. # define sqlite3_result_text16 0
  65311. # define sqlite3_result_text16be 0
  65312. # define sqlite3_result_text16le 0
  65313. # define sqlite3_value_text16 0
  65314. # define sqlite3_value_text16be 0
  65315. # define sqlite3_value_text16le 0
  65316. # define sqlite3_column_database_name16 0
  65317. # define sqlite3_column_table_name16 0
  65318. # define sqlite3_column_origin_name16 0
  65319. #endif
  65320. #ifdef SQLITE_OMIT_COMPLETE
  65321. # define sqlite3_complete 0
  65322. # define sqlite3_complete16 0
  65323. #endif
  65324. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  65325. # define sqlite3_progress_handler 0
  65326. #endif
  65327. #ifdef SQLITE_OMIT_VIRTUALTABLE
  65328. # define sqlite3_create_module 0
  65329. # define sqlite3_create_module_v2 0
  65330. # define sqlite3_declare_vtab 0
  65331. #endif
  65332. #ifdef SQLITE_OMIT_SHARED_CACHE
  65333. # define sqlite3_enable_shared_cache 0
  65334. #endif
  65335. #ifdef SQLITE_OMIT_TRACE
  65336. # define sqlite3_profile 0
  65337. # define sqlite3_trace 0
  65338. #endif
  65339. #ifdef SQLITE_OMIT_GET_TABLE
  65340. # define sqlite3_free_table 0
  65341. # define sqlite3_get_table 0
  65342. #endif
  65343. #ifdef SQLITE_OMIT_INCRBLOB
  65344. #define sqlite3_bind_zeroblob 0
  65345. #define sqlite3_blob_bytes 0
  65346. #define sqlite3_blob_close 0
  65347. #define sqlite3_blob_open 0
  65348. #define sqlite3_blob_read 0
  65349. #define sqlite3_blob_write 0
  65350. #endif
  65351. /*
  65352. ** The following structure contains pointers to all SQLite API routines.
  65353. ** A pointer to this structure is passed into extensions when they are
  65354. ** loaded so that the extension can make calls back into the SQLite
  65355. ** library.
  65356. **
  65357. ** When adding new APIs, add them to the bottom of this structure
  65358. ** in order to preserve backwards compatibility.
  65359. **
  65360. ** Extensions that use newer APIs should first call the
  65361. ** sqlite3_libversion_number() to make sure that the API they
  65362. ** intend to use is supported by the library. Extensions should
  65363. ** also check to make sure that the pointer to the function is
  65364. ** not NULL before calling it.
  65365. */
  65366. static const sqlite3_api_routines sqlite3Apis = {
  65367. sqlite3_aggregate_context,
  65368. #ifndef SQLITE_OMIT_DEPRECATED
  65369. sqlite3_aggregate_count,
  65370. #else
  65371. 0,
  65372. #endif
  65373. sqlite3_bind_blob,
  65374. sqlite3_bind_double,
  65375. sqlite3_bind_int,
  65376. sqlite3_bind_int64,
  65377. sqlite3_bind_null,
  65378. sqlite3_bind_parameter_count,
  65379. sqlite3_bind_parameter_index,
  65380. sqlite3_bind_parameter_name,
  65381. sqlite3_bind_text,
  65382. sqlite3_bind_text16,
  65383. sqlite3_bind_value,
  65384. sqlite3_busy_handler,
  65385. sqlite3_busy_timeout,
  65386. sqlite3_changes,
  65387. sqlite3_close,
  65388. sqlite3_collation_needed,
  65389. sqlite3_collation_needed16,
  65390. sqlite3_column_blob,
  65391. sqlite3_column_bytes,
  65392. sqlite3_column_bytes16,
  65393. sqlite3_column_count,
  65394. sqlite3_column_database_name,
  65395. sqlite3_column_database_name16,
  65396. sqlite3_column_decltype,
  65397. sqlite3_column_decltype16,
  65398. sqlite3_column_double,
  65399. sqlite3_column_int,
  65400. sqlite3_column_int64,
  65401. sqlite3_column_name,
  65402. sqlite3_column_name16,
  65403. sqlite3_column_origin_name,
  65404. sqlite3_column_origin_name16,
  65405. sqlite3_column_table_name,
  65406. sqlite3_column_table_name16,
  65407. sqlite3_column_text,
  65408. sqlite3_column_text16,
  65409. sqlite3_column_type,
  65410. sqlite3_column_value,
  65411. sqlite3_commit_hook,
  65412. sqlite3_complete,
  65413. sqlite3_complete16,
  65414. sqlite3_create_collation,
  65415. sqlite3_create_collation16,
  65416. sqlite3_create_function,
  65417. sqlite3_create_function16,
  65418. sqlite3_create_module,
  65419. sqlite3_data_count,
  65420. sqlite3_db_handle,
  65421. sqlite3_declare_vtab,
  65422. sqlite3_enable_shared_cache,
  65423. sqlite3_errcode,
  65424. sqlite3_errmsg,
  65425. sqlite3_errmsg16,
  65426. sqlite3_exec,
  65427. #ifndef SQLITE_OMIT_DEPRECATED
  65428. sqlite3_expired,
  65429. #else
  65430. 0,
  65431. #endif
  65432. sqlite3_finalize,
  65433. sqlite3_free,
  65434. sqlite3_free_table,
  65435. sqlite3_get_autocommit,
  65436. sqlite3_get_auxdata,
  65437. sqlite3_get_table,
  65438. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  65439. sqlite3_interrupt,
  65440. sqlite3_last_insert_rowid,
  65441. sqlite3_libversion,
  65442. sqlite3_libversion_number,
  65443. sqlite3_malloc,
  65444. sqlite3_mprintf,
  65445. sqlite3_open,
  65446. sqlite3_open16,
  65447. sqlite3_prepare,
  65448. sqlite3_prepare16,
  65449. sqlite3_profile,
  65450. sqlite3_progress_handler,
  65451. sqlite3_realloc,
  65452. sqlite3_reset,
  65453. sqlite3_result_blob,
  65454. sqlite3_result_double,
  65455. sqlite3_result_error,
  65456. sqlite3_result_error16,
  65457. sqlite3_result_int,
  65458. sqlite3_result_int64,
  65459. sqlite3_result_null,
  65460. sqlite3_result_text,
  65461. sqlite3_result_text16,
  65462. sqlite3_result_text16be,
  65463. sqlite3_result_text16le,
  65464. sqlite3_result_value,
  65465. sqlite3_rollback_hook,
  65466. sqlite3_set_authorizer,
  65467. sqlite3_set_auxdata,
  65468. sqlite3_snprintf,
  65469. sqlite3_step,
  65470. sqlite3_table_column_metadata,
  65471. #ifndef SQLITE_OMIT_DEPRECATED
  65472. sqlite3_thread_cleanup,
  65473. #else
  65474. 0,
  65475. #endif
  65476. sqlite3_total_changes,
  65477. sqlite3_trace,
  65478. #ifndef SQLITE_OMIT_DEPRECATED
  65479. sqlite3_transfer_bindings,
  65480. #else
  65481. 0,
  65482. #endif
  65483. sqlite3_update_hook,
  65484. sqlite3_user_data,
  65485. sqlite3_value_blob,
  65486. sqlite3_value_bytes,
  65487. sqlite3_value_bytes16,
  65488. sqlite3_value_double,
  65489. sqlite3_value_int,
  65490. sqlite3_value_int64,
  65491. sqlite3_value_numeric_type,
  65492. sqlite3_value_text,
  65493. sqlite3_value_text16,
  65494. sqlite3_value_text16be,
  65495. sqlite3_value_text16le,
  65496. sqlite3_value_type,
  65497. sqlite3_vmprintf,
  65498. /*
  65499. ** The original API set ends here. All extensions can call any
  65500. ** of the APIs above provided that the pointer is not NULL. But
  65501. ** before calling APIs that follow, extension should check the
  65502. ** sqlite3_libversion_number() to make sure they are dealing with
  65503. ** a library that is new enough to support that API.
  65504. *************************************************************************
  65505. */
  65506. sqlite3_overload_function,
  65507. /*
  65508. ** Added after 3.3.13
  65509. */
  65510. sqlite3_prepare_v2,
  65511. sqlite3_prepare16_v2,
  65512. sqlite3_clear_bindings,
  65513. /*
  65514. ** Added for 3.4.1
  65515. */
  65516. sqlite3_create_module_v2,
  65517. /*
  65518. ** Added for 3.5.0
  65519. */
  65520. sqlite3_bind_zeroblob,
  65521. sqlite3_blob_bytes,
  65522. sqlite3_blob_close,
  65523. sqlite3_blob_open,
  65524. sqlite3_blob_read,
  65525. sqlite3_blob_write,
  65526. sqlite3_create_collation_v2,
  65527. sqlite3_file_control,
  65528. sqlite3_memory_highwater,
  65529. sqlite3_memory_used,
  65530. #ifdef SQLITE_MUTEX_OMIT
  65531. 0,
  65532. 0,
  65533. 0,
  65534. 0,
  65535. 0,
  65536. #else
  65537. sqlite3_mutex_alloc,
  65538. sqlite3_mutex_enter,
  65539. sqlite3_mutex_free,
  65540. sqlite3_mutex_leave,
  65541. sqlite3_mutex_try,
  65542. #endif
  65543. sqlite3_open_v2,
  65544. sqlite3_release_memory,
  65545. sqlite3_result_error_nomem,
  65546. sqlite3_result_error_toobig,
  65547. sqlite3_sleep,
  65548. sqlite3_soft_heap_limit,
  65549. sqlite3_vfs_find,
  65550. sqlite3_vfs_register,
  65551. sqlite3_vfs_unregister,
  65552. /*
  65553. ** Added for 3.5.8
  65554. */
  65555. sqlite3_threadsafe,
  65556. sqlite3_result_zeroblob,
  65557. sqlite3_result_error_code,
  65558. sqlite3_test_control,
  65559. sqlite3_randomness,
  65560. sqlite3_context_db_handle,
  65561. /*
  65562. ** Added for 3.6.0
  65563. */
  65564. sqlite3_extended_result_codes,
  65565. sqlite3_limit,
  65566. sqlite3_next_stmt,
  65567. sqlite3_sql,
  65568. sqlite3_status,
  65569. };
  65570. /*
  65571. ** Attempt to load an SQLite extension library contained in the file
  65572. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  65573. ** default entry point name (sqlite3_extension_init) is used. Use
  65574. ** of the default name is recommended.
  65575. **
  65576. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  65577. **
  65578. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  65579. ** error message text. The calling function should free this memory
  65580. ** by calling sqlite3DbFree(db, ).
  65581. */
  65582. static int sqlite3LoadExtension(
  65583. sqlite3 *db, /* Load the extension into this database connection */
  65584. const char *zFile, /* Name of the shared library containing extension */
  65585. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  65586. char **pzErrMsg /* Put error message here if not 0 */
  65587. ){
  65588. sqlite3_vfs *pVfs = db->pVfs;
  65589. void *handle;
  65590. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  65591. char *zErrmsg = 0;
  65592. void **aHandle;
  65593. /* Ticket #1863. To avoid a creating security problems for older
  65594. ** applications that relink against newer versions of SQLite, the
  65595. ** ability to run load_extension is turned off by default. One
  65596. ** must call sqlite3_enable_load_extension() to turn on extension
  65597. ** loading. Otherwise you get the following error.
  65598. */
  65599. if( (db->flags & SQLITE_LoadExtension)==0 ){
  65600. if( pzErrMsg ){
  65601. *pzErrMsg = sqlite3_mprintf("not authorized");
  65602. }
  65603. return SQLITE_ERROR;
  65604. }
  65605. if( zProc==0 ){
  65606. zProc = "sqlite3_extension_init";
  65607. }
  65608. handle = sqlite3OsDlOpen(pVfs, zFile);
  65609. if( handle==0 ){
  65610. if( pzErrMsg ){
  65611. char zErr[256];
  65612. zErr[sizeof(zErr)-1] = '\0';
  65613. sqlite3_snprintf(sizeof(zErr)-1, zErr,
  65614. "unable to open shared library [%s]", zFile);
  65615. sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
  65616. *pzErrMsg = sqlite3DbStrDup(0, zErr);
  65617. }
  65618. return SQLITE_ERROR;
  65619. }
  65620. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  65621. sqlite3OsDlSym(pVfs, handle, zProc);
  65622. if( xInit==0 ){
  65623. if( pzErrMsg ){
  65624. char zErr[256];
  65625. zErr[sizeof(zErr)-1] = '\0';
  65626. sqlite3_snprintf(sizeof(zErr)-1, zErr,
  65627. "no entry point [%s] in shared library [%s]", zProc,zFile);
  65628. sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
  65629. *pzErrMsg = sqlite3DbStrDup(0, zErr);
  65630. sqlite3OsDlClose(pVfs, handle);
  65631. }
  65632. return SQLITE_ERROR;
  65633. }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  65634. if( pzErrMsg ){
  65635. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  65636. }
  65637. sqlite3_free(zErrmsg);
  65638. sqlite3OsDlClose(pVfs, handle);
  65639. return SQLITE_ERROR;
  65640. }
  65641. /* Append the new shared library handle to the db->aExtension array. */
  65642. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  65643. if( aHandle==0 ){
  65644. return SQLITE_NOMEM;
  65645. }
  65646. if( db->nExtension>0 ){
  65647. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  65648. }
  65649. sqlite3DbFree(db, db->aExtension);
  65650. db->aExtension = aHandle;
  65651. db->aExtension[db->nExtension++] = handle;
  65652. return SQLITE_OK;
  65653. }
  65654. SQLITE_API int sqlite3_load_extension(
  65655. sqlite3 *db, /* Load the extension into this database connection */
  65656. const char *zFile, /* Name of the shared library containing extension */
  65657. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  65658. char **pzErrMsg /* Put error message here if not 0 */
  65659. ){
  65660. int rc;
  65661. sqlite3_mutex_enter(db->mutex);
  65662. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  65663. sqlite3_mutex_leave(db->mutex);
  65664. return rc;
  65665. }
  65666. /*
  65667. ** Call this routine when the database connection is closing in order
  65668. ** to clean up loaded extensions
  65669. */
  65670. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  65671. int i;
  65672. assert( sqlite3_mutex_held(db->mutex) );
  65673. for(i=0; i<db->nExtension; i++){
  65674. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  65675. }
  65676. sqlite3DbFree(db, db->aExtension);
  65677. }
  65678. /*
  65679. ** Enable or disable extension loading. Extension loading is disabled by
  65680. ** default so as not to open security holes in older applications.
  65681. */
  65682. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  65683. sqlite3_mutex_enter(db->mutex);
  65684. if( onoff ){
  65685. db->flags |= SQLITE_LoadExtension;
  65686. }else{
  65687. db->flags &= ~SQLITE_LoadExtension;
  65688. }
  65689. sqlite3_mutex_leave(db->mutex);
  65690. return SQLITE_OK;
  65691. }
  65692. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  65693. /*
  65694. ** The auto-extension code added regardless of whether or not extension
  65695. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  65696. ** code if regular extension loading is not available. This is that
  65697. ** dummy pointer.
  65698. */
  65699. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  65700. static const sqlite3_api_routines sqlite3Apis = { 0 };
  65701. #endif
  65702. /*
  65703. ** The following object holds the list of automatically loaded
  65704. ** extensions.
  65705. **
  65706. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  65707. ** mutex must be held while accessing this list.
  65708. */
  65709. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  65710. static SQLITE_WSD struct sqlite3AutoExtList {
  65711. int nExt; /* Number of entries in aExt[] */
  65712. void (**aExt)(void); /* Pointers to the extension init functions */
  65713. } sqlite3Autoext = { 0, 0 };
  65714. /* The "wsdAutoext" macro will resolve to the autoextension
  65715. ** state vector. If writable static data is unsupported on the target,
  65716. ** we have to locate the state vector at run-time. In the more common
  65717. ** case where writable static data is supported, wsdStat can refer directly
  65718. ** to the "sqlite3Autoext" state vector declared above.
  65719. */
  65720. #ifdef SQLITE_OMIT_WSD
  65721. # define wsdAutoextInit \
  65722. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  65723. # define wsdAutoext x[0]
  65724. #else
  65725. # define wsdAutoextInit
  65726. # define wsdAutoext sqlite3Autoext
  65727. #endif
  65728. /*
  65729. ** Register a statically linked extension that is automatically
  65730. ** loaded by every new database connection.
  65731. */
  65732. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  65733. int rc = SQLITE_OK;
  65734. #ifndef SQLITE_OMIT_AUTOINIT
  65735. rc = sqlite3_initialize();
  65736. if( rc ){
  65737. return rc;
  65738. }else
  65739. #endif
  65740. {
  65741. int i;
  65742. #if SQLITE_THREADSAFE
  65743. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  65744. #endif
  65745. wsdAutoextInit;
  65746. sqlite3_mutex_enter(mutex);
  65747. for(i=0; i<wsdAutoext.nExt; i++){
  65748. if( wsdAutoext.aExt[i]==xInit ) break;
  65749. }
  65750. if( i==wsdAutoext.nExt ){
  65751. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  65752. void (**aNew)(void);
  65753. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  65754. if( aNew==0 ){
  65755. rc = SQLITE_NOMEM;
  65756. }else{
  65757. wsdAutoext.aExt = aNew;
  65758. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  65759. wsdAutoext.nExt++;
  65760. }
  65761. }
  65762. sqlite3_mutex_leave(mutex);
  65763. assert( (rc&0xff)==rc );
  65764. return rc;
  65765. }
  65766. }
  65767. /*
  65768. ** Reset the automatic extension loading mechanism.
  65769. */
  65770. SQLITE_API void sqlite3_reset_auto_extension(void){
  65771. #ifndef SQLITE_OMIT_AUTOINIT
  65772. if( sqlite3_initialize()==SQLITE_OK )
  65773. #endif
  65774. {
  65775. #if SQLITE_THREADSAFE
  65776. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  65777. #endif
  65778. wsdAutoextInit;
  65779. sqlite3_mutex_enter(mutex);
  65780. sqlite3_free(wsdAutoext.aExt);
  65781. wsdAutoext.aExt = 0;
  65782. wsdAutoext.nExt = 0;
  65783. sqlite3_mutex_leave(mutex);
  65784. }
  65785. }
  65786. /*
  65787. ** Load all automatic extensions.
  65788. */
  65789. SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
  65790. int i;
  65791. int go = 1;
  65792. int rc = SQLITE_OK;
  65793. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  65794. wsdAutoextInit;
  65795. if( wsdAutoext.nExt==0 ){
  65796. /* Common case: early out without every having to acquire a mutex */
  65797. return SQLITE_OK;
  65798. }
  65799. for(i=0; go; i++){
  65800. char *zErrmsg = 0;
  65801. #if SQLITE_THREADSAFE
  65802. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  65803. #endif
  65804. sqlite3_mutex_enter(mutex);
  65805. if( i>=wsdAutoext.nExt ){
  65806. xInit = 0;
  65807. go = 0;
  65808. }else{
  65809. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  65810. wsdAutoext.aExt[i];
  65811. }
  65812. sqlite3_mutex_leave(mutex);
  65813. if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
  65814. sqlite3Error(db, SQLITE_ERROR,
  65815. "automatic extension loading failed: %s", zErrmsg);
  65816. go = 0;
  65817. rc = SQLITE_ERROR;
  65818. sqlite3_free(zErrmsg);
  65819. }
  65820. }
  65821. return rc;
  65822. }
  65823. /************** End of loadext.c *********************************************/
  65824. /************** Begin file pragma.c ******************************************/
  65825. /*
  65826. ** 2003 April 6
  65827. **
  65828. ** The author disclaims copyright to this source code. In place of
  65829. ** a legal notice, here is a blessing:
  65830. **
  65831. ** May you do good and not evil.
  65832. ** May you find forgiveness for yourself and forgive others.
  65833. ** May you share freely, never taking more than you give.
  65834. **
  65835. *************************************************************************
  65836. ** This file contains code used to implement the PRAGMA command.
  65837. **
  65838. ** $Id: pragma.c,v 1.201 2009/01/13 20:14:16 drh Exp $
  65839. */
  65840. /* Ignore this whole file if pragmas are disabled
  65841. */
  65842. #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
  65843. /*
  65844. ** Interpret the given string as a safety level. Return 0 for OFF,
  65845. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  65846. ** unrecognized string argument.
  65847. **
  65848. ** Note that the values returned are one less that the values that
  65849. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  65850. ** to support legacy SQL code. The safety level used to be boolean
  65851. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  65852. */
  65853. static u8 getSafetyLevel(const char *z){
  65854. /* 123456789 123456789 */
  65855. static const char zText[] = "onoffalseyestruefull";
  65856. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  65857. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  65858. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  65859. int i, n;
  65860. if( isdigit(*z) ){
  65861. return (u8)atoi(z);
  65862. }
  65863. n = sqlite3Strlen30(z);
  65864. for(i=0; i<ArraySize(iLength); i++){
  65865. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  65866. return iValue[i];
  65867. }
  65868. }
  65869. return 1;
  65870. }
  65871. /*
  65872. ** Interpret the given string as a boolean value.
  65873. */
  65874. static u8 getBoolean(const char *z){
  65875. return getSafetyLevel(z)&1;
  65876. }
  65877. /*
  65878. ** Interpret the given string as a locking mode value.
  65879. */
  65880. static int getLockingMode(const char *z){
  65881. if( z ){
  65882. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  65883. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  65884. }
  65885. return PAGER_LOCKINGMODE_QUERY;
  65886. }
  65887. #ifndef SQLITE_OMIT_AUTOVACUUM
  65888. /*
  65889. ** Interpret the given string as an auto-vacuum mode value.
  65890. **
  65891. ** The following strings, "none", "full" and "incremental" are
  65892. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  65893. */
  65894. static int getAutoVacuum(const char *z){
  65895. int i;
  65896. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  65897. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  65898. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  65899. i = atoi(z);
  65900. return (u8)((i>=0&&i<=2)?i:0);
  65901. }
  65902. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  65903. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  65904. /*
  65905. ** Interpret the given string as a temp db location. Return 1 for file
  65906. ** backed temporary databases, 2 for the Red-Black tree in memory database
  65907. ** and 0 to use the compile-time default.
  65908. */
  65909. static int getTempStore(const char *z){
  65910. if( z[0]>='0' && z[0]<='2' ){
  65911. return z[0] - '0';
  65912. }else if( sqlite3StrICmp(z, "file")==0 ){
  65913. return 1;
  65914. }else if( sqlite3StrICmp(z, "memory")==0 ){
  65915. return 2;
  65916. }else{
  65917. return 0;
  65918. }
  65919. }
  65920. #endif /* SQLITE_PAGER_PRAGMAS */
  65921. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  65922. /*
  65923. ** Invalidate temp storage, either when the temp storage is changed
  65924. ** from default, or when 'file' and the temp_store_directory has changed
  65925. */
  65926. static int invalidateTempStorage(Parse *pParse){
  65927. sqlite3 *db = pParse->db;
  65928. if( db->aDb[1].pBt!=0 ){
  65929. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  65930. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  65931. "from within a transaction");
  65932. return SQLITE_ERROR;
  65933. }
  65934. sqlite3BtreeClose(db->aDb[1].pBt);
  65935. db->aDb[1].pBt = 0;
  65936. sqlite3ResetInternalSchema(db, 0);
  65937. }
  65938. return SQLITE_OK;
  65939. }
  65940. #endif /* SQLITE_PAGER_PRAGMAS */
  65941. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  65942. /*
  65943. ** If the TEMP database is open, close it and mark the database schema
  65944. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  65945. ** or DEFAULT_TEMP_STORE pragmas.
  65946. */
  65947. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  65948. int ts = getTempStore(zStorageType);
  65949. sqlite3 *db = pParse->db;
  65950. if( db->temp_store==ts ) return SQLITE_OK;
  65951. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  65952. return SQLITE_ERROR;
  65953. }
  65954. db->temp_store = (u8)ts;
  65955. return SQLITE_OK;
  65956. }
  65957. #endif /* SQLITE_PAGER_PRAGMAS */
  65958. /*
  65959. ** Generate code to return a single integer value.
  65960. */
  65961. static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
  65962. Vdbe *v = sqlite3GetVdbe(pParse);
  65963. int mem = ++pParse->nMem;
  65964. sqlite3VdbeAddOp2(v, OP_Integer, value, mem);
  65965. if( pParse->explain==0 ){
  65966. sqlite3VdbeSetNumCols(v, 1);
  65967. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  65968. }
  65969. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  65970. }
  65971. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  65972. /*
  65973. ** Check to see if zRight and zLeft refer to a pragma that queries
  65974. ** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
  65975. ** Also, implement the pragma.
  65976. */
  65977. static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
  65978. static const struct sPragmaType {
  65979. const char *zName; /* Name of the pragma */
  65980. int mask; /* Mask for the db->flags value */
  65981. } aPragma[] = {
  65982. { "full_column_names", SQLITE_FullColNames },
  65983. { "short_column_names", SQLITE_ShortColNames },
  65984. { "count_changes", SQLITE_CountRows },
  65985. { "empty_result_callbacks", SQLITE_NullCallback },
  65986. { "legacy_file_format", SQLITE_LegacyFileFmt },
  65987. { "fullfsync", SQLITE_FullFSync },
  65988. #ifdef SQLITE_DEBUG
  65989. { "sql_trace", SQLITE_SqlTrace },
  65990. { "vdbe_listing", SQLITE_VdbeListing },
  65991. { "vdbe_trace", SQLITE_VdbeTrace },
  65992. #endif
  65993. #ifndef SQLITE_OMIT_CHECK
  65994. { "ignore_check_constraints", SQLITE_IgnoreChecks },
  65995. #endif
  65996. /* The following is VERY experimental */
  65997. { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
  65998. { "omit_readlock", SQLITE_NoReadlock },
  65999. /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
  66000. ** flag if there are any active statements. */
  66001. { "read_uncommitted", SQLITE_ReadUncommitted },
  66002. };
  66003. int i;
  66004. const struct sPragmaType *p;
  66005. for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
  66006. if( sqlite3StrICmp(zLeft, p->zName)==0 ){
  66007. sqlite3 *db = pParse->db;
  66008. Vdbe *v;
  66009. v = sqlite3GetVdbe(pParse);
  66010. assert( v!=0 ); /* Already allocated by sqlite3Pragma() */
  66011. if( ALWAYS(v) ){
  66012. if( zRight==0 ){
  66013. returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
  66014. }else{
  66015. if( getBoolean(zRight) ){
  66016. db->flags |= p->mask;
  66017. }else{
  66018. db->flags &= ~p->mask;
  66019. }
  66020. /* Many of the flag-pragmas modify the code generated by the SQL
  66021. ** compiler (eg. count_changes). So add an opcode to expire all
  66022. ** compiled SQL statements after modifying a pragma value.
  66023. */
  66024. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  66025. }
  66026. }
  66027. return 1;
  66028. }
  66029. }
  66030. return 0;
  66031. }
  66032. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  66033. /*
  66034. ** Return a human-readable name for a constraint resolution action.
  66035. */
  66036. static const char *actionName(u8 action){
  66037. const char *zName;
  66038. switch( action ){
  66039. case OE_SetNull: zName = "SET NULL"; break;
  66040. case OE_SetDflt: zName = "SET DEFAULT"; break;
  66041. case OE_Cascade: zName = "CASCADE"; break;
  66042. default: zName = "RESTRICT";
  66043. assert( action==OE_Restrict ); break;
  66044. }
  66045. return zName;
  66046. }
  66047. /*
  66048. ** Process a pragma statement.
  66049. **
  66050. ** Pragmas are of this form:
  66051. **
  66052. ** PRAGMA [database.]id [= value]
  66053. **
  66054. ** The identifier might also be a string. The value is a string, and
  66055. ** identifier, or a number. If minusFlag is true, then the value is
  66056. ** a number that was preceded by a minus sign.
  66057. **
  66058. ** If the left side is "database.id" then pId1 is the database name
  66059. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  66060. ** id and pId2 is any empty string.
  66061. */
  66062. SQLITE_PRIVATE void sqlite3Pragma(
  66063. Parse *pParse,
  66064. Token *pId1, /* First part of [database.]id field */
  66065. Token *pId2, /* Second part of [database.]id field, or NULL */
  66066. Token *pValue, /* Token for <value>, or NULL */
  66067. int minusFlag /* True if a '-' sign preceded <value> */
  66068. ){
  66069. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  66070. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  66071. const char *zDb = 0; /* The database name */
  66072. Token *pId; /* Pointer to <id> token */
  66073. int iDb; /* Database index for <database> */
  66074. sqlite3 *db = pParse->db;
  66075. Db *pDb;
  66076. Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
  66077. if( v==0 ) return;
  66078. pParse->nMem = 2;
  66079. /* Interpret the [database.] part of the pragma statement. iDb is the
  66080. ** index of the database this pragma is being applied to in db.aDb[]. */
  66081. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  66082. if( iDb<0 ) return;
  66083. pDb = &db->aDb[iDb];
  66084. /* If the temp database has been explicitly named as part of the
  66085. ** pragma, make sure it is open.
  66086. */
  66087. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  66088. return;
  66089. }
  66090. zLeft = sqlite3NameFromToken(db, pId);
  66091. if( !zLeft ) return;
  66092. if( minusFlag ){
  66093. zRight = sqlite3MPrintf(db, "-%T", pValue);
  66094. }else{
  66095. zRight = sqlite3NameFromToken(db, pValue);
  66096. }
  66097. assert( pId2 );
  66098. zDb = pId2->n>0 ? pDb->zName : 0;
  66099. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  66100. goto pragma_out;
  66101. }
  66102. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  66103. /*
  66104. ** PRAGMA [database.]default_cache_size
  66105. ** PRAGMA [database.]default_cache_size=N
  66106. **
  66107. ** The first form reports the current persistent setting for the
  66108. ** page cache size. The value returned is the maximum number of
  66109. ** pages in the page cache. The second form sets both the current
  66110. ** page cache size value and the persistent page cache size value
  66111. ** stored in the database file.
  66112. **
  66113. ** The default cache size is stored in meta-value 2 of page 1 of the
  66114. ** database file. The cache size is actually the absolute value of
  66115. ** this memory location. The sign of meta-value 2 determines the
  66116. ** synchronous setting. A negative value means synchronous is off
  66117. ** and a positive value means synchronous is on.
  66118. */
  66119. if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
  66120. static const VdbeOpList getCacheSize[] = {
  66121. { OP_ReadCookie, 0, 1, 2}, /* 0 */
  66122. { OP_IfPos, 1, 6, 0},
  66123. { OP_Integer, 0, 2, 0},
  66124. { OP_Subtract, 1, 2, 1},
  66125. { OP_IfPos, 1, 6, 0},
  66126. { OP_Integer, 0, 1, 0}, /* 5 */
  66127. { OP_ResultRow, 1, 1, 0},
  66128. };
  66129. int addr;
  66130. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66131. sqlite3VdbeUsesBtree(v, iDb);
  66132. if( !zRight ){
  66133. sqlite3VdbeSetNumCols(v, 1);
  66134. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  66135. pParse->nMem += 2;
  66136. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  66137. sqlite3VdbeChangeP1(v, addr, iDb);
  66138. sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
  66139. }else{
  66140. int size = atoi(zRight);
  66141. if( size<0 ) size = -size;
  66142. sqlite3BeginWriteOperation(pParse, 0, iDb);
  66143. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  66144. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, 2);
  66145. addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
  66146. sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
  66147. sqlite3VdbeJumpHere(v, addr);
  66148. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 2, 1);
  66149. pDb->pSchema->cache_size = size;
  66150. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  66151. }
  66152. }else
  66153. /*
  66154. ** PRAGMA [database.]page_size
  66155. ** PRAGMA [database.]page_size=N
  66156. **
  66157. ** The first form reports the current setting for the
  66158. ** database page size in bytes. The second form sets the
  66159. ** database page size value. The value can only be set if
  66160. ** the database has not yet been created.
  66161. */
  66162. if( sqlite3StrICmp(zLeft,"page_size")==0 ){
  66163. Btree *pBt = pDb->pBt;
  66164. assert( pBt!=0 );
  66165. if( !zRight ){
  66166. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  66167. returnSingleInt(pParse, "page_size", size);
  66168. }else{
  66169. /* Malloc may fail when setting the page-size, as there is an internal
  66170. ** buffer that the pager module resizes using sqlite3_realloc().
  66171. */
  66172. db->nextPagesize = atoi(zRight);
  66173. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1) ){
  66174. db->mallocFailed = 1;
  66175. }
  66176. }
  66177. }else
  66178. /*
  66179. ** PRAGMA [database.]max_page_count
  66180. ** PRAGMA [database.]max_page_count=N
  66181. **
  66182. ** The first form reports the current setting for the
  66183. ** maximum number of pages in the database file. The
  66184. ** second form attempts to change this setting. Both
  66185. ** forms return the current setting.
  66186. */
  66187. if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
  66188. Btree *pBt = pDb->pBt;
  66189. int newMax = 0;
  66190. assert( pBt!=0 );
  66191. if( zRight ){
  66192. newMax = atoi(zRight);
  66193. }
  66194. if( ALWAYS(pBt) ){
  66195. newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
  66196. }
  66197. returnSingleInt(pParse, "max_page_count", newMax);
  66198. }else
  66199. /*
  66200. ** PRAGMA [database.]page_count
  66201. **
  66202. ** Return the number of pages in the specified database.
  66203. */
  66204. if( sqlite3StrICmp(zLeft,"page_count")==0 ){
  66205. int iReg;
  66206. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66207. sqlite3CodeVerifySchema(pParse, iDb);
  66208. iReg = ++pParse->nMem;
  66209. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  66210. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  66211. sqlite3VdbeSetNumCols(v, 1);
  66212. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
  66213. }else
  66214. /*
  66215. ** PRAGMA [database.]locking_mode
  66216. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  66217. */
  66218. if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
  66219. const char *zRet = "normal";
  66220. int eMode = getLockingMode(zRight);
  66221. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  66222. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  66223. ** the current default locking mode (which may be different to
  66224. ** the locking-mode of the main database).
  66225. */
  66226. eMode = db->dfltLockMode;
  66227. }else{
  66228. Pager *pPager;
  66229. if( pId2->n==0 ){
  66230. /* This indicates that no database name was specified as part
  66231. ** of the PRAGMA command. In this case the locking-mode must be
  66232. ** set on all attached databases, as well as the main db file.
  66233. **
  66234. ** Also, the sqlite3.dfltLockMode variable is set so that
  66235. ** any subsequently attached databases also use the specified
  66236. ** locking mode.
  66237. */
  66238. int ii;
  66239. assert(pDb==&db->aDb[0]);
  66240. for(ii=2; ii<db->nDb; ii++){
  66241. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  66242. sqlite3PagerLockingMode(pPager, eMode);
  66243. }
  66244. db->dfltLockMode = (u8)eMode;
  66245. }
  66246. pPager = sqlite3BtreePager(pDb->pBt);
  66247. eMode = sqlite3PagerLockingMode(pPager, eMode);
  66248. }
  66249. assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
  66250. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  66251. zRet = "exclusive";
  66252. }
  66253. sqlite3VdbeSetNumCols(v, 1);
  66254. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  66255. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  66256. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  66257. }else
  66258. /*
  66259. ** PRAGMA [database.]journal_mode
  66260. ** PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
  66261. */
  66262. if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
  66263. int eMode;
  66264. static char * const azModeName[] = {
  66265. "delete", "persist", "off", "truncate", "memory"
  66266. };
  66267. if( zRight==0 ){
  66268. eMode = PAGER_JOURNALMODE_QUERY;
  66269. }else{
  66270. int n = sqlite3Strlen30(zRight);
  66271. eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
  66272. while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
  66273. eMode--;
  66274. }
  66275. }
  66276. if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
  66277. /* Simple "PRAGMA journal_mode;" statement. This is a query for
  66278. ** the current default journal mode (which may be different to
  66279. ** the journal-mode of the main database).
  66280. */
  66281. eMode = db->dfltJournalMode;
  66282. }else{
  66283. Pager *pPager;
  66284. if( pId2->n==0 ){
  66285. /* This indicates that no database name was specified as part
  66286. ** of the PRAGMA command. In this case the journal-mode must be
  66287. ** set on all attached databases, as well as the main db file.
  66288. **
  66289. ** Also, the sqlite3.dfltJournalMode variable is set so that
  66290. ** any subsequently attached databases also use the specified
  66291. ** journal mode.
  66292. */
  66293. int ii;
  66294. assert(pDb==&db->aDb[0]);
  66295. for(ii=1; ii<db->nDb; ii++){
  66296. if( db->aDb[ii].pBt ){
  66297. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  66298. sqlite3PagerJournalMode(pPager, eMode);
  66299. }
  66300. }
  66301. db->dfltJournalMode = (u8)eMode;
  66302. }
  66303. pPager = sqlite3BtreePager(pDb->pBt);
  66304. eMode = sqlite3PagerJournalMode(pPager, eMode);
  66305. }
  66306. assert( eMode==PAGER_JOURNALMODE_DELETE
  66307. || eMode==PAGER_JOURNALMODE_TRUNCATE
  66308. || eMode==PAGER_JOURNALMODE_PERSIST
  66309. || eMode==PAGER_JOURNALMODE_OFF
  66310. || eMode==PAGER_JOURNALMODE_MEMORY );
  66311. sqlite3VdbeSetNumCols(v, 1);
  66312. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  66313. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0,
  66314. azModeName[eMode], P4_STATIC);
  66315. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  66316. }else
  66317. /*
  66318. ** PRAGMA [database.]journal_size_limit
  66319. ** PRAGMA [database.]journal_size_limit=N
  66320. **
  66321. ** Get or set the size limit on rollback journal files.
  66322. */
  66323. if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
  66324. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  66325. i64 iLimit = -2;
  66326. if( zRight ){
  66327. int iLimit32 = atoi(zRight);
  66328. if( iLimit32<-1 ){
  66329. iLimit32 = -1;
  66330. }
  66331. iLimit = iLimit32;
  66332. }
  66333. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  66334. returnSingleInt(pParse, "journal_size_limit", (int)iLimit);
  66335. }else
  66336. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  66337. /*
  66338. ** PRAGMA [database.]auto_vacuum
  66339. ** PRAGMA [database.]auto_vacuum=N
  66340. **
  66341. ** Get or set the value of the database 'auto-vacuum' parameter.
  66342. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  66343. */
  66344. #ifndef SQLITE_OMIT_AUTOVACUUM
  66345. if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
  66346. Btree *pBt = pDb->pBt;
  66347. assert( pBt!=0 );
  66348. if( sqlite3ReadSchema(pParse) ){
  66349. goto pragma_out;
  66350. }
  66351. if( !zRight ){
  66352. int auto_vacuum;
  66353. if( ALWAYS(pBt) ){
  66354. auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
  66355. }else{
  66356. auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
  66357. }
  66358. returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
  66359. }else{
  66360. int eAuto = getAutoVacuum(zRight);
  66361. assert( eAuto>=0 && eAuto<=2 );
  66362. db->nextAutovac = (u8)eAuto;
  66363. if( ALWAYS(eAuto>=0) ){
  66364. /* Call SetAutoVacuum() to set initialize the internal auto and
  66365. ** incr-vacuum flags. This is required in case this connection
  66366. ** creates the database file. It is important that it is created
  66367. ** as an auto-vacuum capable db.
  66368. */
  66369. int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  66370. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  66371. /* When setting the auto_vacuum mode to either "full" or
  66372. ** "incremental", write the value of meta[6] in the database
  66373. ** file. Before writing to meta[6], check that meta[3] indicates
  66374. ** that this really is an auto-vacuum capable database.
  66375. */
  66376. static const VdbeOpList setMeta6[] = {
  66377. { OP_Transaction, 0, 1, 0}, /* 0 */
  66378. { OP_ReadCookie, 0, 1, 3}, /* 1 */
  66379. { OP_If, 1, 0, 0}, /* 2 */
  66380. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  66381. { OP_Integer, 0, 1, 0}, /* 4 */
  66382. { OP_SetCookie, 0, 6, 1}, /* 5 */
  66383. };
  66384. int iAddr;
  66385. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
  66386. sqlite3VdbeChangeP1(v, iAddr, iDb);
  66387. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  66388. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  66389. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  66390. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  66391. sqlite3VdbeUsesBtree(v, iDb);
  66392. }
  66393. }
  66394. }
  66395. }else
  66396. #endif
  66397. /*
  66398. ** PRAGMA [database.]incremental_vacuum(N)
  66399. **
  66400. ** Do N steps of incremental vacuuming on a database.
  66401. */
  66402. #ifndef SQLITE_OMIT_AUTOVACUUM
  66403. if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
  66404. int iLimit, addr;
  66405. if( sqlite3ReadSchema(pParse) ){
  66406. goto pragma_out;
  66407. }
  66408. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  66409. iLimit = 0x7fffffff;
  66410. }
  66411. sqlite3BeginWriteOperation(pParse, 0, iDb);
  66412. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  66413. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
  66414. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  66415. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  66416. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
  66417. sqlite3VdbeJumpHere(v, addr);
  66418. }else
  66419. #endif
  66420. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  66421. /*
  66422. ** PRAGMA [database.]cache_size
  66423. ** PRAGMA [database.]cache_size=N
  66424. **
  66425. ** The first form reports the current local setting for the
  66426. ** page cache size. The local setting can be different from
  66427. ** the persistent cache size value that is stored in the database
  66428. ** file itself. The value returned is the maximum number of
  66429. ** pages in the page cache. The second form sets the local
  66430. ** page cache size value. It does not change the persistent
  66431. ** cache size stored on the disk so the cache size will revert
  66432. ** to its default value when the database is closed and reopened.
  66433. ** N should be a positive integer.
  66434. */
  66435. if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
  66436. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66437. if( !zRight ){
  66438. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  66439. }else{
  66440. int size = atoi(zRight);
  66441. if( size<0 ) size = -size;
  66442. pDb->pSchema->cache_size = size;
  66443. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  66444. }
  66445. }else
  66446. /*
  66447. ** PRAGMA temp_store
  66448. ** PRAGMA temp_store = "default"|"memory"|"file"
  66449. **
  66450. ** Return or set the local value of the temp_store flag. Changing
  66451. ** the local value does not make changes to the disk file and the default
  66452. ** value will be restored the next time the database is opened.
  66453. **
  66454. ** Note that it is possible for the library compile-time options to
  66455. ** override this setting
  66456. */
  66457. if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
  66458. if( !zRight ){
  66459. returnSingleInt(pParse, "temp_store", db->temp_store);
  66460. }else{
  66461. changeTempStorage(pParse, zRight);
  66462. }
  66463. }else
  66464. /*
  66465. ** PRAGMA temp_store_directory
  66466. ** PRAGMA temp_store_directory = ""|"directory_name"
  66467. **
  66468. ** Return or set the local value of the temp_store_directory flag. Changing
  66469. ** the value sets a specific directory to be used for temporary files.
  66470. ** Setting to a null string reverts to the default temporary directory search.
  66471. ** If temporary directory is changed, then invalidateTempStorage.
  66472. **
  66473. */
  66474. if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
  66475. if( !zRight ){
  66476. if( sqlite3_temp_directory ){
  66477. sqlite3VdbeSetNumCols(v, 1);
  66478. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  66479. "temp_store_directory", SQLITE_STATIC);
  66480. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  66481. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  66482. }
  66483. }else{
  66484. #ifndef SQLITE_OMIT_WSD
  66485. if( zRight[0] ){
  66486. int rc;
  66487. int res;
  66488. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  66489. if( rc!=SQLITE_OK || res==0 ){
  66490. sqlite3ErrorMsg(pParse, "not a writable directory");
  66491. goto pragma_out;
  66492. }
  66493. }
  66494. if( SQLITE_TEMP_STORE==0
  66495. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  66496. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  66497. ){
  66498. invalidateTempStorage(pParse);
  66499. }
  66500. sqlite3_free(sqlite3_temp_directory);
  66501. if( zRight[0] ){
  66502. sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
  66503. }else{
  66504. sqlite3_temp_directory = 0;
  66505. }
  66506. #endif /* SQLITE_OMIT_WSD */
  66507. }
  66508. }else
  66509. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  66510. # if defined(__APPLE__)
  66511. # define SQLITE_ENABLE_LOCKING_STYLE 1
  66512. # else
  66513. # define SQLITE_ENABLE_LOCKING_STYLE 0
  66514. # endif
  66515. #endif
  66516. #if SQLITE_ENABLE_LOCKING_STYLE
  66517. /*
  66518. ** PRAGMA [database.]lock_proxy_file
  66519. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  66520. **
  66521. ** Return or set the value of the lock_proxy_file flag. Changing
  66522. ** the value sets a specific file to be used for database access locks.
  66523. **
  66524. */
  66525. if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
  66526. if( !zRight ){
  66527. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  66528. char *proxy_file_path = NULL;
  66529. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  66530. sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
  66531. &proxy_file_path);
  66532. if( proxy_file_path ){
  66533. sqlite3VdbeSetNumCols(v, 1);
  66534. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  66535. "lock_proxy_file", SQLITE_STATIC);
  66536. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  66537. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  66538. }
  66539. }else{
  66540. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  66541. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  66542. int res;
  66543. if( zRight[0] ){
  66544. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  66545. zRight);
  66546. } else {
  66547. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  66548. NULL);
  66549. }
  66550. if( res!=SQLITE_OK ){
  66551. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  66552. goto pragma_out;
  66553. }
  66554. }
  66555. }else
  66556. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  66557. /*
  66558. ** PRAGMA [database.]synchronous
  66559. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  66560. **
  66561. ** Return or set the local value of the synchronous flag. Changing
  66562. ** the local value does not make changes to the disk file and the
  66563. ** default value will be restored the next time the database is
  66564. ** opened.
  66565. */
  66566. if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
  66567. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66568. if( !zRight ){
  66569. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  66570. }else{
  66571. if( !db->autoCommit ){
  66572. sqlite3ErrorMsg(pParse,
  66573. "Safety level may not be changed inside a transaction");
  66574. }else{
  66575. pDb->safety_level = getSafetyLevel(zRight)+1;
  66576. }
  66577. }
  66578. }else
  66579. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  66580. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  66581. if( flagPragma(pParse, zLeft, zRight) ){
  66582. /* The flagPragma() subroutine also generates any necessary code
  66583. ** there is nothing more to do here */
  66584. }else
  66585. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  66586. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  66587. /*
  66588. ** PRAGMA table_info(<table>)
  66589. **
  66590. ** Return a single row for each column of the named table. The columns of
  66591. ** the returned data set are:
  66592. **
  66593. ** cid: Column id (numbered from left to right, starting at 0)
  66594. ** name: Column name
  66595. ** type: Column declaration type.
  66596. ** notnull: True if 'NOT NULL' is part of column declaration
  66597. ** dflt_value: The default value for the column, if any.
  66598. */
  66599. if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
  66600. Table *pTab;
  66601. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66602. pTab = sqlite3FindTable(db, zRight, zDb);
  66603. if( pTab ){
  66604. int i;
  66605. int nHidden = 0;
  66606. Column *pCol;
  66607. sqlite3VdbeSetNumCols(v, 6);
  66608. pParse->nMem = 6;
  66609. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  66610. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  66611. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  66612. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  66613. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  66614. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  66615. sqlite3ViewGetColumnNames(pParse, pTab);
  66616. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  66617. const Token *pDflt;
  66618. if( IsHiddenColumn(pCol) ){
  66619. nHidden++;
  66620. continue;
  66621. }
  66622. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  66623. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  66624. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  66625. pCol->zType ? pCol->zType : "", 0);
  66626. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  66627. if( pCol->pDflt ){
  66628. pDflt = &pCol->pDflt->span;
  66629. assert( pDflt->z );
  66630. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pDflt->z, pDflt->n);
  66631. }else{
  66632. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  66633. }
  66634. sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
  66635. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  66636. }
  66637. }
  66638. }else
  66639. if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
  66640. Index *pIdx;
  66641. Table *pTab;
  66642. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66643. pIdx = sqlite3FindIndex(db, zRight, zDb);
  66644. if( pIdx ){
  66645. int i;
  66646. pTab = pIdx->pTable;
  66647. sqlite3VdbeSetNumCols(v, 3);
  66648. pParse->nMem = 3;
  66649. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  66650. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  66651. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  66652. for(i=0; i<pIdx->nColumn; i++){
  66653. int cnum = pIdx->aiColumn[i];
  66654. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  66655. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  66656. assert( pTab->nCol>cnum );
  66657. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  66658. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  66659. }
  66660. }
  66661. }else
  66662. if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
  66663. Index *pIdx;
  66664. Table *pTab;
  66665. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66666. pTab = sqlite3FindTable(db, zRight, zDb);
  66667. if( pTab ){
  66668. v = sqlite3GetVdbe(pParse);
  66669. pIdx = pTab->pIndex;
  66670. if( pIdx ){
  66671. int i = 0;
  66672. sqlite3VdbeSetNumCols(v, 3);
  66673. pParse->nMem = 3;
  66674. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  66675. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  66676. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  66677. while(pIdx){
  66678. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  66679. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  66680. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
  66681. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  66682. ++i;
  66683. pIdx = pIdx->pNext;
  66684. }
  66685. }
  66686. }
  66687. }else
  66688. if( sqlite3StrICmp(zLeft, "database_list")==0 ){
  66689. int i;
  66690. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66691. sqlite3VdbeSetNumCols(v, 3);
  66692. pParse->nMem = 3;
  66693. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  66694. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  66695. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  66696. for(i=0; i<db->nDb; i++){
  66697. if( db->aDb[i].pBt==0 ) continue;
  66698. assert( db->aDb[i].zName!=0 );
  66699. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  66700. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  66701. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  66702. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  66703. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  66704. }
  66705. }else
  66706. if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
  66707. int i = 0;
  66708. HashElem *p;
  66709. sqlite3VdbeSetNumCols(v, 2);
  66710. pParse->nMem = 2;
  66711. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  66712. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  66713. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  66714. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  66715. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  66716. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  66717. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  66718. }
  66719. }else
  66720. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  66721. #ifndef SQLITE_OMIT_FOREIGN_KEY
  66722. if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
  66723. FKey *pFK;
  66724. Table *pTab;
  66725. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66726. pTab = sqlite3FindTable(db, zRight, zDb);
  66727. if( pTab ){
  66728. v = sqlite3GetVdbe(pParse);
  66729. pFK = pTab->pFKey;
  66730. if( pFK ){
  66731. int i = 0;
  66732. sqlite3VdbeSetNumCols(v, 8);
  66733. pParse->nMem = 8;
  66734. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  66735. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  66736. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  66737. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  66738. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  66739. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  66740. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  66741. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  66742. while(pFK){
  66743. int j;
  66744. for(j=0; j<pFK->nCol; j++){
  66745. char *zCol = pFK->aCol[j].zCol;
  66746. char *zOnUpdate = (char *)actionName(pFK->updateConf);
  66747. char *zOnDelete = (char *)actionName(pFK->deleteConf);
  66748. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  66749. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  66750. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  66751. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  66752. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  66753. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  66754. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  66755. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  66756. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  66757. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  66758. }
  66759. ++i;
  66760. pFK = pFK->pNextFrom;
  66761. }
  66762. }
  66763. }
  66764. }else
  66765. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  66766. #ifndef NDEBUG
  66767. if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
  66768. if( zRight ){
  66769. if( getBoolean(zRight) ){
  66770. sqlite3ParserTrace(stderr, "parser: ");
  66771. }else{
  66772. sqlite3ParserTrace(0, 0);
  66773. }
  66774. }
  66775. }else
  66776. #endif
  66777. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  66778. ** used will be case sensitive or not depending on the RHS.
  66779. */
  66780. if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
  66781. if( zRight ){
  66782. sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
  66783. }
  66784. }else
  66785. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  66786. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  66787. #endif
  66788. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  66789. /* Pragma "quick_check" is an experimental reduced version of
  66790. ** integrity_check designed to detect most database corruption
  66791. ** without most of the overhead of a full integrity-check.
  66792. */
  66793. if( sqlite3StrICmp(zLeft, "integrity_check")==0
  66794. || sqlite3StrICmp(zLeft, "quick_check")==0
  66795. ){
  66796. int i, j, addr, mxErr;
  66797. /* Code that appears at the end of the integrity check. If no error
  66798. ** messages have been generated, output OK. Otherwise output the
  66799. ** error message
  66800. */
  66801. static const VdbeOpList endCode[] = {
  66802. { OP_AddImm, 1, 0, 0}, /* 0 */
  66803. { OP_IfNeg, 1, 0, 0}, /* 1 */
  66804. { OP_String8, 0, 3, 0}, /* 2 */
  66805. { OP_ResultRow, 3, 1, 0},
  66806. };
  66807. int isQuick = (zLeft[0]=='q');
  66808. /* Initialize the VDBE program */
  66809. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66810. pParse->nMem = 6;
  66811. sqlite3VdbeSetNumCols(v, 1);
  66812. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  66813. /* Set the maximum error count */
  66814. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  66815. if( zRight ){
  66816. mxErr = atoi(zRight);
  66817. if( mxErr<=0 ){
  66818. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  66819. }
  66820. }
  66821. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  66822. /* Do an integrity check on each database file */
  66823. for(i=0; i<db->nDb; i++){
  66824. HashElem *x;
  66825. Hash *pTbls;
  66826. int cnt = 0;
  66827. if( OMIT_TEMPDB && i==1 ) continue;
  66828. sqlite3CodeVerifySchema(pParse, i);
  66829. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  66830. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  66831. sqlite3VdbeJumpHere(v, addr);
  66832. /* Do an integrity check of the B-Tree
  66833. **
  66834. ** Begin by filling registers 2, 3, ... with the root pages numbers
  66835. ** for all tables and indices in the database.
  66836. */
  66837. pTbls = &db->aDb[i].pSchema->tblHash;
  66838. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  66839. Table *pTab = sqliteHashData(x);
  66840. Index *pIdx;
  66841. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  66842. cnt++;
  66843. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  66844. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  66845. cnt++;
  66846. }
  66847. }
  66848. if( cnt==0 ) continue;
  66849. /* Make sure sufficient number of registers have been allocated */
  66850. if( pParse->nMem < cnt+4 ){
  66851. pParse->nMem = cnt+4;
  66852. }
  66853. /* Do the b-tree integrity checks */
  66854. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  66855. sqlite3VdbeChangeP5(v, (u8)i);
  66856. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  66857. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  66858. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  66859. P4_DYNAMIC);
  66860. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  66861. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  66862. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  66863. sqlite3VdbeJumpHere(v, addr);
  66864. /* Make sure all the indices are constructed correctly.
  66865. */
  66866. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  66867. Table *pTab = sqliteHashData(x);
  66868. Index *pIdx;
  66869. int loopTop;
  66870. if( pTab->pIndex==0 ) continue;
  66871. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  66872. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  66873. sqlite3VdbeJumpHere(v, addr);
  66874. sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  66875. sqlite3VdbeAddOp2(v, OP_Integer, 0, 2); /* reg(2) will count entries */
  66876. loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
  66877. sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1); /* increment entry count */
  66878. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  66879. int jmp2;
  66880. static const VdbeOpList idxErr[] = {
  66881. { OP_AddImm, 1, -1, 0},
  66882. { OP_String8, 0, 3, 0}, /* 1 */
  66883. { OP_Rowid, 1, 4, 0},
  66884. { OP_String8, 0, 5, 0}, /* 3 */
  66885. { OP_String8, 0, 6, 0}, /* 4 */
  66886. { OP_Concat, 4, 3, 3},
  66887. { OP_Concat, 5, 3, 3},
  66888. { OP_Concat, 6, 3, 3},
  66889. { OP_ResultRow, 3, 1, 0},
  66890. { OP_IfPos, 1, 0, 0}, /* 9 */
  66891. { OP_Halt, 0, 0, 0},
  66892. };
  66893. sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 1);
  66894. jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3);
  66895. addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  66896. sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  66897. sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  66898. sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
  66899. sqlite3VdbeJumpHere(v, addr+9);
  66900. sqlite3VdbeJumpHere(v, jmp2);
  66901. }
  66902. sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
  66903. sqlite3VdbeJumpHere(v, loopTop);
  66904. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  66905. static const VdbeOpList cntIdx[] = {
  66906. { OP_Integer, 0, 3, 0},
  66907. { OP_Rewind, 0, 0, 0}, /* 1 */
  66908. { OP_AddImm, 3, 1, 0},
  66909. { OP_Next, 0, 0, 0}, /* 3 */
  66910. { OP_Eq, 2, 0, 3}, /* 4 */
  66911. { OP_AddImm, 1, -1, 0},
  66912. { OP_String8, 0, 2, 0}, /* 6 */
  66913. { OP_String8, 0, 3, 0}, /* 7 */
  66914. { OP_Concat, 3, 2, 2},
  66915. { OP_ResultRow, 2, 1, 0},
  66916. };
  66917. if( pIdx->tnum==0 ) continue;
  66918. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
  66919. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  66920. sqlite3VdbeJumpHere(v, addr);
  66921. addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
  66922. sqlite3VdbeChangeP1(v, addr+1, j+2);
  66923. sqlite3VdbeChangeP2(v, addr+1, addr+4);
  66924. sqlite3VdbeChangeP1(v, addr+3, j+2);
  66925. sqlite3VdbeChangeP2(v, addr+3, addr+2);
  66926. sqlite3VdbeJumpHere(v, addr+4);
  66927. sqlite3VdbeChangeP4(v, addr+6,
  66928. "wrong # of entries in index ", P4_STATIC);
  66929. sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
  66930. }
  66931. }
  66932. }
  66933. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  66934. sqlite3VdbeChangeP2(v, addr, -mxErr);
  66935. sqlite3VdbeJumpHere(v, addr+1);
  66936. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  66937. }else
  66938. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  66939. #ifndef SQLITE_OMIT_UTF16
  66940. /*
  66941. ** PRAGMA encoding
  66942. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  66943. **
  66944. ** In its first form, this pragma returns the encoding of the main
  66945. ** database. If the database is not initialized, it is initialized now.
  66946. **
  66947. ** The second form of this pragma is a no-op if the main database file
  66948. ** has not already been initialized. In this case it sets the default
  66949. ** encoding that will be used for the main database file if a new file
  66950. ** is created. If an existing main database file is opened, then the
  66951. ** default text encoding for the existing database is used.
  66952. **
  66953. ** In all cases new databases created using the ATTACH command are
  66954. ** created to use the same default text encoding as the main database. If
  66955. ** the main database has not been initialized and/or created when ATTACH
  66956. ** is executed, this is done before the ATTACH operation.
  66957. **
  66958. ** In the second form this pragma sets the text encoding to be used in
  66959. ** new database files created using this database handle. It is only
  66960. ** useful if invoked immediately after the main database i
  66961. */
  66962. if( sqlite3StrICmp(zLeft, "encoding")==0 ){
  66963. static const struct EncName {
  66964. char *zName;
  66965. u8 enc;
  66966. } encnames[] = {
  66967. { "UTF8", SQLITE_UTF8 },
  66968. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  66969. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  66970. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  66971. { "UTF16le", SQLITE_UTF16LE },
  66972. { "UTF16be", SQLITE_UTF16BE },
  66973. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  66974. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  66975. { 0, 0 }
  66976. };
  66977. const struct EncName *pEnc;
  66978. if( !zRight ){ /* "PRAGMA encoding" */
  66979. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  66980. sqlite3VdbeSetNumCols(v, 1);
  66981. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  66982. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  66983. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  66984. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  66985. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  66986. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  66987. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  66988. }else{ /* "PRAGMA encoding = XXX" */
  66989. /* Only change the value of sqlite.enc if the database handle is not
  66990. ** initialized. If the main database exists, the new sqlite.enc value
  66991. ** will be overwritten when the schema is next loaded. If it does not
  66992. ** already exists, it will be created to use the new encoding value.
  66993. */
  66994. if(
  66995. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  66996. DbHasProperty(db, 0, DB_Empty)
  66997. ){
  66998. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  66999. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  67000. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  67001. break;
  67002. }
  67003. }
  67004. if( !pEnc->zName ){
  67005. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  67006. }
  67007. }
  67008. }
  67009. }else
  67010. #endif /* SQLITE_OMIT_UTF16 */
  67011. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  67012. /*
  67013. ** PRAGMA [database.]schema_version
  67014. ** PRAGMA [database.]schema_version = <integer>
  67015. **
  67016. ** PRAGMA [database.]user_version
  67017. ** PRAGMA [database.]user_version = <integer>
  67018. **
  67019. ** The pragma's schema_version and user_version are used to set or get
  67020. ** the value of the schema-version and user-version, respectively. Both
  67021. ** the schema-version and the user-version are 32-bit signed integers
  67022. ** stored in the database header.
  67023. **
  67024. ** The schema-cookie is usually only manipulated internally by SQLite. It
  67025. ** is incremented by SQLite whenever the database schema is modified (by
  67026. ** creating or dropping a table or index). The schema version is used by
  67027. ** SQLite each time a query is executed to ensure that the internal cache
  67028. ** of the schema used when compiling the SQL query matches the schema of
  67029. ** the database against which the compiled query is actually executed.
  67030. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  67031. ** the schema-version is potentially dangerous and may lead to program
  67032. ** crashes or database corruption. Use with caution!
  67033. **
  67034. ** The user-version is not used internally by SQLite. It may be used by
  67035. ** applications for any purpose.
  67036. */
  67037. if( sqlite3StrICmp(zLeft, "schema_version")==0
  67038. || sqlite3StrICmp(zLeft, "user_version")==0
  67039. || sqlite3StrICmp(zLeft, "freelist_count")==0
  67040. ){
  67041. int iCookie; /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
  67042. sqlite3VdbeUsesBtree(v, iDb);
  67043. switch( zLeft[0] ){
  67044. case 's': case 'S':
  67045. iCookie = 0;
  67046. break;
  67047. case 'f': case 'F':
  67048. iCookie = 1;
  67049. iDb = (-1*(iDb+1));
  67050. assert(iDb<=0);
  67051. break;
  67052. default:
  67053. iCookie = 5;
  67054. break;
  67055. }
  67056. if( zRight && iDb>=0 ){
  67057. /* Write the specified cookie value */
  67058. static const VdbeOpList setCookie[] = {
  67059. { OP_Transaction, 0, 1, 0}, /* 0 */
  67060. { OP_Integer, 0, 1, 0}, /* 1 */
  67061. { OP_SetCookie, 0, 0, 1}, /* 2 */
  67062. };
  67063. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
  67064. sqlite3VdbeChangeP1(v, addr, iDb);
  67065. sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
  67066. sqlite3VdbeChangeP1(v, addr+2, iDb);
  67067. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  67068. }else{
  67069. /* Read the specified cookie value */
  67070. static const VdbeOpList readCookie[] = {
  67071. { OP_ReadCookie, 0, 1, 0}, /* 0 */
  67072. { OP_ResultRow, 1, 1, 0}
  67073. };
  67074. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
  67075. sqlite3VdbeChangeP1(v, addr, iDb);
  67076. sqlite3VdbeChangeP3(v, addr, iCookie);
  67077. sqlite3VdbeSetNumCols(v, 1);
  67078. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  67079. }
  67080. }else
  67081. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  67082. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  67083. /*
  67084. ** Report the current state of file logs for all databases
  67085. */
  67086. if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
  67087. static const char *const azLockName[] = {
  67088. "unlocked", "shared", "reserved", "pending", "exclusive"
  67089. };
  67090. int i;
  67091. sqlite3VdbeSetNumCols(v, 2);
  67092. pParse->nMem = 2;
  67093. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  67094. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  67095. for(i=0; i<db->nDb; i++){
  67096. Btree *pBt;
  67097. Pager *pPager;
  67098. const char *zState = "unknown";
  67099. int j;
  67100. if( db->aDb[i].zName==0 ) continue;
  67101. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  67102. pBt = db->aDb[i].pBt;
  67103. if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
  67104. zState = "closed";
  67105. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  67106. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  67107. zState = azLockName[j];
  67108. }
  67109. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  67110. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  67111. }
  67112. }else
  67113. #endif
  67114. #ifdef SQLITE_SSE
  67115. /*
  67116. ** Check to see if the sqlite_statements table exists. Create it
  67117. ** if it does not.
  67118. */
  67119. if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
  67120. extern int sqlite3CreateStatementsTable(Parse*);
  67121. sqlite3CreateStatementsTable(pParse);
  67122. }else
  67123. #endif
  67124. #if SQLITE_HAS_CODEC
  67125. if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
  67126. sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
  67127. }else
  67128. if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
  67129. sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
  67130. }else
  67131. if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
  67132. sqlite3StrICmp(zLeft, "hexrekey")==0) ){
  67133. int i, h1, h2;
  67134. char zKey[40];
  67135. for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
  67136. h1 += 9*(1&(h1>>6));
  67137. h2 += 9*(1&(h2>>6));
  67138. zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
  67139. }
  67140. if( (zLeft[3] & 0xf)==0xb ){
  67141. sqlite3_key(db, zKey, i/2);
  67142. }else{
  67143. sqlite3_rekey(db, zKey, i/2);
  67144. }
  67145. }else
  67146. #endif
  67147. #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
  67148. if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
  67149. #if SQLITE_HAS_CODEC
  67150. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  67151. extern void sqlite3_activate_see(const char*);
  67152. sqlite3_activate_see(&zRight[4]);
  67153. }
  67154. #endif
  67155. #ifdef SQLITE_ENABLE_CEROD
  67156. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  67157. extern void sqlite3_activate_cerod(const char*);
  67158. sqlite3_activate_cerod(&zRight[6]);
  67159. }
  67160. #endif
  67161. }else
  67162. #endif
  67163. {/* Empty ELSE clause */}
  67164. /* Code an OP_Expire at the end of each PRAGMA program to cause
  67165. ** the VDBE implementing the pragma to expire. Most (all?) pragmas
  67166. ** are only valid for a single execution.
  67167. */
  67168. sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
  67169. /*
  67170. ** Reset the safety level, in case the fullfsync flag or synchronous
  67171. ** setting changed.
  67172. */
  67173. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  67174. if( db->autoCommit ){
  67175. sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
  67176. (db->flags&SQLITE_FullFSync)!=0);
  67177. }
  67178. #endif
  67179. pragma_out:
  67180. sqlite3DbFree(db, zLeft);
  67181. sqlite3DbFree(db, zRight);
  67182. }
  67183. #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
  67184. /************** End of pragma.c **********************************************/
  67185. /************** Begin file prepare.c *****************************************/
  67186. /*
  67187. ** 2005 May 25
  67188. **
  67189. ** The author disclaims copyright to this source code. In place of
  67190. ** a legal notice, here is a blessing:
  67191. **
  67192. ** May you do good and not evil.
  67193. ** May you find forgiveness for yourself and forgive others.
  67194. ** May you share freely, never taking more than you give.
  67195. **
  67196. *************************************************************************
  67197. ** This file contains the implementation of the sqlite3_prepare()
  67198. ** interface, and routines that contribute to loading the database schema
  67199. ** from disk.
  67200. **
  67201. ** $Id: prepare.c,v 1.104 2009/01/09 02:49:32 drh Exp $
  67202. */
  67203. /*
  67204. ** Fill the InitData structure with an error message that indicates
  67205. ** that the database is corrupt.
  67206. */
  67207. static void corruptSchema(
  67208. InitData *pData, /* Initialization context */
  67209. const char *zObj, /* Object being parsed at the point of error */
  67210. const char *zExtra /* Error information */
  67211. ){
  67212. sqlite3 *db = pData->db;
  67213. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  67214. if( zObj==0 ) zObj = "?";
  67215. sqlite3SetString(pData->pzErrMsg, pData->db,
  67216. "malformed database schema (%s)", zObj);
  67217. if( zExtra && zExtra[0] ){
  67218. *pData->pzErrMsg = sqlite3MAppendf(pData->db, *pData->pzErrMsg, "%s - %s",
  67219. *pData->pzErrMsg, zExtra);
  67220. }
  67221. }
  67222. pData->rc = SQLITE_CORRUPT;
  67223. }
  67224. /*
  67225. ** This is the callback routine for the code that initializes the
  67226. ** database. See sqlite3Init() below for additional information.
  67227. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  67228. **
  67229. ** Each callback contains the following information:
  67230. **
  67231. ** argv[0] = name of thing being created
  67232. ** argv[1] = root page number for table or index. 0 for trigger or view.
  67233. ** argv[2] = SQL text for the CREATE statement.
  67234. **
  67235. */
  67236. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  67237. InitData *pData = (InitData*)pInit;
  67238. sqlite3 *db = pData->db;
  67239. int iDb = pData->iDb;
  67240. assert( argc==3 );
  67241. UNUSED_PARAMETER2(NotUsed, argc);
  67242. assert( sqlite3_mutex_held(db->mutex) );
  67243. DbClearProperty(db, iDb, DB_Empty);
  67244. if( db->mallocFailed ){
  67245. corruptSchema(pData, argv[0], 0);
  67246. return SQLITE_NOMEM;
  67247. }
  67248. assert( iDb>=0 && iDb<db->nDb );
  67249. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  67250. if( argv[1]==0 ){
  67251. corruptSchema(pData, argv[0], 0);
  67252. }else if( argv[2] && argv[2][0] ){
  67253. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  67254. ** But because db->init.busy is set to 1, no VDBE code is generated
  67255. ** or executed. All the parser does is build the internal data
  67256. ** structures that describe the table, index, or view.
  67257. */
  67258. char *zErr;
  67259. int rc;
  67260. u8 lookasideEnabled;
  67261. assert( db->init.busy );
  67262. db->init.iDb = iDb;
  67263. db->init.newTnum = atoi(argv[1]);
  67264. lookasideEnabled = db->lookaside.bEnabled;
  67265. db->lookaside.bEnabled = 0;
  67266. rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
  67267. db->init.iDb = 0;
  67268. db->lookaside.bEnabled = lookasideEnabled;
  67269. assert( rc!=SQLITE_OK || zErr==0 );
  67270. if( SQLITE_OK!=rc ){
  67271. pData->rc = rc;
  67272. if( rc==SQLITE_NOMEM ){
  67273. db->mallocFailed = 1;
  67274. }else if( rc!=SQLITE_INTERRUPT ){
  67275. corruptSchema(pData, argv[0], zErr);
  67276. }
  67277. sqlite3DbFree(db, zErr);
  67278. }
  67279. }else if( argv[0]==0 ){
  67280. corruptSchema(pData, 0, 0);
  67281. }else{
  67282. /* If the SQL column is blank it means this is an index that
  67283. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  67284. ** constraint for a CREATE TABLE. The index should have already
  67285. ** been created when we processed the CREATE TABLE. All we have
  67286. ** to do here is record the root page number for that index.
  67287. */
  67288. Index *pIndex;
  67289. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  67290. if( pIndex==0 || pIndex->tnum!=0 ){
  67291. /* This can occur if there exists an index on a TEMP table which
  67292. ** has the same name as another index on a permanent index. Since
  67293. ** the permanent table is hidden by the TEMP table, we can also
  67294. ** safely ignore the index on the permanent table.
  67295. */
  67296. /* Do Nothing */;
  67297. }else{
  67298. pIndex->tnum = atoi(argv[1]);
  67299. }
  67300. }
  67301. return 0;
  67302. }
  67303. /*
  67304. ** Attempt to read the database schema and initialize internal
  67305. ** data structures for a single database file. The index of the
  67306. ** database file is given by iDb. iDb==0 is used for the main
  67307. ** database. iDb==1 should never be used. iDb>=2 is used for
  67308. ** auxiliary databases. Return one of the SQLITE_ error codes to
  67309. ** indicate success or failure.
  67310. */
  67311. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  67312. int rc;
  67313. BtCursor *curMain;
  67314. int size;
  67315. Table *pTab;
  67316. Db *pDb;
  67317. char const *azArg[4];
  67318. int meta[10];
  67319. InitData initData;
  67320. char const *zMasterSchema;
  67321. char const *zMasterName = SCHEMA_TABLE(iDb);
  67322. /*
  67323. ** The master database table has a structure like this
  67324. */
  67325. static const char master_schema[] =
  67326. "CREATE TABLE sqlite_master(\n"
  67327. " type text,\n"
  67328. " name text,\n"
  67329. " tbl_name text,\n"
  67330. " rootpage integer,\n"
  67331. " sql text\n"
  67332. ")"
  67333. ;
  67334. #ifndef SQLITE_OMIT_TEMPDB
  67335. static const char temp_master_schema[] =
  67336. "CREATE TEMP TABLE sqlite_temp_master(\n"
  67337. " type text,\n"
  67338. " name text,\n"
  67339. " tbl_name text,\n"
  67340. " rootpage integer,\n"
  67341. " sql text\n"
  67342. ")"
  67343. ;
  67344. #else
  67345. #define temp_master_schema 0
  67346. #endif
  67347. assert( iDb>=0 && iDb<db->nDb );
  67348. assert( db->aDb[iDb].pSchema );
  67349. assert( sqlite3_mutex_held(db->mutex) );
  67350. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  67351. /* zMasterSchema and zInitScript are set to point at the master schema
  67352. ** and initialisation script appropriate for the database being
  67353. ** initialised. zMasterName is the name of the master table.
  67354. */
  67355. if( !OMIT_TEMPDB && iDb==1 ){
  67356. zMasterSchema = temp_master_schema;
  67357. }else{
  67358. zMasterSchema = master_schema;
  67359. }
  67360. zMasterName = SCHEMA_TABLE(iDb);
  67361. /* Construct the schema tables. */
  67362. azArg[0] = zMasterName;
  67363. azArg[1] = "1";
  67364. azArg[2] = zMasterSchema;
  67365. azArg[3] = 0;
  67366. initData.db = db;
  67367. initData.iDb = iDb;
  67368. initData.rc = SQLITE_OK;
  67369. initData.pzErrMsg = pzErrMsg;
  67370. (void)sqlite3SafetyOff(db);
  67371. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  67372. (void)sqlite3SafetyOn(db);
  67373. if( initData.rc ){
  67374. rc = initData.rc;
  67375. goto error_out;
  67376. }
  67377. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  67378. if( pTab ){
  67379. pTab->tabFlags |= TF_Readonly;
  67380. }
  67381. /* Create a cursor to hold the database open
  67382. */
  67383. pDb = &db->aDb[iDb];
  67384. if( pDb->pBt==0 ){
  67385. if( !OMIT_TEMPDB && iDb==1 ){
  67386. DbSetProperty(db, 1, DB_SchemaLoaded);
  67387. }
  67388. return SQLITE_OK;
  67389. }
  67390. curMain = sqlite3MallocZero(sqlite3BtreeCursorSize());
  67391. if( !curMain ){
  67392. rc = SQLITE_NOMEM;
  67393. goto error_out;
  67394. }
  67395. sqlite3BtreeEnter(pDb->pBt);
  67396. rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
  67397. if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
  67398. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  67399. goto initone_error_out;
  67400. }
  67401. /* Get the database meta information.
  67402. **
  67403. ** Meta values are as follows:
  67404. ** meta[0] Schema cookie. Changes with each schema change.
  67405. ** meta[1] File format of schema layer.
  67406. ** meta[2] Size of the page cache.
  67407. ** meta[3] Use freelist if 0. Autovacuum if greater than zero.
  67408. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  67409. ** meta[5] The user cookie. Used by the application.
  67410. ** meta[6] Incremental-vacuum flag.
  67411. ** meta[7]
  67412. ** meta[8]
  67413. ** meta[9]
  67414. **
  67415. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  67416. ** the possible values of meta[4].
  67417. */
  67418. if( rc==SQLITE_OK ){
  67419. int i;
  67420. for(i=0; i<ArraySize(meta); i++){
  67421. rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  67422. if( rc ){
  67423. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  67424. goto initone_error_out;
  67425. }
  67426. }
  67427. }else{
  67428. memset(meta, 0, sizeof(meta));
  67429. }
  67430. pDb->pSchema->schema_cookie = meta[0];
  67431. /* If opening a non-empty database, check the text encoding. For the
  67432. ** main database, set sqlite3.enc to the encoding of the main database.
  67433. ** For an attached db, it is an error if the encoding is not the same
  67434. ** as sqlite3.enc.
  67435. */
  67436. if( meta[4] ){ /* text encoding */
  67437. if( iDb==0 ){
  67438. /* If opening the main database, set ENC(db). */
  67439. ENC(db) = (u8)meta[4];
  67440. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
  67441. }else{
  67442. /* If opening an attached database, the encoding much match ENC(db) */
  67443. if( meta[4]!=ENC(db) ){
  67444. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  67445. " text encoding as main database");
  67446. rc = SQLITE_ERROR;
  67447. goto initone_error_out;
  67448. }
  67449. }
  67450. }else{
  67451. DbSetProperty(db, iDb, DB_Empty);
  67452. }
  67453. pDb->pSchema->enc = ENC(db);
  67454. if( pDb->pSchema->cache_size==0 ){
  67455. size = meta[2];
  67456. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  67457. if( size<0 ) size = -size;
  67458. pDb->pSchema->cache_size = size;
  67459. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  67460. }
  67461. /*
  67462. ** file_format==1 Version 3.0.0.
  67463. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  67464. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  67465. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  67466. */
  67467. pDb->pSchema->file_format = (u8)meta[1];
  67468. if( pDb->pSchema->file_format==0 ){
  67469. pDb->pSchema->file_format = 1;
  67470. }
  67471. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  67472. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  67473. rc = SQLITE_ERROR;
  67474. goto initone_error_out;
  67475. }
  67476. /* Ticket #2804: When we open a database in the newer file format,
  67477. ** clear the legacy_file_format pragma flag so that a VACUUM will
  67478. ** not downgrade the database and thus invalidate any descending
  67479. ** indices that the user might have created.
  67480. */
  67481. if( iDb==0 && meta[1]>=4 ){
  67482. db->flags &= ~SQLITE_LegacyFileFmt;
  67483. }
  67484. /* Read the schema information out of the schema tables
  67485. */
  67486. assert( db->init.busy );
  67487. if( rc==SQLITE_EMPTY ){
  67488. /* For an empty database, there is nothing to read */
  67489. rc = SQLITE_OK;
  67490. }else{
  67491. char *zSql;
  67492. zSql = sqlite3MPrintf(db,
  67493. "SELECT name, rootpage, sql FROM '%q'.%s",
  67494. db->aDb[iDb].zName, zMasterName);
  67495. (void)sqlite3SafetyOff(db);
  67496. #ifndef SQLITE_OMIT_AUTHORIZATION
  67497. {
  67498. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  67499. xAuth = db->xAuth;
  67500. db->xAuth = 0;
  67501. #endif
  67502. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  67503. #ifndef SQLITE_OMIT_AUTHORIZATION
  67504. db->xAuth = xAuth;
  67505. }
  67506. #endif
  67507. if( rc==SQLITE_OK ) rc = initData.rc;
  67508. (void)sqlite3SafetyOn(db);
  67509. sqlite3DbFree(db, zSql);
  67510. #ifndef SQLITE_OMIT_ANALYZE
  67511. if( rc==SQLITE_OK ){
  67512. sqlite3AnalysisLoad(db, iDb);
  67513. }
  67514. #endif
  67515. }
  67516. if( db->mallocFailed ){
  67517. rc = SQLITE_NOMEM;
  67518. sqlite3ResetInternalSchema(db, 0);
  67519. }
  67520. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  67521. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  67522. ** the schema loaded, even if errors occured. In this situation the
  67523. ** current sqlite3_prepare() operation will fail, but the following one
  67524. ** will attempt to compile the supplied statement against whatever subset
  67525. ** of the schema was loaded before the error occured. The primary
  67526. ** purpose of this is to allow access to the sqlite_master table
  67527. ** even when its contents have been corrupted.
  67528. */
  67529. DbSetProperty(db, iDb, DB_SchemaLoaded);
  67530. rc = SQLITE_OK;
  67531. }
  67532. /* Jump here for an error that occurs after successfully allocating
  67533. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  67534. ** before that point, jump to error_out.
  67535. */
  67536. initone_error_out:
  67537. sqlite3BtreeCloseCursor(curMain);
  67538. sqlite3_free(curMain);
  67539. sqlite3BtreeLeave(pDb->pBt);
  67540. error_out:
  67541. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  67542. db->mallocFailed = 1;
  67543. }
  67544. return rc;
  67545. }
  67546. /*
  67547. ** Initialize all database files - the main database file, the file
  67548. ** used to store temporary tables, and any additional database files
  67549. ** created using ATTACH statements. Return a success code. If an
  67550. ** error occurs, write an error message into *pzErrMsg.
  67551. **
  67552. ** After a database is initialized, the DB_SchemaLoaded bit is set
  67553. ** bit is set in the flags field of the Db structure. If the database
  67554. ** file was of zero-length, then the DB_Empty flag is also set.
  67555. */
  67556. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  67557. int i, rc;
  67558. int commit_internal = !(db->flags&SQLITE_InternChanges);
  67559. assert( sqlite3_mutex_held(db->mutex) );
  67560. if( db->init.busy ) return SQLITE_OK;
  67561. rc = SQLITE_OK;
  67562. db->init.busy = 1;
  67563. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  67564. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  67565. rc = sqlite3InitOne(db, i, pzErrMsg);
  67566. if( rc ){
  67567. sqlite3ResetInternalSchema(db, i);
  67568. }
  67569. }
  67570. /* Once all the other databases have been initialised, load the schema
  67571. ** for the TEMP database. This is loaded last, as the TEMP database
  67572. ** schema may contain references to objects in other databases.
  67573. */
  67574. #ifndef SQLITE_OMIT_TEMPDB
  67575. if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  67576. rc = sqlite3InitOne(db, 1, pzErrMsg);
  67577. if( rc ){
  67578. sqlite3ResetInternalSchema(db, 1);
  67579. }
  67580. }
  67581. #endif
  67582. db->init.busy = 0;
  67583. if( rc==SQLITE_OK && commit_internal ){
  67584. sqlite3CommitInternalChanges(db);
  67585. }
  67586. return rc;
  67587. }
  67588. /*
  67589. ** This routine is a no-op if the database schema is already initialised.
  67590. ** Otherwise, the schema is loaded. An error code is returned.
  67591. */
  67592. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  67593. int rc = SQLITE_OK;
  67594. sqlite3 *db = pParse->db;
  67595. assert( sqlite3_mutex_held(db->mutex) );
  67596. if( !db->init.busy ){
  67597. rc = sqlite3Init(db, &pParse->zErrMsg);
  67598. }
  67599. if( rc!=SQLITE_OK ){
  67600. pParse->rc = rc;
  67601. pParse->nErr++;
  67602. }
  67603. return rc;
  67604. }
  67605. /*
  67606. ** Check schema cookies in all databases. If any cookie is out
  67607. ** of date, return 0. If all schema cookies are current, return 1.
  67608. */
  67609. static int schemaIsValid(sqlite3 *db){
  67610. int iDb;
  67611. int rc;
  67612. BtCursor *curTemp;
  67613. int cookie;
  67614. int allOk = 1;
  67615. curTemp = (BtCursor *)sqlite3Malloc(sqlite3BtreeCursorSize());
  67616. if( curTemp ){
  67617. assert( sqlite3_mutex_held(db->mutex) );
  67618. for(iDb=0; allOk && iDb<db->nDb; iDb++){
  67619. Btree *pBt;
  67620. pBt = db->aDb[iDb].pBt;
  67621. if( pBt==0 ) continue;
  67622. memset(curTemp, 0, sqlite3BtreeCursorSize());
  67623. rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, curTemp);
  67624. if( rc==SQLITE_OK ){
  67625. rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
  67626. if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  67627. allOk = 0;
  67628. }
  67629. sqlite3BtreeCloseCursor(curTemp);
  67630. }
  67631. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  67632. db->mallocFailed = 1;
  67633. }
  67634. }
  67635. sqlite3_free(curTemp);
  67636. }else{
  67637. allOk = 0;
  67638. db->mallocFailed = 1;
  67639. }
  67640. return allOk;
  67641. }
  67642. /*
  67643. ** Convert a schema pointer into the iDb index that indicates
  67644. ** which database file in db->aDb[] the schema refers to.
  67645. **
  67646. ** If the same database is attached more than once, the first
  67647. ** attached database is returned.
  67648. */
  67649. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  67650. int i = -1000000;
  67651. /* If pSchema is NULL, then return -1000000. This happens when code in
  67652. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  67653. ** created by a sub-select). In this case the return value of this
  67654. ** function should never be used.
  67655. **
  67656. ** We return -1000000 instead of the more usual -1 simply because using
  67657. ** -1000000 as the incorrect index into db->aDb[] is much
  67658. ** more likely to cause a segfault than -1 (of course there are assert()
  67659. ** statements too, but it never hurts to play the odds).
  67660. */
  67661. assert( sqlite3_mutex_held(db->mutex) );
  67662. if( pSchema ){
  67663. for(i=0; ALWAYS(i<db->nDb); i++){
  67664. if( db->aDb[i].pSchema==pSchema ){
  67665. break;
  67666. }
  67667. }
  67668. assert( i>=0 && i<db->nDb );
  67669. }
  67670. return i;
  67671. }
  67672. /*
  67673. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  67674. */
  67675. static int sqlite3Prepare(
  67676. sqlite3 *db, /* Database handle. */
  67677. const char *zSql, /* UTF-8 encoded SQL statement. */
  67678. int nBytes, /* Length of zSql in bytes. */
  67679. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  67680. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  67681. const char **pzTail /* OUT: End of parsed string */
  67682. ){
  67683. Parse sParse;
  67684. char *zErrMsg = 0;
  67685. int rc = SQLITE_OK;
  67686. int i;
  67687. assert( ppStmt );
  67688. *ppStmt = 0;
  67689. if( sqlite3SafetyOn(db) ){
  67690. return SQLITE_MISUSE;
  67691. }
  67692. assert( !db->mallocFailed );
  67693. assert( sqlite3_mutex_held(db->mutex) );
  67694. /* If any attached database schemas are locked, do not proceed with
  67695. ** compilation. Instead return SQLITE_LOCKED immediately.
  67696. */
  67697. for(i=0; i<db->nDb; i++) {
  67698. Btree *pBt = db->aDb[i].pBt;
  67699. if( pBt ){
  67700. rc = sqlite3BtreeSchemaLocked(pBt);
  67701. if( rc ){
  67702. const char *zDb = db->aDb[i].zName;
  67703. sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
  67704. (void)sqlite3SafetyOff(db);
  67705. return sqlite3ApiExit(db, SQLITE_LOCKED);
  67706. }
  67707. }
  67708. }
  67709. memset(&sParse, 0, sizeof(sParse));
  67710. sParse.db = db;
  67711. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  67712. char *zSqlCopy;
  67713. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  67714. if( nBytes>mxLen ){
  67715. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  67716. (void)sqlite3SafetyOff(db);
  67717. return sqlite3ApiExit(db, SQLITE_TOOBIG);
  67718. }
  67719. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  67720. if( zSqlCopy ){
  67721. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  67722. sqlite3DbFree(db, zSqlCopy);
  67723. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  67724. }else{
  67725. sParse.zTail = &zSql[nBytes];
  67726. }
  67727. }else{
  67728. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  67729. }
  67730. if( db->mallocFailed ){
  67731. sParse.rc = SQLITE_NOMEM;
  67732. }
  67733. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  67734. if( sParse.checkSchema && !schemaIsValid(db) ){
  67735. sParse.rc = SQLITE_SCHEMA;
  67736. }
  67737. if( sParse.rc==SQLITE_SCHEMA ){
  67738. sqlite3ResetInternalSchema(db, 0);
  67739. }
  67740. if( db->mallocFailed ){
  67741. sParse.rc = SQLITE_NOMEM;
  67742. }
  67743. if( pzTail ){
  67744. *pzTail = sParse.zTail;
  67745. }
  67746. rc = sParse.rc;
  67747. #ifndef SQLITE_OMIT_EXPLAIN
  67748. if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
  67749. if( sParse.explain==2 ){
  67750. sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
  67751. sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", SQLITE_STATIC);
  67752. sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", SQLITE_STATIC);
  67753. sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", SQLITE_STATIC);
  67754. }else{
  67755. sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
  67756. sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", SQLITE_STATIC);
  67757. sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", SQLITE_STATIC);
  67758. sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", SQLITE_STATIC);
  67759. sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", SQLITE_STATIC);
  67760. sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", SQLITE_STATIC);
  67761. sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", SQLITE_STATIC);
  67762. sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", SQLITE_STATIC);
  67763. sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment", SQLITE_STATIC);
  67764. }
  67765. }
  67766. #endif
  67767. if( sqlite3SafetyOff(db) ){
  67768. rc = SQLITE_MISUSE;
  67769. }
  67770. if( saveSqlFlag ){
  67771. sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail - zSql));
  67772. }
  67773. if( rc!=SQLITE_OK || db->mallocFailed ){
  67774. sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
  67775. assert(!(*ppStmt));
  67776. }else{
  67777. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  67778. }
  67779. if( zErrMsg ){
  67780. sqlite3Error(db, rc, "%s", zErrMsg);
  67781. sqlite3DbFree(db, zErrMsg);
  67782. }else{
  67783. sqlite3Error(db, rc, 0);
  67784. }
  67785. rc = sqlite3ApiExit(db, rc);
  67786. assert( (rc&db->errMask)==rc );
  67787. return rc;
  67788. }
  67789. static int sqlite3LockAndPrepare(
  67790. sqlite3 *db, /* Database handle. */
  67791. const char *zSql, /* UTF-8 encoded SQL statement. */
  67792. int nBytes, /* Length of zSql in bytes. */
  67793. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  67794. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  67795. const char **pzTail /* OUT: End of parsed string */
  67796. ){
  67797. int rc;
  67798. if( !sqlite3SafetyCheckOk(db) ){
  67799. return SQLITE_MISUSE;
  67800. }
  67801. sqlite3_mutex_enter(db->mutex);
  67802. sqlite3BtreeEnterAll(db);
  67803. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
  67804. sqlite3BtreeLeaveAll(db);
  67805. sqlite3_mutex_leave(db->mutex);
  67806. return rc;
  67807. }
  67808. /*
  67809. ** Rerun the compilation of a statement after a schema change.
  67810. ** Return true if the statement was recompiled successfully.
  67811. ** Return false if there is an error of some kind.
  67812. */
  67813. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  67814. int rc;
  67815. sqlite3_stmt *pNew;
  67816. const char *zSql;
  67817. sqlite3 *db;
  67818. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  67819. zSql = sqlite3_sql((sqlite3_stmt *)p);
  67820. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  67821. db = sqlite3VdbeDb(p);
  67822. assert( sqlite3_mutex_held(db->mutex) );
  67823. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
  67824. if( rc ){
  67825. if( rc==SQLITE_NOMEM ){
  67826. db->mallocFailed = 1;
  67827. }
  67828. assert( pNew==0 );
  67829. return 0;
  67830. }else{
  67831. assert( pNew!=0 );
  67832. }
  67833. sqlite3VdbeSwap((Vdbe*)pNew, p);
  67834. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  67835. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  67836. sqlite3VdbeFinalize((Vdbe*)pNew);
  67837. return 1;
  67838. }
  67839. /*
  67840. ** Two versions of the official API. Legacy and new use. In the legacy
  67841. ** version, the original SQL text is not saved in the prepared statement
  67842. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  67843. ** sqlite3_step(). In the new version, the original SQL text is retained
  67844. ** and the statement is automatically recompiled if an schema change
  67845. ** occurs.
  67846. */
  67847. SQLITE_API int sqlite3_prepare(
  67848. sqlite3 *db, /* Database handle. */
  67849. const char *zSql, /* UTF-8 encoded SQL statement. */
  67850. int nBytes, /* Length of zSql in bytes. */
  67851. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  67852. const char **pzTail /* OUT: End of parsed string */
  67853. ){
  67854. int rc;
  67855. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
  67856. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  67857. return rc;
  67858. }
  67859. SQLITE_API int sqlite3_prepare_v2(
  67860. sqlite3 *db, /* Database handle. */
  67861. const char *zSql, /* UTF-8 encoded SQL statement. */
  67862. int nBytes, /* Length of zSql in bytes. */
  67863. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  67864. const char **pzTail /* OUT: End of parsed string */
  67865. ){
  67866. int rc;
  67867. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
  67868. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  67869. return rc;
  67870. }
  67871. #ifndef SQLITE_OMIT_UTF16
  67872. /*
  67873. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  67874. */
  67875. static int sqlite3Prepare16(
  67876. sqlite3 *db, /* Database handle. */
  67877. const void *zSql, /* UTF-8 encoded SQL statement. */
  67878. int nBytes, /* Length of zSql in bytes. */
  67879. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  67880. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  67881. const void **pzTail /* OUT: End of parsed string */
  67882. ){
  67883. /* This function currently works by first transforming the UTF-16
  67884. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  67885. ** tricky bit is figuring out the pointer to return in *pzTail.
  67886. */
  67887. char *zSql8;
  67888. const char *zTail8 = 0;
  67889. int rc = SQLITE_OK;
  67890. if( !sqlite3SafetyCheckOk(db) ){
  67891. return SQLITE_MISUSE;
  67892. }
  67893. sqlite3_mutex_enter(db->mutex);
  67894. zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
  67895. if( zSql8 ){
  67896. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
  67897. }
  67898. if( zTail8 && pzTail ){
  67899. /* If sqlite3_prepare returns a tail pointer, we calculate the
  67900. ** equivalent pointer into the UTF-16 string by counting the unicode
  67901. ** characters between zSql8 and zTail8, and then returning a pointer
  67902. ** the same number of characters into the UTF-16 string.
  67903. */
  67904. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  67905. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  67906. }
  67907. sqlite3DbFree(db, zSql8);
  67908. rc = sqlite3ApiExit(db, rc);
  67909. sqlite3_mutex_leave(db->mutex);
  67910. return rc;
  67911. }
  67912. /*
  67913. ** Two versions of the official API. Legacy and new use. In the legacy
  67914. ** version, the original SQL text is not saved in the prepared statement
  67915. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  67916. ** sqlite3_step(). In the new version, the original SQL text is retained
  67917. ** and the statement is automatically recompiled if an schema change
  67918. ** occurs.
  67919. */
  67920. SQLITE_API int sqlite3_prepare16(
  67921. sqlite3 *db, /* Database handle. */
  67922. const void *zSql, /* UTF-8 encoded SQL statement. */
  67923. int nBytes, /* Length of zSql in bytes. */
  67924. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  67925. const void **pzTail /* OUT: End of parsed string */
  67926. ){
  67927. int rc;
  67928. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  67929. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  67930. return rc;
  67931. }
  67932. SQLITE_API int sqlite3_prepare16_v2(
  67933. sqlite3 *db, /* Database handle. */
  67934. const void *zSql, /* UTF-8 encoded SQL statement. */
  67935. int nBytes, /* Length of zSql in bytes. */
  67936. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  67937. const void **pzTail /* OUT: End of parsed string */
  67938. ){
  67939. int rc;
  67940. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  67941. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  67942. return rc;
  67943. }
  67944. #endif /* SQLITE_OMIT_UTF16 */
  67945. /************** End of prepare.c *********************************************/
  67946. /************** Begin file select.c ******************************************/
  67947. /*
  67948. ** 2001 September 15
  67949. **
  67950. ** The author disclaims copyright to this source code. In place of
  67951. ** a legal notice, here is a blessing:
  67952. **
  67953. ** May you do good and not evil.
  67954. ** May you find forgiveness for yourself and forgive others.
  67955. ** May you share freely, never taking more than you give.
  67956. **
  67957. *************************************************************************
  67958. ** This file contains C code routines that are called by the parser
  67959. ** to handle SELECT statements in SQLite.
  67960. **
  67961. ** $Id: select.c,v 1.498 2009/01/09 02:49:32 drh Exp $
  67962. */
  67963. /*
  67964. ** Delete all the content of a Select structure but do not deallocate
  67965. ** the select structure itself.
  67966. */
  67967. static void clearSelect(sqlite3 *db, Select *p){
  67968. sqlite3ExprListDelete(db, p->pEList);
  67969. sqlite3SrcListDelete(db, p->pSrc);
  67970. sqlite3ExprDelete(db, p->pWhere);
  67971. sqlite3ExprListDelete(db, p->pGroupBy);
  67972. sqlite3ExprDelete(db, p->pHaving);
  67973. sqlite3ExprListDelete(db, p->pOrderBy);
  67974. sqlite3SelectDelete(db, p->pPrior);
  67975. sqlite3ExprDelete(db, p->pLimit);
  67976. sqlite3ExprDelete(db, p->pOffset);
  67977. }
  67978. /*
  67979. ** Initialize a SelectDest structure.
  67980. */
  67981. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  67982. pDest->eDest = (u8)eDest;
  67983. pDest->iParm = iParm;
  67984. pDest->affinity = 0;
  67985. pDest->iMem = 0;
  67986. pDest->nMem = 0;
  67987. }
  67988. /*
  67989. ** Allocate a new Select structure and return a pointer to that
  67990. ** structure.
  67991. */
  67992. SQLITE_PRIVATE Select *sqlite3SelectNew(
  67993. Parse *pParse, /* Parsing context */
  67994. ExprList *pEList, /* which columns to include in the result */
  67995. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  67996. Expr *pWhere, /* the WHERE clause */
  67997. ExprList *pGroupBy, /* the GROUP BY clause */
  67998. Expr *pHaving, /* the HAVING clause */
  67999. ExprList *pOrderBy, /* the ORDER BY clause */
  68000. int isDistinct, /* true if the DISTINCT keyword is present */
  68001. Expr *pLimit, /* LIMIT value. NULL means not used */
  68002. Expr *pOffset /* OFFSET value. NULL means no offset */
  68003. ){
  68004. Select *pNew;
  68005. Select standin;
  68006. sqlite3 *db = pParse->db;
  68007. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  68008. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  68009. if( pNew==0 ){
  68010. pNew = &standin;
  68011. memset(pNew, 0, sizeof(*pNew));
  68012. }
  68013. if( pEList==0 ){
  68014. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
  68015. }
  68016. pNew->pEList = pEList;
  68017. pNew->pSrc = pSrc;
  68018. pNew->pWhere = pWhere;
  68019. pNew->pGroupBy = pGroupBy;
  68020. pNew->pHaving = pHaving;
  68021. pNew->pOrderBy = pOrderBy;
  68022. pNew->selFlags = isDistinct ? SF_Distinct : 0;
  68023. pNew->op = TK_SELECT;
  68024. pNew->pLimit = pLimit;
  68025. pNew->pOffset = pOffset;
  68026. pNew->addrOpenEphm[0] = -1;
  68027. pNew->addrOpenEphm[1] = -1;
  68028. pNew->addrOpenEphm[2] = -1;
  68029. if( db->mallocFailed ) {
  68030. clearSelect(db, pNew);
  68031. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  68032. pNew = 0;
  68033. }
  68034. return pNew;
  68035. }
  68036. /*
  68037. ** Delete the given Select structure and all of its substructures.
  68038. */
  68039. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  68040. if( p ){
  68041. clearSelect(db, p);
  68042. sqlite3DbFree(db, p);
  68043. }
  68044. }
  68045. /*
  68046. ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
  68047. ** type of join. Return an integer constant that expresses that type
  68048. ** in terms of the following bit values:
  68049. **
  68050. ** JT_INNER
  68051. ** JT_CROSS
  68052. ** JT_OUTER
  68053. ** JT_NATURAL
  68054. ** JT_LEFT
  68055. ** JT_RIGHT
  68056. **
  68057. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  68058. **
  68059. ** If an illegal or unsupported join type is seen, then still return
  68060. ** a join type, but put an error in the pParse structure.
  68061. */
  68062. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  68063. int jointype = 0;
  68064. Token *apAll[3];
  68065. Token *p;
  68066. static const struct {
  68067. const char zKeyword[8];
  68068. u8 nChar;
  68069. u8 code;
  68070. } keywords[] = {
  68071. { "natural", 7, JT_NATURAL },
  68072. { "left", 4, JT_LEFT|JT_OUTER },
  68073. { "right", 5, JT_RIGHT|JT_OUTER },
  68074. { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  68075. { "outer", 5, JT_OUTER },
  68076. { "inner", 5, JT_INNER },
  68077. { "cross", 5, JT_INNER|JT_CROSS },
  68078. };
  68079. int i, j;
  68080. apAll[0] = pA;
  68081. apAll[1] = pB;
  68082. apAll[2] = pC;
  68083. for(i=0; i<3 && apAll[i]; i++){
  68084. p = apAll[i];
  68085. for(j=0; j<ArraySize(keywords); j++){
  68086. if( p->n==keywords[j].nChar
  68087. && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
  68088. jointype |= keywords[j].code;
  68089. break;
  68090. }
  68091. }
  68092. if( j>=ArraySize(keywords) ){
  68093. jointype |= JT_ERROR;
  68094. break;
  68095. }
  68096. }
  68097. if(
  68098. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  68099. (jointype & JT_ERROR)!=0
  68100. ){
  68101. const char *zSp = " ";
  68102. assert( pB!=0 );
  68103. if( pC==0 ){ zSp++; }
  68104. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  68105. "%T %T%s%T", pA, pB, zSp, pC);
  68106. jointype = JT_INNER;
  68107. }else if( jointype & JT_RIGHT ){
  68108. sqlite3ErrorMsg(pParse,
  68109. "RIGHT and FULL OUTER JOINs are not currently supported");
  68110. jointype = JT_INNER;
  68111. }
  68112. return jointype;
  68113. }
  68114. /*
  68115. ** Return the index of a column in a table. Return -1 if the column
  68116. ** is not contained in the table.
  68117. */
  68118. static int columnIndex(Table *pTab, const char *zCol){
  68119. int i;
  68120. for(i=0; i<pTab->nCol; i++){
  68121. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  68122. }
  68123. return -1;
  68124. }
  68125. /*
  68126. ** Set the value of a token to a '\000'-terminated string.
  68127. */
  68128. static void setToken(Token *p, const char *z){
  68129. p->z = (u8*)z;
  68130. p->n = z ? sqlite3Strlen30(z) : 0;
  68131. p->dyn = 0;
  68132. }
  68133. /*
  68134. ** Set the token to the double-quoted and escaped version of the string pointed
  68135. ** to by z. For example;
  68136. **
  68137. ** {a"bc} -> {"a""bc"}
  68138. */
  68139. static void setQuotedToken(Parse *pParse, Token *p, const char *z){
  68140. /* Check if the string appears to be quoted using "..." or `...`
  68141. ** or [...] or '...' or if the string contains any " characters.
  68142. ** If it does, then record a version of the string with the special
  68143. ** characters escaped.
  68144. */
  68145. const char *z2 = z;
  68146. if( *z2!='[' && *z2!='`' && *z2!='\'' ){
  68147. while( *z2 ){
  68148. if( *z2=='"' ) break;
  68149. z2++;
  68150. }
  68151. }
  68152. if( *z2 ){
  68153. /* String contains " characters - copy and quote the string. */
  68154. p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
  68155. if( p->z ){
  68156. p->n = sqlite3Strlen30((char *)p->z);
  68157. p->dyn = 1;
  68158. }
  68159. }else{
  68160. /* String contains no " characters - copy the pointer. */
  68161. p->z = (u8*)z;
  68162. p->n = (int)(z2 - z);
  68163. p->dyn = 0;
  68164. }
  68165. }
  68166. /*
  68167. ** Create an expression node for an identifier with the name of zName
  68168. */
  68169. SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
  68170. Token dummy;
  68171. setToken(&dummy, zName);
  68172. return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
  68173. }
  68174. /*
  68175. ** Add a term to the WHERE expression in *ppExpr that requires the
  68176. ** zCol column to be equal in the two tables pTab1 and pTab2.
  68177. */
  68178. static void addWhereTerm(
  68179. Parse *pParse, /* Parsing context */
  68180. const char *zCol, /* Name of the column */
  68181. const Table *pTab1, /* First table */
  68182. const char *zAlias1, /* Alias for first table. May be NULL */
  68183. const Table *pTab2, /* Second table */
  68184. const char *zAlias2, /* Alias for second table. May be NULL */
  68185. int iRightJoinTable, /* VDBE cursor for the right table */
  68186. Expr **ppExpr, /* Add the equality term to this expression */
  68187. int isOuterJoin /* True if dealing with an OUTER join */
  68188. ){
  68189. Expr *pE1a, *pE1b, *pE1c;
  68190. Expr *pE2a, *pE2b, *pE2c;
  68191. Expr *pE;
  68192. pE1a = sqlite3CreateIdExpr(pParse, zCol);
  68193. pE2a = sqlite3CreateIdExpr(pParse, zCol);
  68194. if( zAlias1==0 ){
  68195. zAlias1 = pTab1->zName;
  68196. }
  68197. pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
  68198. if( zAlias2==0 ){
  68199. zAlias2 = pTab2->zName;
  68200. }
  68201. pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
  68202. pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
  68203. pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
  68204. pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
  68205. if( pE && isOuterJoin ){
  68206. ExprSetProperty(pE, EP_FromJoin);
  68207. pE->iRightJoinTable = iRightJoinTable;
  68208. }
  68209. *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
  68210. }
  68211. /*
  68212. ** Set the EP_FromJoin property on all terms of the given expression.
  68213. ** And set the Expr.iRightJoinTable to iTable for every term in the
  68214. ** expression.
  68215. **
  68216. ** The EP_FromJoin property is used on terms of an expression to tell
  68217. ** the LEFT OUTER JOIN processing logic that this term is part of the
  68218. ** join restriction specified in the ON or USING clause and not a part
  68219. ** of the more general WHERE clause. These terms are moved over to the
  68220. ** WHERE clause during join processing but we need to remember that they
  68221. ** originated in the ON or USING clause.
  68222. **
  68223. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  68224. ** expression depends on table iRightJoinTable even if that table is not
  68225. ** explicitly mentioned in the expression. That information is needed
  68226. ** for cases like this:
  68227. **
  68228. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  68229. **
  68230. ** The where clause needs to defer the handling of the t1.x=5
  68231. ** term until after the t2 loop of the join. In that way, a
  68232. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  68233. ** defer the handling of t1.x=5, it will be processed immediately
  68234. ** after the t1 loop and rows with t1.x!=5 will never appear in
  68235. ** the output, which is incorrect.
  68236. */
  68237. static void setJoinExpr(Expr *p, int iTable){
  68238. while( p ){
  68239. ExprSetProperty(p, EP_FromJoin);
  68240. p->iRightJoinTable = iTable;
  68241. setJoinExpr(p->pLeft, iTable);
  68242. p = p->pRight;
  68243. }
  68244. }
  68245. /*
  68246. ** This routine processes the join information for a SELECT statement.
  68247. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  68248. ** NATURAL joins also create extra WHERE clause terms.
  68249. **
  68250. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  68251. ** The left most table is the first entry in Select.pSrc. The right-most
  68252. ** table is the last entry. The join operator is held in the entry to
  68253. ** the left. Thus entry 0 contains the join operator for the join between
  68254. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  68255. ** also attached to the left entry.
  68256. **
  68257. ** This routine returns the number of errors encountered.
  68258. */
  68259. static int sqliteProcessJoin(Parse *pParse, Select *p){
  68260. SrcList *pSrc; /* All tables in the FROM clause */
  68261. int i, j; /* Loop counters */
  68262. struct SrcList_item *pLeft; /* Left table being joined */
  68263. struct SrcList_item *pRight; /* Right table being joined */
  68264. pSrc = p->pSrc;
  68265. pLeft = &pSrc->a[0];
  68266. pRight = &pLeft[1];
  68267. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  68268. Table *pLeftTab = pLeft->pTab;
  68269. Table *pRightTab = pRight->pTab;
  68270. int isOuter;
  68271. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  68272. isOuter = (pRight->jointype & JT_OUTER)!=0;
  68273. /* When the NATURAL keyword is present, add WHERE clause terms for
  68274. ** every column that the two tables have in common.
  68275. */
  68276. if( pRight->jointype & JT_NATURAL ){
  68277. if( pRight->pOn || pRight->pUsing ){
  68278. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  68279. "an ON or USING clause", 0);
  68280. return 1;
  68281. }
  68282. for(j=0; j<pLeftTab->nCol; j++){
  68283. char *zName = pLeftTab->aCol[j].zName;
  68284. if( columnIndex(pRightTab, zName)>=0 ){
  68285. addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
  68286. pRightTab, pRight->zAlias,
  68287. pRight->iCursor, &p->pWhere, isOuter);
  68288. }
  68289. }
  68290. }
  68291. /* Disallow both ON and USING clauses in the same join
  68292. */
  68293. if( pRight->pOn && pRight->pUsing ){
  68294. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  68295. "clauses in the same join");
  68296. return 1;
  68297. }
  68298. /* Add the ON clause to the end of the WHERE clause, connected by
  68299. ** an AND operator.
  68300. */
  68301. if( pRight->pOn ){
  68302. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  68303. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  68304. pRight->pOn = 0;
  68305. }
  68306. /* Create extra terms on the WHERE clause for each column named
  68307. ** in the USING clause. Example: If the two tables to be joined are
  68308. ** A and B and the USING clause names X, Y, and Z, then add this
  68309. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  68310. ** Report an error if any column mentioned in the USING clause is
  68311. ** not contained in both tables to be joined.
  68312. */
  68313. if( pRight->pUsing ){
  68314. IdList *pList = pRight->pUsing;
  68315. for(j=0; j<pList->nId; j++){
  68316. char *zName = pList->a[j].zName;
  68317. if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
  68318. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  68319. "not present in both tables", zName);
  68320. return 1;
  68321. }
  68322. addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
  68323. pRightTab, pRight->zAlias,
  68324. pRight->iCursor, &p->pWhere, isOuter);
  68325. }
  68326. }
  68327. }
  68328. return 0;
  68329. }
  68330. /*
  68331. ** Insert code into "v" that will push the record on the top of the
  68332. ** stack into the sorter.
  68333. */
  68334. static void pushOntoSorter(
  68335. Parse *pParse, /* Parser context */
  68336. ExprList *pOrderBy, /* The ORDER BY clause */
  68337. Select *pSelect, /* The whole SELECT statement */
  68338. int regData /* Register holding data to be sorted */
  68339. ){
  68340. Vdbe *v = pParse->pVdbe;
  68341. int nExpr = pOrderBy->nExpr;
  68342. int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  68343. int regRecord = sqlite3GetTempReg(pParse);
  68344. sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  68345. sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  68346. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  68347. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  68348. sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
  68349. sqlite3ReleaseTempReg(pParse, regRecord);
  68350. sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  68351. if( pSelect->iLimit ){
  68352. int addr1, addr2;
  68353. int iLimit;
  68354. if( pSelect->iOffset ){
  68355. iLimit = pSelect->iOffset+1;
  68356. }else{
  68357. iLimit = pSelect->iLimit;
  68358. }
  68359. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
  68360. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  68361. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  68362. sqlite3VdbeJumpHere(v, addr1);
  68363. sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
  68364. sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
  68365. sqlite3VdbeJumpHere(v, addr2);
  68366. pSelect->iLimit = 0;
  68367. }
  68368. }
  68369. /*
  68370. ** Add code to implement the OFFSET
  68371. */
  68372. static void codeOffset(
  68373. Vdbe *v, /* Generate code into this VM */
  68374. Select *p, /* The SELECT statement being coded */
  68375. int iContinue /* Jump here to skip the current record */
  68376. ){
  68377. if( p->iOffset && iContinue!=0 ){
  68378. int addr;
  68379. sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
  68380. addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
  68381. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  68382. VdbeComment((v, "skip OFFSET records"));
  68383. sqlite3VdbeJumpHere(v, addr);
  68384. }
  68385. }
  68386. /*
  68387. ** Add code that will check to make sure the N registers starting at iMem
  68388. ** form a distinct entry. iTab is a sorting index that holds previously
  68389. ** seen combinations of the N values. A new entry is made in iTab
  68390. ** if the current N values are new.
  68391. **
  68392. ** A jump to addrRepeat is made and the N+1 values are popped from the
  68393. ** stack if the top N elements are not distinct.
  68394. */
  68395. static void codeDistinct(
  68396. Parse *pParse, /* Parsing and code generating context */
  68397. int iTab, /* A sorting index used to test for distinctness */
  68398. int addrRepeat, /* Jump to here if not distinct */
  68399. int N, /* Number of elements */
  68400. int iMem /* First element */
  68401. ){
  68402. Vdbe *v;
  68403. int r1;
  68404. v = pParse->pVdbe;
  68405. r1 = sqlite3GetTempReg(pParse);
  68406. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  68407. sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
  68408. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  68409. sqlite3ReleaseTempReg(pParse, r1);
  68410. }
  68411. /*
  68412. ** Generate an error message when a SELECT is used within a subexpression
  68413. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  68414. ** column. We do this in a subroutine because the error occurs in multiple
  68415. ** places.
  68416. */
  68417. static int checkForMultiColumnSelectError(
  68418. Parse *pParse, /* Parse context. */
  68419. SelectDest *pDest, /* Destination of SELECT results */
  68420. int nExpr /* Number of result columns returned by SELECT */
  68421. ){
  68422. int eDest = pDest->eDest;
  68423. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  68424. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  68425. "a SELECT that is part of an expression");
  68426. return 1;
  68427. }else{
  68428. return 0;
  68429. }
  68430. }
  68431. /*
  68432. ** This routine generates the code for the inside of the inner loop
  68433. ** of a SELECT.
  68434. **
  68435. ** If srcTab and nColumn are both zero, then the pEList expressions
  68436. ** are evaluated in order to get the data for this row. If nColumn>0
  68437. ** then data is pulled from srcTab and pEList is used only to get the
  68438. ** datatypes for each column.
  68439. */
  68440. static void selectInnerLoop(
  68441. Parse *pParse, /* The parser context */
  68442. Select *p, /* The complete select statement being coded */
  68443. ExprList *pEList, /* List of values being extracted */
  68444. int srcTab, /* Pull data from this table */
  68445. int nColumn, /* Number of columns in the source table */
  68446. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  68447. int distinct, /* If >=0, make sure results are distinct */
  68448. SelectDest *pDest, /* How to dispose of the results */
  68449. int iContinue, /* Jump here to continue with next row */
  68450. int iBreak /* Jump here to break out of the inner loop */
  68451. ){
  68452. Vdbe *v = pParse->pVdbe;
  68453. int i;
  68454. int hasDistinct; /* True if the DISTINCT keyword is present */
  68455. int regResult; /* Start of memory holding result set */
  68456. int eDest = pDest->eDest; /* How to dispose of results */
  68457. int iParm = pDest->iParm; /* First argument to disposal method */
  68458. int nResultCol; /* Number of result columns */
  68459. assert( v );
  68460. if( NEVER(v==0) ) return;
  68461. assert( pEList!=0 );
  68462. hasDistinct = distinct>=0;
  68463. if( pOrderBy==0 && !hasDistinct ){
  68464. codeOffset(v, p, iContinue);
  68465. }
  68466. /* Pull the requested columns.
  68467. */
  68468. if( nColumn>0 ){
  68469. nResultCol = nColumn;
  68470. }else{
  68471. nResultCol = pEList->nExpr;
  68472. }
  68473. if( pDest->iMem==0 ){
  68474. pDest->iMem = pParse->nMem+1;
  68475. pDest->nMem = nResultCol;
  68476. pParse->nMem += nResultCol;
  68477. }else{
  68478. assert( pDest->nMem==nResultCol );
  68479. }
  68480. regResult = pDest->iMem;
  68481. if( nColumn>0 ){
  68482. for(i=0; i<nColumn; i++){
  68483. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  68484. }
  68485. }else if( eDest!=SRT_Exists ){
  68486. /* If the destination is an EXISTS(...) expression, the actual
  68487. ** values returned by the SELECT are not required.
  68488. */
  68489. sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  68490. }
  68491. nColumn = nResultCol;
  68492. /* If the DISTINCT keyword was present on the SELECT statement
  68493. ** and this row has been seen before, then do not make this row
  68494. ** part of the result.
  68495. */
  68496. if( hasDistinct ){
  68497. assert( pEList!=0 );
  68498. assert( pEList->nExpr==nColumn );
  68499. codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
  68500. if( pOrderBy==0 ){
  68501. codeOffset(v, p, iContinue);
  68502. }
  68503. }
  68504. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  68505. return;
  68506. }
  68507. switch( eDest ){
  68508. /* In this mode, write each query result to the key of the temporary
  68509. ** table iParm.
  68510. */
  68511. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  68512. case SRT_Union: {
  68513. int r1;
  68514. r1 = sqlite3GetTempReg(pParse);
  68515. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  68516. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  68517. sqlite3ReleaseTempReg(pParse, r1);
  68518. break;
  68519. }
  68520. /* Construct a record from the query result, but instead of
  68521. ** saving that record, use it as a key to delete elements from
  68522. ** the temporary table iParm.
  68523. */
  68524. case SRT_Except: {
  68525. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
  68526. break;
  68527. }
  68528. #endif
  68529. /* Store the result as data using a unique key.
  68530. */
  68531. case SRT_Table:
  68532. case SRT_EphemTab: {
  68533. int r1 = sqlite3GetTempReg(pParse);
  68534. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  68535. if( pOrderBy ){
  68536. pushOntoSorter(pParse, pOrderBy, p, r1);
  68537. }else{
  68538. int r2 = sqlite3GetTempReg(pParse);
  68539. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  68540. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  68541. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  68542. sqlite3ReleaseTempReg(pParse, r2);
  68543. }
  68544. sqlite3ReleaseTempReg(pParse, r1);
  68545. break;
  68546. }
  68547. #ifndef SQLITE_OMIT_SUBQUERY
  68548. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  68549. ** then there should be a single item on the stack. Write this
  68550. ** item into the set table with bogus data.
  68551. */
  68552. case SRT_Set: {
  68553. assert( nColumn==1 );
  68554. p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
  68555. if( pOrderBy ){
  68556. /* At first glance you would think we could optimize out the
  68557. ** ORDER BY in this case since the order of entries in the set
  68558. ** does not matter. But there might be a LIMIT clause, in which
  68559. ** case the order does matter */
  68560. pushOntoSorter(pParse, pOrderBy, p, regResult);
  68561. }else{
  68562. int r1 = sqlite3GetTempReg(pParse);
  68563. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
  68564. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  68565. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  68566. sqlite3ReleaseTempReg(pParse, r1);
  68567. }
  68568. break;
  68569. }
  68570. /* If any row exist in the result set, record that fact and abort.
  68571. */
  68572. case SRT_Exists: {
  68573. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  68574. /* The LIMIT clause will terminate the loop for us */
  68575. break;
  68576. }
  68577. /* If this is a scalar select that is part of an expression, then
  68578. ** store the results in the appropriate memory cell and break out
  68579. ** of the scan loop.
  68580. */
  68581. case SRT_Mem: {
  68582. assert( nColumn==1 );
  68583. if( pOrderBy ){
  68584. pushOntoSorter(pParse, pOrderBy, p, regResult);
  68585. }else{
  68586. sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
  68587. /* The LIMIT clause will jump out of the loop for us */
  68588. }
  68589. break;
  68590. }
  68591. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  68592. /* Send the data to the callback function or to a subroutine. In the
  68593. ** case of a subroutine, the subroutine itself is responsible for
  68594. ** popping the data from the stack.
  68595. */
  68596. case SRT_Coroutine:
  68597. case SRT_Output: {
  68598. if( pOrderBy ){
  68599. int r1 = sqlite3GetTempReg(pParse);
  68600. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  68601. pushOntoSorter(pParse, pOrderBy, p, r1);
  68602. sqlite3ReleaseTempReg(pParse, r1);
  68603. }else if( eDest==SRT_Coroutine ){
  68604. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
  68605. }else{
  68606. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
  68607. sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
  68608. }
  68609. break;
  68610. }
  68611. #if !defined(SQLITE_OMIT_TRIGGER)
  68612. /* Discard the results. This is used for SELECT statements inside
  68613. ** the body of a TRIGGER. The purpose of such selects is to call
  68614. ** user-defined functions that have side effects. We do not care
  68615. ** about the actual results of the select.
  68616. */
  68617. default: {
  68618. assert( eDest==SRT_Discard );
  68619. break;
  68620. }
  68621. #endif
  68622. }
  68623. /* Jump to the end of the loop if the LIMIT is reached.
  68624. */
  68625. if( p->iLimit ){
  68626. assert( pOrderBy==0 ); /* If there is an ORDER BY, the call to
  68627. ** pushOntoSorter() would have cleared p->iLimit */
  68628. sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
  68629. sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
  68630. }
  68631. }
  68632. /*
  68633. ** Given an expression list, generate a KeyInfo structure that records
  68634. ** the collating sequence for each expression in that expression list.
  68635. **
  68636. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  68637. ** KeyInfo structure is appropriate for initializing a virtual index to
  68638. ** implement that clause. If the ExprList is the result set of a SELECT
  68639. ** then the KeyInfo structure is appropriate for initializing a virtual
  68640. ** index to implement a DISTINCT test.
  68641. **
  68642. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  68643. ** function is responsible for seeing that this structure is eventually
  68644. ** freed. Add the KeyInfo structure to the P4 field of an opcode using
  68645. ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
  68646. */
  68647. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  68648. sqlite3 *db = pParse->db;
  68649. int nExpr;
  68650. KeyInfo *pInfo;
  68651. struct ExprList_item *pItem;
  68652. int i;
  68653. nExpr = pList->nExpr;
  68654. pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
  68655. if( pInfo ){
  68656. pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
  68657. pInfo->nField = (u16)nExpr;
  68658. pInfo->enc = ENC(db);
  68659. pInfo->db = db;
  68660. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  68661. CollSeq *pColl;
  68662. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  68663. if( !pColl ){
  68664. pColl = db->pDfltColl;
  68665. }
  68666. pInfo->aColl[i] = pColl;
  68667. pInfo->aSortOrder[i] = pItem->sortOrder;
  68668. }
  68669. }
  68670. return pInfo;
  68671. }
  68672. /*
  68673. ** If the inner loop was generated using a non-null pOrderBy argument,
  68674. ** then the results were placed in a sorter. After the loop is terminated
  68675. ** we need to run the sorter and output the results. The following
  68676. ** routine generates the code needed to do that.
  68677. */
  68678. static void generateSortTail(
  68679. Parse *pParse, /* Parsing context */
  68680. Select *p, /* The SELECT statement */
  68681. Vdbe *v, /* Generate code into this VDBE */
  68682. int nColumn, /* Number of columns of data */
  68683. SelectDest *pDest /* Write the sorted results here */
  68684. ){
  68685. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  68686. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  68687. int addr;
  68688. int iTab;
  68689. int pseudoTab = 0;
  68690. ExprList *pOrderBy = p->pOrderBy;
  68691. int eDest = pDest->eDest;
  68692. int iParm = pDest->iParm;
  68693. int regRow;
  68694. int regRowid;
  68695. iTab = pOrderBy->iECursor;
  68696. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  68697. pseudoTab = pParse->nTab++;
  68698. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
  68699. sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Output);
  68700. }
  68701. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  68702. codeOffset(v, p, addrContinue);
  68703. regRow = sqlite3GetTempReg(pParse);
  68704. regRowid = sqlite3GetTempReg(pParse);
  68705. sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
  68706. switch( eDest ){
  68707. case SRT_Table:
  68708. case SRT_EphemTab: {
  68709. testcase( eDest==SRT_Table );
  68710. testcase( eDest==SRT_EphemTab );
  68711. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  68712. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  68713. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  68714. break;
  68715. }
  68716. #ifndef SQLITE_OMIT_SUBQUERY
  68717. case SRT_Set: {
  68718. assert( nColumn==1 );
  68719. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
  68720. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  68721. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  68722. break;
  68723. }
  68724. case SRT_Mem: {
  68725. assert( nColumn==1 );
  68726. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  68727. /* The LIMIT clause will terminate the loop for us */
  68728. break;
  68729. }
  68730. #endif
  68731. case SRT_Output:
  68732. case SRT_Coroutine: {
  68733. int i;
  68734. testcase( eDest==SRT_Output );
  68735. testcase( eDest==SRT_Coroutine );
  68736. sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
  68737. sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
  68738. for(i=0; i<nColumn; i++){
  68739. assert( regRow!=pDest->iMem+i );
  68740. sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
  68741. }
  68742. if( eDest==SRT_Output ){
  68743. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
  68744. sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
  68745. }else{
  68746. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
  68747. }
  68748. break;
  68749. }
  68750. default: {
  68751. /* Do nothing */
  68752. break;
  68753. }
  68754. }
  68755. sqlite3ReleaseTempReg(pParse, regRow);
  68756. sqlite3ReleaseTempReg(pParse, regRowid);
  68757. /* LIMIT has been implemented by the pushOntoSorter() routine.
  68758. */
  68759. assert( p->iLimit==0 );
  68760. /* The bottom of the loop
  68761. */
  68762. sqlite3VdbeResolveLabel(v, addrContinue);
  68763. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  68764. sqlite3VdbeResolveLabel(v, addrBreak);
  68765. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  68766. sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  68767. }
  68768. }
  68769. /*
  68770. ** Return a pointer to a string containing the 'declaration type' of the
  68771. ** expression pExpr. The string may be treated as static by the caller.
  68772. **
  68773. ** The declaration type is the exact datatype definition extracted from the
  68774. ** original CREATE TABLE statement if the expression is a column. The
  68775. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  68776. ** is considered a column can be complex in the presence of subqueries. The
  68777. ** result-set expression in all of the following SELECT statements is
  68778. ** considered a column by this function.
  68779. **
  68780. ** SELECT col FROM tbl;
  68781. ** SELECT (SELECT col FROM tbl;
  68782. ** SELECT (SELECT col FROM tbl);
  68783. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  68784. **
  68785. ** The declaration type for any expression other than a column is NULL.
  68786. */
  68787. static const char *columnType(
  68788. NameContext *pNC,
  68789. Expr *pExpr,
  68790. const char **pzOriginDb,
  68791. const char **pzOriginTab,
  68792. const char **pzOriginCol
  68793. ){
  68794. char const *zType = 0;
  68795. char const *zOriginDb = 0;
  68796. char const *zOriginTab = 0;
  68797. char const *zOriginCol = 0;
  68798. int j;
  68799. if( pExpr==0 || pNC->pSrcList==0 ) return 0;
  68800. switch( pExpr->op ){
  68801. case TK_AGG_COLUMN:
  68802. case TK_COLUMN: {
  68803. /* The expression is a column. Locate the table the column is being
  68804. ** extracted from in NameContext.pSrcList. This table may be real
  68805. ** database table or a subquery.
  68806. */
  68807. Table *pTab = 0; /* Table structure column is extracted from */
  68808. Select *pS = 0; /* Select the column is extracted from */
  68809. int iCol = pExpr->iColumn; /* Index of column in pTab */
  68810. while( pNC && !pTab ){
  68811. SrcList *pTabList = pNC->pSrcList;
  68812. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  68813. if( j<pTabList->nSrc ){
  68814. pTab = pTabList->a[j].pTab;
  68815. pS = pTabList->a[j].pSelect;
  68816. }else{
  68817. pNC = pNC->pNext;
  68818. }
  68819. }
  68820. if( pTab==0 ){
  68821. /* FIX ME:
  68822. ** This can occurs if you have something like "SELECT new.x;" inside
  68823. ** a trigger. In other words, if you reference the special "new"
  68824. ** table in the result set of a select. We do not have a good way
  68825. ** to find the actual table type, so call it "TEXT". This is really
  68826. ** something of a bug, but I do not know how to fix it.
  68827. **
  68828. ** This code does not produce the correct answer - it just prevents
  68829. ** a segfault. See ticket #1229.
  68830. */
  68831. zType = "TEXT";
  68832. break;
  68833. }
  68834. assert( pTab );
  68835. if( pS ){
  68836. /* The "table" is actually a sub-select or a view in the FROM clause
  68837. ** of the SELECT statement. Return the declaration type and origin
  68838. ** data for the result-set column of the sub-select.
  68839. */
  68840. if( ALWAYS(iCol>=0 && iCol<pS->pEList->nExpr) ){
  68841. /* If iCol is less than zero, then the expression requests the
  68842. ** rowid of the sub-select or view. This expression is legal (see
  68843. ** test case misc2.2.2) - it always evaluates to NULL.
  68844. */
  68845. NameContext sNC;
  68846. Expr *p = pS->pEList->a[iCol].pExpr;
  68847. sNC.pSrcList = pS->pSrc;
  68848. sNC.pNext = 0;
  68849. sNC.pParse = pNC->pParse;
  68850. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  68851. }
  68852. }else if( ALWAYS(pTab->pSchema) ){
  68853. /* A real table */
  68854. assert( !pS );
  68855. if( iCol<0 ) iCol = pTab->iPKey;
  68856. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  68857. if( iCol<0 ){
  68858. zType = "INTEGER";
  68859. zOriginCol = "rowid";
  68860. }else{
  68861. zType = pTab->aCol[iCol].zType;
  68862. zOriginCol = pTab->aCol[iCol].zName;
  68863. }
  68864. zOriginTab = pTab->zName;
  68865. if( pNC->pParse ){
  68866. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  68867. zOriginDb = pNC->pParse->db->aDb[iDb].zName;
  68868. }
  68869. }
  68870. break;
  68871. }
  68872. #ifndef SQLITE_OMIT_SUBQUERY
  68873. case TK_SELECT: {
  68874. /* The expression is a sub-select. Return the declaration type and
  68875. ** origin info for the single column in the result set of the SELECT
  68876. ** statement.
  68877. */
  68878. NameContext sNC;
  68879. Select *pS = pExpr->pSelect;
  68880. Expr *p = pS->pEList->a[0].pExpr;
  68881. sNC.pSrcList = pS->pSrc;
  68882. sNC.pNext = pNC;
  68883. sNC.pParse = pNC->pParse;
  68884. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  68885. break;
  68886. }
  68887. #endif
  68888. }
  68889. if( pzOriginDb ){
  68890. assert( pzOriginTab && pzOriginCol );
  68891. *pzOriginDb = zOriginDb;
  68892. *pzOriginTab = zOriginTab;
  68893. *pzOriginCol = zOriginCol;
  68894. }
  68895. return zType;
  68896. }
  68897. /*
  68898. ** Generate code that will tell the VDBE the declaration types of columns
  68899. ** in the result set.
  68900. */
  68901. static void generateColumnTypes(
  68902. Parse *pParse, /* Parser context */
  68903. SrcList *pTabList, /* List of tables */
  68904. ExprList *pEList /* Expressions defining the result set */
  68905. ){
  68906. #ifndef SQLITE_OMIT_DECLTYPE
  68907. Vdbe *v = pParse->pVdbe;
  68908. int i;
  68909. NameContext sNC;
  68910. sNC.pSrcList = pTabList;
  68911. sNC.pParse = pParse;
  68912. for(i=0; i<pEList->nExpr; i++){
  68913. Expr *p = pEList->a[i].pExpr;
  68914. const char *zType;
  68915. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  68916. const char *zOrigDb = 0;
  68917. const char *zOrigTab = 0;
  68918. const char *zOrigCol = 0;
  68919. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  68920. /* The vdbe must make its own copy of the column-type and other
  68921. ** column specific strings, in case the schema is reset before this
  68922. ** virtual machine is deleted.
  68923. */
  68924. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  68925. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  68926. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  68927. #else
  68928. zType = columnType(&sNC, p, 0, 0, 0);
  68929. #endif
  68930. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  68931. }
  68932. #endif /* SQLITE_OMIT_DECLTYPE */
  68933. }
  68934. /*
  68935. ** Generate code that will tell the VDBE the names of columns
  68936. ** in the result set. This information is used to provide the
  68937. ** azCol[] values in the callback.
  68938. */
  68939. static void generateColumnNames(
  68940. Parse *pParse, /* Parser context */
  68941. SrcList *pTabList, /* List of tables */
  68942. ExprList *pEList /* Expressions defining the result set */
  68943. ){
  68944. Vdbe *v = pParse->pVdbe;
  68945. int i, j;
  68946. sqlite3 *db = pParse->db;
  68947. int fullNames, shortNames;
  68948. #ifndef SQLITE_OMIT_EXPLAIN
  68949. /* If this is an EXPLAIN, skip this step */
  68950. if( pParse->explain ){
  68951. return;
  68952. }
  68953. #endif
  68954. assert( v!=0 );
  68955. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  68956. pParse->colNamesSet = 1;
  68957. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  68958. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  68959. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  68960. for(i=0; i<pEList->nExpr; i++){
  68961. Expr *p;
  68962. p = pEList->a[i].pExpr;
  68963. if( p==0 ) continue;
  68964. if( pEList->a[i].zName ){
  68965. char *zName = pEList->a[i].zName;
  68966. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  68967. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  68968. Table *pTab;
  68969. char *zCol;
  68970. int iCol = p->iColumn;
  68971. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  68972. if( pTabList->a[j].iCursor==p->iTable ) break;
  68973. }
  68974. assert( j<pTabList->nSrc );
  68975. pTab = pTabList->a[j].pTab;
  68976. if( iCol<0 ) iCol = pTab->iPKey;
  68977. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  68978. if( iCol<0 ){
  68979. zCol = "rowid";
  68980. }else{
  68981. zCol = pTab->aCol[iCol].zName;
  68982. }
  68983. if( !shortNames && !fullNames ){
  68984. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  68985. sqlite3DbStrNDup(db, (char*)p->span.z, p->span.n), SQLITE_DYNAMIC);
  68986. }else if( fullNames ){
  68987. char *zName = 0;
  68988. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  68989. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  68990. }else{
  68991. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  68992. }
  68993. }else{
  68994. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  68995. sqlite3DbStrNDup(db, (char*)p->span.z, p->span.n), SQLITE_DYNAMIC);
  68996. }
  68997. }
  68998. generateColumnTypes(pParse, pTabList, pEList);
  68999. }
  69000. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  69001. /*
  69002. ** Name of the connection operator, used for error messages.
  69003. */
  69004. static const char *selectOpName(int id){
  69005. char *z;
  69006. switch( id ){
  69007. case TK_ALL: z = "UNION ALL"; break;
  69008. case TK_INTERSECT: z = "INTERSECT"; break;
  69009. case TK_EXCEPT: z = "EXCEPT"; break;
  69010. default: z = "UNION"; break;
  69011. }
  69012. return z;
  69013. }
  69014. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  69015. /*
  69016. ** Given a an expression list (which is really the list of expressions
  69017. ** that form the result set of a SELECT statement) compute appropriate
  69018. ** column names for a table that would hold the expression list.
  69019. **
  69020. ** All column names will be unique.
  69021. **
  69022. ** Only the column names are computed. Column.zType, Column.zColl,
  69023. ** and other fields of Column are zeroed.
  69024. **
  69025. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  69026. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  69027. */
  69028. static int selectColumnsFromExprList(
  69029. Parse *pParse, /* Parsing context */
  69030. ExprList *pEList, /* Expr list from which to derive column names */
  69031. int *pnCol, /* Write the number of columns here */
  69032. Column **paCol /* Write the new column list here */
  69033. ){
  69034. sqlite3 *db = pParse->db; /* Database connection */
  69035. int i, j; /* Loop counters */
  69036. int cnt; /* Index added to make the name unique */
  69037. Column *aCol, *pCol; /* For looping over result columns */
  69038. int nCol; /* Number of columns in the result set */
  69039. Expr *p; /* Expression for a single result column */
  69040. char *zName; /* Column name */
  69041. int nName; /* Size of name in zName[] */
  69042. *pnCol = nCol = pEList->nExpr;
  69043. aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  69044. if( aCol==0 ) return SQLITE_NOMEM;
  69045. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  69046. /* Get an appropriate name for the column
  69047. */
  69048. p = pEList->a[i].pExpr;
  69049. assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
  69050. if( (zName = pEList->a[i].zName)!=0 ){
  69051. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  69052. zName = sqlite3DbStrDup(db, zName);
  69053. }else{
  69054. Expr *pColExpr = p; /* The expression that is the result column name */
  69055. Table *pTab; /* Table associated with this expression */
  69056. while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
  69057. if( pColExpr->op==TK_COLUMN && (pTab = pColExpr->pTab)!=0 ){
  69058. /* For columns use the column name name */
  69059. int iCol = pColExpr->iColumn;
  69060. if( iCol<0 ) iCol = pTab->iPKey;
  69061. zName = sqlite3MPrintf(db, "%s",
  69062. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  69063. }else{
  69064. /* Use the original text of the column expression as its name */
  69065. Token *pToken = (pColExpr->span.z?&pColExpr->span:&pColExpr->token);
  69066. zName = sqlite3MPrintf(db, "%T", pToken);
  69067. }
  69068. }
  69069. if( db->mallocFailed ){
  69070. sqlite3DbFree(db, zName);
  69071. break;
  69072. }
  69073. sqlite3Dequote(zName);
  69074. /* Make sure the column name is unique. If the name is not unique,
  69075. ** append a integer to the name so that it becomes unique.
  69076. */
  69077. nName = sqlite3Strlen30(zName);
  69078. for(j=cnt=0; j<i; j++){
  69079. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  69080. char *zNewName;
  69081. zName[nName] = 0;
  69082. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  69083. sqlite3DbFree(db, zName);
  69084. zName = zNewName;
  69085. j = -1;
  69086. if( zName==0 ) break;
  69087. }
  69088. }
  69089. pCol->zName = zName;
  69090. }
  69091. if( db->mallocFailed ){
  69092. for(j=0; j<i; j++){
  69093. sqlite3DbFree(db, aCol[j].zName);
  69094. }
  69095. sqlite3DbFree(db, aCol);
  69096. *paCol = 0;
  69097. *pnCol = 0;
  69098. return SQLITE_NOMEM;
  69099. }
  69100. return SQLITE_OK;
  69101. }
  69102. /*
  69103. ** Add type and collation information to a column list based on
  69104. ** a SELECT statement.
  69105. **
  69106. ** The column list presumably came from selectColumnNamesFromExprList().
  69107. ** The column list has only names, not types or collations. This
  69108. ** routine goes through and adds the types and collations.
  69109. **
  69110. ** This routine requires that all indentifiers in the SELECT
  69111. ** statement be resolved.
  69112. */
  69113. static void selectAddColumnTypeAndCollation(
  69114. Parse *pParse, /* Parsing contexts */
  69115. int nCol, /* Number of columns */
  69116. Column *aCol, /* List of columns */
  69117. Select *pSelect /* SELECT used to determine types and collations */
  69118. ){
  69119. sqlite3 *db = pParse->db;
  69120. NameContext sNC;
  69121. Column *pCol;
  69122. CollSeq *pColl;
  69123. int i;
  69124. Expr *p;
  69125. struct ExprList_item *a;
  69126. assert( pSelect!=0 );
  69127. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  69128. assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
  69129. if( db->mallocFailed ) return;
  69130. memset(&sNC, 0, sizeof(sNC));
  69131. sNC.pSrcList = pSelect->pSrc;
  69132. a = pSelect->pEList->a;
  69133. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  69134. p = a[i].pExpr;
  69135. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
  69136. pCol->affinity = sqlite3ExprAffinity(p);
  69137. pColl = sqlite3ExprCollSeq(pParse, p);
  69138. if( pColl ){
  69139. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  69140. }
  69141. }
  69142. }
  69143. /*
  69144. ** Given a SELECT statement, generate a Table structure that describes
  69145. ** the result set of that SELECT.
  69146. */
  69147. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  69148. Table *pTab;
  69149. sqlite3 *db = pParse->db;
  69150. int savedFlags;
  69151. savedFlags = db->flags;
  69152. db->flags &= ~SQLITE_FullColNames;
  69153. db->flags |= SQLITE_ShortColNames;
  69154. sqlite3SelectPrep(pParse, pSelect, 0);
  69155. if( pParse->nErr ) return 0;
  69156. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  69157. db->flags = savedFlags;
  69158. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  69159. if( pTab==0 ){
  69160. return 0;
  69161. }
  69162. pTab->db = db;
  69163. pTab->nRef = 1;
  69164. pTab->zName = 0;
  69165. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  69166. selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
  69167. pTab->iPKey = -1;
  69168. if( db->mallocFailed ){
  69169. sqlite3DeleteTable(pTab);
  69170. return 0;
  69171. }
  69172. return pTab;
  69173. }
  69174. /*
  69175. ** Get a VDBE for the given parser context. Create a new one if necessary.
  69176. ** If an error occurs, return NULL and leave a message in pParse.
  69177. */
  69178. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  69179. Vdbe *v = pParse->pVdbe;
  69180. if( v==0 ){
  69181. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  69182. #ifndef SQLITE_OMIT_TRACE
  69183. if( v ){
  69184. sqlite3VdbeAddOp0(v, OP_Trace);
  69185. }
  69186. #endif
  69187. }
  69188. return v;
  69189. }
  69190. /*
  69191. ** Compute the iLimit and iOffset fields of the SELECT based on the
  69192. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  69193. ** that appear in the original SQL statement after the LIMIT and OFFSET
  69194. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  69195. ** are the integer memory register numbers for counters used to compute
  69196. ** the limit and offset. If there is no limit and/or offset, then
  69197. ** iLimit and iOffset are negative.
  69198. **
  69199. ** This routine changes the values of iLimit and iOffset only if
  69200. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  69201. ** iOffset should have been preset to appropriate default values
  69202. ** (usually but not always -1) prior to calling this routine.
  69203. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  69204. ** redefined. The UNION ALL operator uses this property to force
  69205. ** the reuse of the same limit and offset registers across multiple
  69206. ** SELECT statements.
  69207. */
  69208. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  69209. Vdbe *v = 0;
  69210. int iLimit = 0;
  69211. int iOffset;
  69212. int addr1;
  69213. if( p->iLimit ) return;
  69214. /*
  69215. ** "LIMIT -1" always shows all rows. There is some
  69216. ** contraversy about what the correct behavior should be.
  69217. ** The current implementation interprets "LIMIT 0" to mean
  69218. ** no rows.
  69219. */
  69220. if( p->pLimit ){
  69221. p->iLimit = iLimit = ++pParse->nMem;
  69222. v = sqlite3GetVdbe(pParse);
  69223. if( v==0 ) return;
  69224. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  69225. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  69226. VdbeComment((v, "LIMIT counter"));
  69227. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  69228. }
  69229. if( p->pOffset ){
  69230. p->iOffset = iOffset = ++pParse->nMem;
  69231. if( p->pLimit ){
  69232. pParse->nMem++; /* Allocate an extra register for limit+offset */
  69233. }
  69234. v = sqlite3GetVdbe(pParse);
  69235. if( v==0 ) return;
  69236. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  69237. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  69238. VdbeComment((v, "OFFSET counter"));
  69239. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  69240. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  69241. sqlite3VdbeJumpHere(v, addr1);
  69242. if( p->pLimit ){
  69243. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  69244. VdbeComment((v, "LIMIT+OFFSET"));
  69245. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  69246. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  69247. sqlite3VdbeJumpHere(v, addr1);
  69248. }
  69249. }
  69250. }
  69251. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  69252. /*
  69253. ** Return the appropriate collating sequence for the iCol-th column of
  69254. ** the result set for the compound-select statement "p". Return NULL if
  69255. ** the column has no default collating sequence.
  69256. **
  69257. ** The collating sequence for the compound select is taken from the
  69258. ** left-most term of the select that has a collating sequence.
  69259. */
  69260. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  69261. CollSeq *pRet;
  69262. if( p->pPrior ){
  69263. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  69264. }else{
  69265. pRet = 0;
  69266. }
  69267. if( pRet==0 ){
  69268. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  69269. }
  69270. return pRet;
  69271. }
  69272. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  69273. /* Forward reference */
  69274. static int multiSelectOrderBy(
  69275. Parse *pParse, /* Parsing context */
  69276. Select *p, /* The right-most of SELECTs to be coded */
  69277. SelectDest *pDest /* What to do with query results */
  69278. );
  69279. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  69280. /*
  69281. ** This routine is called to process a compound query form from
  69282. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  69283. ** INTERSECT
  69284. **
  69285. ** "p" points to the right-most of the two queries. the query on the
  69286. ** left is p->pPrior. The left query could also be a compound query
  69287. ** in which case this routine will be called recursively.
  69288. **
  69289. ** The results of the total query are to be written into a destination
  69290. ** of type eDest with parameter iParm.
  69291. **
  69292. ** Example 1: Consider a three-way compound SQL statement.
  69293. **
  69294. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  69295. **
  69296. ** This statement is parsed up as follows:
  69297. **
  69298. ** SELECT c FROM t3
  69299. ** |
  69300. ** `-----> SELECT b FROM t2
  69301. ** |
  69302. ** `------> SELECT a FROM t1
  69303. **
  69304. ** The arrows in the diagram above represent the Select.pPrior pointer.
  69305. ** So if this routine is called with p equal to the t3 query, then
  69306. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  69307. **
  69308. ** Notice that because of the way SQLite parses compound SELECTs, the
  69309. ** individual selects always group from left to right.
  69310. */
  69311. static int multiSelect(
  69312. Parse *pParse, /* Parsing context */
  69313. Select *p, /* The right-most of SELECTs to be coded */
  69314. SelectDest *pDest /* What to do with query results */
  69315. ){
  69316. int rc = SQLITE_OK; /* Success code from a subroutine */
  69317. Select *pPrior; /* Another SELECT immediately to our left */
  69318. Vdbe *v; /* Generate code to this VDBE */
  69319. SelectDest dest; /* Alternative data destination */
  69320. Select *pDelete = 0; /* Chain of simple selects to delete */
  69321. sqlite3 *db; /* Database connection */
  69322. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  69323. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  69324. */
  69325. assert( p && p->pPrior ); /* Calling function guarantees this much */
  69326. db = pParse->db;
  69327. pPrior = p->pPrior;
  69328. assert( pPrior->pRightmost!=pPrior );
  69329. assert( pPrior->pRightmost==p->pRightmost );
  69330. dest = *pDest;
  69331. if( pPrior->pOrderBy ){
  69332. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  69333. selectOpName(p->op));
  69334. rc = 1;
  69335. goto multi_select_end;
  69336. }
  69337. if( pPrior->pLimit ){
  69338. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  69339. selectOpName(p->op));
  69340. rc = 1;
  69341. goto multi_select_end;
  69342. }
  69343. v = sqlite3GetVdbe(pParse);
  69344. assert( v!=0 ); /* The VDBE already created by calling function */
  69345. /* Create the destination temporary table if necessary
  69346. */
  69347. if( dest.eDest==SRT_EphemTab ){
  69348. assert( p->pEList );
  69349. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
  69350. dest.eDest = SRT_Table;
  69351. }
  69352. /* Make sure all SELECTs in the statement have the same number of elements
  69353. ** in their result sets.
  69354. */
  69355. assert( p->pEList && pPrior->pEList );
  69356. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  69357. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  69358. " do not have the same number of result columns", selectOpName(p->op));
  69359. rc = 1;
  69360. goto multi_select_end;
  69361. }
  69362. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  69363. */
  69364. if( p->pOrderBy ){
  69365. return multiSelectOrderBy(pParse, p, pDest);
  69366. }
  69367. /* Generate code for the left and right SELECT statements.
  69368. */
  69369. switch( p->op ){
  69370. case TK_ALL: {
  69371. int addr = 0;
  69372. assert( !pPrior->pLimit );
  69373. pPrior->pLimit = p->pLimit;
  69374. pPrior->pOffset = p->pOffset;
  69375. rc = sqlite3Select(pParse, pPrior, &dest);
  69376. p->pLimit = 0;
  69377. p->pOffset = 0;
  69378. if( rc ){
  69379. goto multi_select_end;
  69380. }
  69381. p->pPrior = 0;
  69382. p->iLimit = pPrior->iLimit;
  69383. p->iOffset = pPrior->iOffset;
  69384. if( p->iLimit ){
  69385. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  69386. VdbeComment((v, "Jump ahead if LIMIT reached"));
  69387. }
  69388. rc = sqlite3Select(pParse, p, &dest);
  69389. pDelete = p->pPrior;
  69390. p->pPrior = pPrior;
  69391. if( rc ){
  69392. goto multi_select_end;
  69393. }
  69394. if( addr ){
  69395. sqlite3VdbeJumpHere(v, addr);
  69396. }
  69397. break;
  69398. }
  69399. case TK_EXCEPT:
  69400. case TK_UNION: {
  69401. int unionTab; /* Cursor number of the temporary table holding result */
  69402. u8 op = 0; /* One of the SRT_ operations to apply to self */
  69403. int priorOp; /* The SRT_ operation to apply to prior selects */
  69404. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  69405. int addr;
  69406. SelectDest uniondest;
  69407. priorOp = SRT_Union;
  69408. if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
  69409. /* We can reuse a temporary table generated by a SELECT to our
  69410. ** right.
  69411. */
  69412. assert( p->pRightmost!=p ); /* Can only happen for leftward elements
  69413. ** of a 3-way or more compound */
  69414. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  69415. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  69416. unionTab = dest.iParm;
  69417. }else{
  69418. /* We will need to create our own temporary table to hold the
  69419. ** intermediate results.
  69420. */
  69421. unionTab = pParse->nTab++;
  69422. assert( p->pOrderBy==0 );
  69423. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  69424. assert( p->addrOpenEphm[0] == -1 );
  69425. p->addrOpenEphm[0] = addr;
  69426. p->pRightmost->selFlags |= SF_UsesEphemeral;
  69427. assert( p->pEList );
  69428. }
  69429. /* Code the SELECT statements to our left
  69430. */
  69431. assert( !pPrior->pOrderBy );
  69432. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  69433. rc = sqlite3Select(pParse, pPrior, &uniondest);
  69434. if( rc ){
  69435. goto multi_select_end;
  69436. }
  69437. /* Code the current SELECT statement
  69438. */
  69439. if( p->op==TK_EXCEPT ){
  69440. op = SRT_Except;
  69441. }else{
  69442. assert( p->op==TK_UNION );
  69443. op = SRT_Union;
  69444. }
  69445. p->pPrior = 0;
  69446. pLimit = p->pLimit;
  69447. p->pLimit = 0;
  69448. pOffset = p->pOffset;
  69449. p->pOffset = 0;
  69450. uniondest.eDest = op;
  69451. rc = sqlite3Select(pParse, p, &uniondest);
  69452. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  69453. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  69454. sqlite3ExprListDelete(db, p->pOrderBy);
  69455. pDelete = p->pPrior;
  69456. p->pPrior = pPrior;
  69457. p->pOrderBy = 0;
  69458. sqlite3ExprDelete(db, p->pLimit);
  69459. p->pLimit = pLimit;
  69460. p->pOffset = pOffset;
  69461. p->iLimit = 0;
  69462. p->iOffset = 0;
  69463. if( rc ){
  69464. goto multi_select_end;
  69465. }
  69466. /* Convert the data in the temporary table into whatever form
  69467. ** it is that we currently need.
  69468. */
  69469. if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
  69470. int iCont, iBreak, iStart;
  69471. assert( p->pEList );
  69472. if( dest.eDest==SRT_Output ){
  69473. Select *pFirst = p;
  69474. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  69475. generateColumnNames(pParse, 0, pFirst->pEList);
  69476. }
  69477. iBreak = sqlite3VdbeMakeLabel(v);
  69478. iCont = sqlite3VdbeMakeLabel(v);
  69479. computeLimitRegisters(pParse, p, iBreak);
  69480. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  69481. iStart = sqlite3VdbeCurrentAddr(v);
  69482. selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  69483. 0, -1, &dest, iCont, iBreak);
  69484. sqlite3VdbeResolveLabel(v, iCont);
  69485. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  69486. sqlite3VdbeResolveLabel(v, iBreak);
  69487. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  69488. }
  69489. break;
  69490. }
  69491. case TK_INTERSECT: {
  69492. int tab1, tab2;
  69493. int iCont, iBreak, iStart;
  69494. Expr *pLimit, *pOffset;
  69495. int addr;
  69496. SelectDest intersectdest;
  69497. int r1;
  69498. /* INTERSECT is different from the others since it requires
  69499. ** two temporary tables. Hence it has its own case. Begin
  69500. ** by allocating the tables we will need.
  69501. */
  69502. tab1 = pParse->nTab++;
  69503. tab2 = pParse->nTab++;
  69504. assert( p->pOrderBy==0 );
  69505. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  69506. assert( p->addrOpenEphm[0] == -1 );
  69507. p->addrOpenEphm[0] = addr;
  69508. p->pRightmost->selFlags |= SF_UsesEphemeral;
  69509. assert( p->pEList );
  69510. /* Code the SELECTs to our left into temporary table "tab1".
  69511. */
  69512. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  69513. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  69514. if( rc ){
  69515. goto multi_select_end;
  69516. }
  69517. /* Code the current SELECT into temporary table "tab2"
  69518. */
  69519. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  69520. assert( p->addrOpenEphm[1] == -1 );
  69521. p->addrOpenEphm[1] = addr;
  69522. p->pPrior = 0;
  69523. pLimit = p->pLimit;
  69524. p->pLimit = 0;
  69525. pOffset = p->pOffset;
  69526. p->pOffset = 0;
  69527. intersectdest.iParm = tab2;
  69528. rc = sqlite3Select(pParse, p, &intersectdest);
  69529. pDelete = p->pPrior;
  69530. p->pPrior = pPrior;
  69531. sqlite3ExprDelete(db, p->pLimit);
  69532. p->pLimit = pLimit;
  69533. p->pOffset = pOffset;
  69534. if( rc ){
  69535. goto multi_select_end;
  69536. }
  69537. /* Generate code to take the intersection of the two temporary
  69538. ** tables.
  69539. */
  69540. assert( p->pEList );
  69541. if( dest.eDest==SRT_Output ){
  69542. Select *pFirst = p;
  69543. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  69544. generateColumnNames(pParse, 0, pFirst->pEList);
  69545. }
  69546. iBreak = sqlite3VdbeMakeLabel(v);
  69547. iCont = sqlite3VdbeMakeLabel(v);
  69548. computeLimitRegisters(pParse, p, iBreak);
  69549. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  69550. r1 = sqlite3GetTempReg(pParse);
  69551. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  69552. sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
  69553. sqlite3ReleaseTempReg(pParse, r1);
  69554. selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  69555. 0, -1, &dest, iCont, iBreak);
  69556. sqlite3VdbeResolveLabel(v, iCont);
  69557. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  69558. sqlite3VdbeResolveLabel(v, iBreak);
  69559. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  69560. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  69561. break;
  69562. }
  69563. }
  69564. /* Compute collating sequences used by
  69565. ** temporary tables needed to implement the compound select.
  69566. ** Attach the KeyInfo structure to all temporary tables.
  69567. **
  69568. ** This section is run by the right-most SELECT statement only.
  69569. ** SELECT statements to the left always skip this part. The right-most
  69570. ** SELECT might also skip this part if it has no ORDER BY clause and
  69571. ** no temp tables are required.
  69572. */
  69573. if( p->selFlags & SF_UsesEphemeral ){
  69574. int i; /* Loop counter */
  69575. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  69576. Select *pLoop; /* For looping through SELECT statements */
  69577. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  69578. int nCol; /* Number of columns in result set */
  69579. assert( p->pRightmost==p );
  69580. nCol = p->pEList->nExpr;
  69581. pKeyInfo = sqlite3DbMallocZero(db,
  69582. sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
  69583. if( !pKeyInfo ){
  69584. rc = SQLITE_NOMEM;
  69585. goto multi_select_end;
  69586. }
  69587. pKeyInfo->enc = ENC(db);
  69588. pKeyInfo->nField = (u16)nCol;
  69589. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  69590. *apColl = multiSelectCollSeq(pParse, p, i);
  69591. if( 0==*apColl ){
  69592. *apColl = db->pDfltColl;
  69593. }
  69594. }
  69595. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  69596. for(i=0; i<2; i++){
  69597. int addr = pLoop->addrOpenEphm[i];
  69598. if( addr<0 ){
  69599. /* If [0] is unused then [1] is also unused. So we can
  69600. ** always safely abort as soon as the first unused slot is found */
  69601. assert( pLoop->addrOpenEphm[1]<0 );
  69602. break;
  69603. }
  69604. sqlite3VdbeChangeP2(v, addr, nCol);
  69605. sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  69606. pLoop->addrOpenEphm[i] = -1;
  69607. }
  69608. }
  69609. sqlite3DbFree(db, pKeyInfo);
  69610. }
  69611. multi_select_end:
  69612. pDest->iMem = dest.iMem;
  69613. pDest->nMem = dest.nMem;
  69614. sqlite3SelectDelete(db, pDelete);
  69615. return rc;
  69616. }
  69617. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  69618. /*
  69619. ** Code an output subroutine for a coroutine implementation of a
  69620. ** SELECT statment.
  69621. **
  69622. ** The data to be output is contained in pIn->iMem. There are
  69623. ** pIn->nMem columns to be output. pDest is where the output should
  69624. ** be sent.
  69625. **
  69626. ** regReturn is the number of the register holding the subroutine
  69627. ** return address.
  69628. **
  69629. ** If regPrev>0 then it is a the first register in a vector that
  69630. ** records the previous output. mem[regPrev] is a flag that is false
  69631. ** if there has been no previous output. If regPrev>0 then code is
  69632. ** generated to suppress duplicates. pKeyInfo is used for comparing
  69633. ** keys.
  69634. **
  69635. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  69636. ** iBreak.
  69637. */
  69638. static int generateOutputSubroutine(
  69639. Parse *pParse, /* Parsing context */
  69640. Select *p, /* The SELECT statement */
  69641. SelectDest *pIn, /* Coroutine supplying data */
  69642. SelectDest *pDest, /* Where to send the data */
  69643. int regReturn, /* The return address register */
  69644. int regPrev, /* Previous result register. No uniqueness if 0 */
  69645. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  69646. int p4type, /* The p4 type for pKeyInfo */
  69647. int iBreak /* Jump here if we hit the LIMIT */
  69648. ){
  69649. Vdbe *v = pParse->pVdbe;
  69650. int iContinue;
  69651. int addr;
  69652. addr = sqlite3VdbeCurrentAddr(v);
  69653. iContinue = sqlite3VdbeMakeLabel(v);
  69654. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  69655. */
  69656. if( regPrev ){
  69657. int j1, j2;
  69658. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  69659. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
  69660. (char*)pKeyInfo, p4type);
  69661. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  69662. sqlite3VdbeJumpHere(v, j1);
  69663. sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
  69664. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  69665. }
  69666. if( pParse->db->mallocFailed ) return 0;
  69667. /* Suppress the the first OFFSET entries if there is an OFFSET clause
  69668. */
  69669. codeOffset(v, p, iContinue);
  69670. switch( pDest->eDest ){
  69671. /* Store the result as data using a unique key.
  69672. */
  69673. case SRT_Table:
  69674. case SRT_EphemTab: {
  69675. int r1 = sqlite3GetTempReg(pParse);
  69676. int r2 = sqlite3GetTempReg(pParse);
  69677. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
  69678. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
  69679. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
  69680. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  69681. sqlite3ReleaseTempReg(pParse, r2);
  69682. sqlite3ReleaseTempReg(pParse, r1);
  69683. break;
  69684. }
  69685. #ifndef SQLITE_OMIT_SUBQUERY
  69686. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  69687. ** then there should be a single item on the stack. Write this
  69688. ** item into the set table with bogus data.
  69689. */
  69690. case SRT_Set: {
  69691. int r1;
  69692. assert( pIn->nMem==1 );
  69693. p->affinity =
  69694. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
  69695. r1 = sqlite3GetTempReg(pParse);
  69696. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
  69697. sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
  69698. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
  69699. sqlite3ReleaseTempReg(pParse, r1);
  69700. break;
  69701. }
  69702. #if 0 /* Never occurs on an ORDER BY query */
  69703. /* If any row exist in the result set, record that fact and abort.
  69704. */
  69705. case SRT_Exists: {
  69706. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
  69707. /* The LIMIT clause will terminate the loop for us */
  69708. break;
  69709. }
  69710. #endif
  69711. /* If this is a scalar select that is part of an expression, then
  69712. ** store the results in the appropriate memory cell and break out
  69713. ** of the scan loop.
  69714. */
  69715. case SRT_Mem: {
  69716. assert( pIn->nMem==1 );
  69717. sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
  69718. /* The LIMIT clause will jump out of the loop for us */
  69719. break;
  69720. }
  69721. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  69722. /* The results are stored in a sequence of registers
  69723. ** starting at pDest->iMem. Then the co-routine yields.
  69724. */
  69725. case SRT_Coroutine: {
  69726. if( pDest->iMem==0 ){
  69727. pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
  69728. pDest->nMem = pIn->nMem;
  69729. }
  69730. sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
  69731. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
  69732. break;
  69733. }
  69734. /* Results are stored in a sequence of registers. Then the
  69735. ** OP_ResultRow opcode is used to cause sqlite3_step() to return
  69736. ** the next row of result.
  69737. */
  69738. case SRT_Output: {
  69739. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
  69740. sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
  69741. break;
  69742. }
  69743. #if !defined(SQLITE_OMIT_TRIGGER)
  69744. /* Discard the results. This is used for SELECT statements inside
  69745. ** the body of a TRIGGER. The purpose of such selects is to call
  69746. ** user-defined functions that have side effects. We do not care
  69747. ** about the actual results of the select.
  69748. */
  69749. default: {
  69750. break;
  69751. }
  69752. #endif
  69753. }
  69754. /* Jump to the end of the loop if the LIMIT is reached.
  69755. */
  69756. if( p->iLimit ){
  69757. sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
  69758. sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
  69759. }
  69760. /* Generate the subroutine return
  69761. */
  69762. sqlite3VdbeResolveLabel(v, iContinue);
  69763. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  69764. return addr;
  69765. }
  69766. /*
  69767. ** Alternative compound select code generator for cases when there
  69768. ** is an ORDER BY clause.
  69769. **
  69770. ** We assume a query of the following form:
  69771. **
  69772. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  69773. **
  69774. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  69775. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  69776. ** co-routines. Then run the co-routines in parallel and merge the results
  69777. ** into the output. In addition to the two coroutines (called selectA and
  69778. ** selectB) there are 7 subroutines:
  69779. **
  69780. ** outA: Move the output of the selectA coroutine into the output
  69781. ** of the compound query.
  69782. **
  69783. ** outB: Move the output of the selectB coroutine into the output
  69784. ** of the compound query. (Only generated for UNION and
  69785. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  69786. ** appears only in B.)
  69787. **
  69788. ** AltB: Called when there is data from both coroutines and A<B.
  69789. **
  69790. ** AeqB: Called when there is data from both coroutines and A==B.
  69791. **
  69792. ** AgtB: Called when there is data from both coroutines and A>B.
  69793. **
  69794. ** EofA: Called when data is exhausted from selectA.
  69795. **
  69796. ** EofB: Called when data is exhausted from selectB.
  69797. **
  69798. ** The implementation of the latter five subroutines depend on which
  69799. ** <operator> is used:
  69800. **
  69801. **
  69802. ** UNION ALL UNION EXCEPT INTERSECT
  69803. ** ------------- ----------------- -------------- -----------------
  69804. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  69805. **
  69806. ** AeqB: outA, nextA nextA nextA outA, nextA
  69807. **
  69808. ** AgtB: outB, nextB outB, nextB nextB nextB
  69809. **
  69810. ** EofA: outB, nextB outB, nextB halt halt
  69811. **
  69812. ** EofB: outA, nextA outA, nextA outA, nextA halt
  69813. **
  69814. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  69815. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  69816. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  69817. ** following nextX causes a jump to the end of the select processing.
  69818. **
  69819. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  69820. ** within the output subroutine. The regPrev register set holds the previously
  69821. ** output value. A comparison is made against this value and the output
  69822. ** is skipped if the next results would be the same as the previous.
  69823. **
  69824. ** The implementation plan is to implement the two coroutines and seven
  69825. ** subroutines first, then put the control logic at the bottom. Like this:
  69826. **
  69827. ** goto Init
  69828. ** coA: coroutine for left query (A)
  69829. ** coB: coroutine for right query (B)
  69830. ** outA: output one row of A
  69831. ** outB: output one row of B (UNION and UNION ALL only)
  69832. ** EofA: ...
  69833. ** EofB: ...
  69834. ** AltB: ...
  69835. ** AeqB: ...
  69836. ** AgtB: ...
  69837. ** Init: initialize coroutine registers
  69838. ** yield coA
  69839. ** if eof(A) goto EofA
  69840. ** yield coB
  69841. ** if eof(B) goto EofB
  69842. ** Cmpr: Compare A, B
  69843. ** Jump AltB, AeqB, AgtB
  69844. ** End: ...
  69845. **
  69846. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  69847. ** actually called using Gosub and they do not Return. EofA and EofB loop
  69848. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  69849. ** and AgtB jump to either L2 or to one of EofA or EofB.
  69850. */
  69851. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  69852. static int multiSelectOrderBy(
  69853. Parse *pParse, /* Parsing context */
  69854. Select *p, /* The right-most of SELECTs to be coded */
  69855. SelectDest *pDest /* What to do with query results */
  69856. ){
  69857. int i, j; /* Loop counters */
  69858. Select *pPrior; /* Another SELECT immediately to our left */
  69859. Vdbe *v; /* Generate code to this VDBE */
  69860. SelectDest destA; /* Destination for coroutine A */
  69861. SelectDest destB; /* Destination for coroutine B */
  69862. int regAddrA; /* Address register for select-A coroutine */
  69863. int regEofA; /* Flag to indicate when select-A is complete */
  69864. int regAddrB; /* Address register for select-B coroutine */
  69865. int regEofB; /* Flag to indicate when select-B is complete */
  69866. int addrSelectA; /* Address of the select-A coroutine */
  69867. int addrSelectB; /* Address of the select-B coroutine */
  69868. int regOutA; /* Address register for the output-A subroutine */
  69869. int regOutB; /* Address register for the output-B subroutine */
  69870. int addrOutA; /* Address of the output-A subroutine */
  69871. int addrOutB = 0; /* Address of the output-B subroutine */
  69872. int addrEofA; /* Address of the select-A-exhausted subroutine */
  69873. int addrEofB; /* Address of the select-B-exhausted subroutine */
  69874. int addrAltB; /* Address of the A<B subroutine */
  69875. int addrAeqB; /* Address of the A==B subroutine */
  69876. int addrAgtB; /* Address of the A>B subroutine */
  69877. int regLimitA; /* Limit register for select-A */
  69878. int regLimitB; /* Limit register for select-A */
  69879. int regPrev; /* A range of registers to hold previous output */
  69880. int savedLimit; /* Saved value of p->iLimit */
  69881. int savedOffset; /* Saved value of p->iOffset */
  69882. int labelCmpr; /* Label for the start of the merge algorithm */
  69883. int labelEnd; /* Label for the end of the overall SELECT stmt */
  69884. int j1; /* Jump instructions that get retargetted */
  69885. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  69886. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  69887. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  69888. sqlite3 *db; /* Database connection */
  69889. ExprList *pOrderBy; /* The ORDER BY clause */
  69890. int nOrderBy; /* Number of terms in the ORDER BY clause */
  69891. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  69892. assert( p->pOrderBy!=0 );
  69893. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  69894. db = pParse->db;
  69895. v = pParse->pVdbe;
  69896. if( v==0 ) return SQLITE_NOMEM;
  69897. labelEnd = sqlite3VdbeMakeLabel(v);
  69898. labelCmpr = sqlite3VdbeMakeLabel(v);
  69899. /* Patch up the ORDER BY clause
  69900. */
  69901. op = p->op;
  69902. pPrior = p->pPrior;
  69903. assert( pPrior->pOrderBy==0 );
  69904. pOrderBy = p->pOrderBy;
  69905. assert( pOrderBy );
  69906. nOrderBy = pOrderBy->nExpr;
  69907. /* For operators other than UNION ALL we have to make sure that
  69908. ** the ORDER BY clause covers every term of the result set. Add
  69909. ** terms to the ORDER BY clause as necessary.
  69910. */
  69911. if( op!=TK_ALL ){
  69912. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  69913. struct ExprList_item *pItem;
  69914. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  69915. assert( pItem->iCol>0 );
  69916. if( pItem->iCol==i ) break;
  69917. }
  69918. if( j==nOrderBy ){
  69919. Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
  69920. if( pNew==0 ) return SQLITE_NOMEM;
  69921. pNew->flags |= EP_IntValue;
  69922. pNew->iTable = i;
  69923. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
  69924. pOrderBy->a[nOrderBy++].iCol = (u16)i;
  69925. }
  69926. }
  69927. }
  69928. /* Compute the comparison permutation and keyinfo that is used with
  69929. ** the permutation in order to comparisons to determine if the next
  69930. ** row of results comes from selectA or selectB. Also add explicit
  69931. ** collations to the ORDER BY clause terms so that when the subqueries
  69932. ** to the right and the left are evaluated, they use the correct
  69933. ** collation.
  69934. */
  69935. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  69936. if( aPermute ){
  69937. struct ExprList_item *pItem;
  69938. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  69939. assert( pItem->iCol>0 && pItem->iCol<=p->pEList->nExpr );
  69940. aPermute[i] = pItem->iCol - 1;
  69941. }
  69942. pKeyMerge =
  69943. sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
  69944. if( pKeyMerge ){
  69945. pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
  69946. pKeyMerge->nField = (u16)nOrderBy;
  69947. pKeyMerge->enc = ENC(db);
  69948. for(i=0; i<nOrderBy; i++){
  69949. CollSeq *pColl;
  69950. Expr *pTerm = pOrderBy->a[i].pExpr;
  69951. if( pTerm->flags & EP_ExpCollate ){
  69952. pColl = pTerm->pColl;
  69953. }else{
  69954. pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  69955. pTerm->flags |= EP_ExpCollate;
  69956. pTerm->pColl = pColl;
  69957. }
  69958. pKeyMerge->aColl[i] = pColl;
  69959. pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  69960. }
  69961. }
  69962. }else{
  69963. pKeyMerge = 0;
  69964. }
  69965. /* Reattach the ORDER BY clause to the query.
  69966. */
  69967. p->pOrderBy = pOrderBy;
  69968. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy);
  69969. /* Allocate a range of temporary registers and the KeyInfo needed
  69970. ** for the logic that removes duplicate result rows when the
  69971. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  69972. */
  69973. if( op==TK_ALL ){
  69974. regPrev = 0;
  69975. }else{
  69976. int nExpr = p->pEList->nExpr;
  69977. assert( nOrderBy>=nExpr || db->mallocFailed );
  69978. regPrev = sqlite3GetTempRange(pParse, nExpr+1);
  69979. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  69980. pKeyDup = sqlite3DbMallocZero(db,
  69981. sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
  69982. if( pKeyDup ){
  69983. pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
  69984. pKeyDup->nField = (u16)nExpr;
  69985. pKeyDup->enc = ENC(db);
  69986. for(i=0; i<nExpr; i++){
  69987. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  69988. pKeyDup->aSortOrder[i] = 0;
  69989. }
  69990. }
  69991. }
  69992. /* Separate the left and the right query from one another
  69993. */
  69994. p->pPrior = 0;
  69995. pPrior->pRightmost = 0;
  69996. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  69997. if( pPrior->pPrior==0 ){
  69998. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  69999. }
  70000. /* Compute the limit registers */
  70001. computeLimitRegisters(pParse, p, labelEnd);
  70002. if( p->iLimit && op==TK_ALL ){
  70003. regLimitA = ++pParse->nMem;
  70004. regLimitB = ++pParse->nMem;
  70005. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  70006. regLimitA);
  70007. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  70008. }else{
  70009. regLimitA = regLimitB = 0;
  70010. }
  70011. sqlite3ExprDelete(db, p->pLimit);
  70012. p->pLimit = 0;
  70013. sqlite3ExprDelete(db, p->pOffset);
  70014. p->pOffset = 0;
  70015. regAddrA = ++pParse->nMem;
  70016. regEofA = ++pParse->nMem;
  70017. regAddrB = ++pParse->nMem;
  70018. regEofB = ++pParse->nMem;
  70019. regOutA = ++pParse->nMem;
  70020. regOutB = ++pParse->nMem;
  70021. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  70022. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  70023. /* Jump past the various subroutines and coroutines to the main
  70024. ** merge loop
  70025. */
  70026. j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  70027. addrSelectA = sqlite3VdbeCurrentAddr(v);
  70028. /* Generate a coroutine to evaluate the SELECT statement to the
  70029. ** left of the compound operator - the "A" select.
  70030. */
  70031. VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  70032. pPrior->iLimit = regLimitA;
  70033. sqlite3Select(pParse, pPrior, &destA);
  70034. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  70035. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  70036. VdbeNoopComment((v, "End coroutine for left SELECT"));
  70037. /* Generate a coroutine to evaluate the SELECT statement on
  70038. ** the right - the "B" select
  70039. */
  70040. addrSelectB = sqlite3VdbeCurrentAddr(v);
  70041. VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  70042. savedLimit = p->iLimit;
  70043. savedOffset = p->iOffset;
  70044. p->iLimit = regLimitB;
  70045. p->iOffset = 0;
  70046. sqlite3Select(pParse, p, &destB);
  70047. p->iLimit = savedLimit;
  70048. p->iOffset = savedOffset;
  70049. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  70050. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  70051. VdbeNoopComment((v, "End coroutine for right SELECT"));
  70052. /* Generate a subroutine that outputs the current row of the A
  70053. ** select as the next output row of the compound select.
  70054. */
  70055. VdbeNoopComment((v, "Output routine for A"));
  70056. addrOutA = generateOutputSubroutine(pParse,
  70057. p, &destA, pDest, regOutA,
  70058. regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  70059. /* Generate a subroutine that outputs the current row of the B
  70060. ** select as the next output row of the compound select.
  70061. */
  70062. if( op==TK_ALL || op==TK_UNION ){
  70063. VdbeNoopComment((v, "Output routine for B"));
  70064. addrOutB = generateOutputSubroutine(pParse,
  70065. p, &destB, pDest, regOutB,
  70066. regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  70067. }
  70068. /* Generate a subroutine to run when the results from select A
  70069. ** are exhausted and only data in select B remains.
  70070. */
  70071. VdbeNoopComment((v, "eof-A subroutine"));
  70072. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  70073. addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  70074. }else{
  70075. addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  70076. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  70077. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  70078. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  70079. }
  70080. /* Generate a subroutine to run when the results from select B
  70081. ** are exhausted and only data in select A remains.
  70082. */
  70083. if( op==TK_INTERSECT ){
  70084. addrEofB = addrEofA;
  70085. }else{
  70086. VdbeNoopComment((v, "eof-B subroutine"));
  70087. addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  70088. sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  70089. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  70090. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  70091. }
  70092. /* Generate code to handle the case of A<B
  70093. */
  70094. VdbeNoopComment((v, "A-lt-B subroutine"));
  70095. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  70096. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  70097. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  70098. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  70099. /* Generate code to handle the case of A==B
  70100. */
  70101. if( op==TK_ALL ){
  70102. addrAeqB = addrAltB;
  70103. }else if( op==TK_INTERSECT ){
  70104. addrAeqB = addrAltB;
  70105. addrAltB++;
  70106. }else{
  70107. VdbeNoopComment((v, "A-eq-B subroutine"));
  70108. addrAeqB =
  70109. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  70110. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  70111. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  70112. }
  70113. /* Generate code to handle the case of A>B
  70114. */
  70115. VdbeNoopComment((v, "A-gt-B subroutine"));
  70116. addrAgtB = sqlite3VdbeCurrentAddr(v);
  70117. if( op==TK_ALL || op==TK_UNION ){
  70118. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  70119. }
  70120. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  70121. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  70122. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  70123. /* This code runs once to initialize everything.
  70124. */
  70125. sqlite3VdbeJumpHere(v, j1);
  70126. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  70127. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  70128. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  70129. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  70130. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  70131. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  70132. /* Implement the main merge loop
  70133. */
  70134. sqlite3VdbeResolveLabel(v, labelCmpr);
  70135. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  70136. sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
  70137. (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  70138. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  70139. /* Release temporary registers
  70140. */
  70141. if( regPrev ){
  70142. sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
  70143. }
  70144. /* Jump to the this point in order to terminate the query.
  70145. */
  70146. sqlite3VdbeResolveLabel(v, labelEnd);
  70147. /* Set the number of output columns
  70148. */
  70149. if( pDest->eDest==SRT_Output ){
  70150. Select *pFirst = pPrior;
  70151. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  70152. generateColumnNames(pParse, 0, pFirst->pEList);
  70153. }
  70154. /* Reassembly the compound query so that it will be freed correctly
  70155. ** by the calling function */
  70156. if( p->pPrior ){
  70157. sqlite3SelectDelete(db, p->pPrior);
  70158. }
  70159. p->pPrior = pPrior;
  70160. /*** TBD: Insert subroutine calls to close cursors on incomplete
  70161. **** subqueries ****/
  70162. return SQLITE_OK;
  70163. }
  70164. #endif
  70165. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  70166. /* Forward Declarations */
  70167. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  70168. static void substSelect(sqlite3*, Select *, int, ExprList *);
  70169. /*
  70170. ** Scan through the expression pExpr. Replace every reference to
  70171. ** a column in table number iTable with a copy of the iColumn-th
  70172. ** entry in pEList. (But leave references to the ROWID column
  70173. ** unchanged.)
  70174. **
  70175. ** This routine is part of the flattening procedure. A subquery
  70176. ** whose result set is defined by pEList appears as entry in the
  70177. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  70178. ** FORM clause entry is iTable. This routine make the necessary
  70179. ** changes to pExpr so that it refers directly to the source table
  70180. ** of the subquery rather the result set of the subquery.
  70181. */
  70182. static void substExpr(
  70183. sqlite3 *db, /* Report malloc errors to this connection */
  70184. Expr *pExpr, /* Expr in which substitution occurs */
  70185. int iTable, /* Table to be substituted */
  70186. ExprList *pEList /* Substitute expressions */
  70187. ){
  70188. if( pExpr==0 ) return;
  70189. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  70190. if( pExpr->iColumn<0 ){
  70191. pExpr->op = TK_NULL;
  70192. }else{
  70193. Expr *pNew;
  70194. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  70195. assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
  70196. pNew = pEList->a[pExpr->iColumn].pExpr;
  70197. assert( pNew!=0 );
  70198. pExpr->op = pNew->op;
  70199. assert( pExpr->pLeft==0 );
  70200. pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
  70201. assert( pExpr->pRight==0 );
  70202. pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
  70203. assert( pExpr->pList==0 );
  70204. pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
  70205. pExpr->iTable = pNew->iTable;
  70206. pExpr->pTab = pNew->pTab;
  70207. pExpr->iColumn = pNew->iColumn;
  70208. pExpr->iAgg = pNew->iAgg;
  70209. sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
  70210. sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
  70211. pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
  70212. pExpr->flags = pNew->flags;
  70213. pExpr->pAggInfo = pNew->pAggInfo;
  70214. pNew->pAggInfo = 0;
  70215. }
  70216. }else{
  70217. substExpr(db, pExpr->pLeft, iTable, pEList);
  70218. substExpr(db, pExpr->pRight, iTable, pEList);
  70219. substSelect(db, pExpr->pSelect, iTable, pEList);
  70220. substExprList(db, pExpr->pList, iTable, pEList);
  70221. }
  70222. }
  70223. static void substExprList(
  70224. sqlite3 *db, /* Report malloc errors here */
  70225. ExprList *pList, /* List to scan and in which to make substitutes */
  70226. int iTable, /* Table to be substituted */
  70227. ExprList *pEList /* Substitute values */
  70228. ){
  70229. int i;
  70230. if( pList==0 ) return;
  70231. for(i=0; i<pList->nExpr; i++){
  70232. substExpr(db, pList->a[i].pExpr, iTable, pEList);
  70233. }
  70234. }
  70235. static void substSelect(
  70236. sqlite3 *db, /* Report malloc errors here */
  70237. Select *p, /* SELECT statement in which to make substitutions */
  70238. int iTable, /* Table to be replaced */
  70239. ExprList *pEList /* Substitute values */
  70240. ){
  70241. SrcList *pSrc;
  70242. struct SrcList_item *pItem;
  70243. int i;
  70244. if( !p ) return;
  70245. substExprList(db, p->pEList, iTable, pEList);
  70246. substExprList(db, p->pGroupBy, iTable, pEList);
  70247. substExprList(db, p->pOrderBy, iTable, pEList);
  70248. substExpr(db, p->pHaving, iTable, pEList);
  70249. substExpr(db, p->pWhere, iTable, pEList);
  70250. substSelect(db, p->pPrior, iTable, pEList);
  70251. pSrc = p->pSrc;
  70252. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  70253. if( ALWAYS(pSrc) ){
  70254. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  70255. substSelect(db, pItem->pSelect, iTable, pEList);
  70256. }
  70257. }
  70258. }
  70259. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  70260. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  70261. /*
  70262. ** This routine attempts to flatten subqueries in order to speed
  70263. ** execution. It returns 1 if it makes changes and 0 if no flattening
  70264. ** occurs.
  70265. **
  70266. ** To understand the concept of flattening, consider the following
  70267. ** query:
  70268. **
  70269. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  70270. **
  70271. ** The default way of implementing this query is to execute the
  70272. ** subquery first and store the results in a temporary table, then
  70273. ** run the outer query on that temporary table. This requires two
  70274. ** passes over the data. Furthermore, because the temporary table
  70275. ** has no indices, the WHERE clause on the outer query cannot be
  70276. ** optimized.
  70277. **
  70278. ** This routine attempts to rewrite queries such as the above into
  70279. ** a single flat select, like this:
  70280. **
  70281. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  70282. **
  70283. ** The code generated for this simpification gives the same result
  70284. ** but only has to scan the data once. And because indices might
  70285. ** exist on the table t1, a complete scan of the data might be
  70286. ** avoided.
  70287. **
  70288. ** Flattening is only attempted if all of the following are true:
  70289. **
  70290. ** (1) The subquery and the outer query do not both use aggregates.
  70291. **
  70292. ** (2) The subquery is not an aggregate or the outer query is not a join.
  70293. **
  70294. ** (3) The subquery is not the right operand of a left outer join
  70295. ** (Originally ticket #306. Strenghtened by ticket #3300)
  70296. **
  70297. ** (4) The subquery is not DISTINCT or the outer query is not a join.
  70298. **
  70299. ** (5) The subquery is not DISTINCT or the outer query does not use
  70300. ** aggregates.
  70301. **
  70302. ** (6) The subquery does not use aggregates or the outer query is not
  70303. ** DISTINCT.
  70304. **
  70305. ** (7) The subquery has a FROM clause.
  70306. **
  70307. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  70308. **
  70309. ** (9) The subquery does not use LIMIT or the outer query does not use
  70310. ** aggregates.
  70311. **
  70312. ** (10) The subquery does not use aggregates or the outer query does not
  70313. ** use LIMIT.
  70314. **
  70315. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  70316. **
  70317. ** (12) Not implemented. Subsumed into restriction (3). Was previously
  70318. ** a separate restriction deriving from ticket #350.
  70319. **
  70320. ** (13) The subquery and outer query do not both use LIMIT
  70321. **
  70322. ** (14) The subquery does not use OFFSET
  70323. **
  70324. ** (15) The outer query is not part of a compound select or the
  70325. ** subquery does not have both an ORDER BY and a LIMIT clause.
  70326. ** (See ticket #2339)
  70327. **
  70328. ** (16) The outer query is not an aggregate or the subquery does
  70329. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  70330. ** until we introduced the group_concat() function.
  70331. **
  70332. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  70333. ** compound clause made up entirely of non-aggregate queries, and
  70334. ** the parent query:
  70335. **
  70336. ** * is not itself part of a compound select,
  70337. ** * is not an aggregate or DISTINCT query, and
  70338. ** * has no other tables or sub-selects in the FROM clause.
  70339. **
  70340. ** The parent and sub-query may contain WHERE clauses. Subject to
  70341. ** rules (11), (13) and (14), they may also contain ORDER BY,
  70342. ** LIMIT and OFFSET clauses.
  70343. **
  70344. ** (18) If the sub-query is a compound select, then all terms of the
  70345. ** ORDER by clause of the parent must be simple references to
  70346. ** columns of the sub-query.
  70347. **
  70348. ** (19) The subquery does not use LIMIT or the outer query does not
  70349. ** have a WHERE clause.
  70350. **
  70351. ** In this routine, the "p" parameter is a pointer to the outer query.
  70352. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  70353. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  70354. **
  70355. ** If flattening is not attempted, this routine is a no-op and returns 0.
  70356. ** If flattening is attempted this routine returns 1.
  70357. **
  70358. ** All of the expression analysis must occur on both the outer query and
  70359. ** the subquery before this routine runs.
  70360. */
  70361. static int flattenSubquery(
  70362. Parse *pParse, /* Parsing context */
  70363. Select *p, /* The parent or outer SELECT statement */
  70364. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  70365. int isAgg, /* True if outer SELECT uses aggregate functions */
  70366. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  70367. ){
  70368. const char *zSavedAuthContext = pParse->zAuthContext;
  70369. Select *pParent;
  70370. Select *pSub; /* The inner query or "subquery" */
  70371. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  70372. SrcList *pSrc; /* The FROM clause of the outer query */
  70373. SrcList *pSubSrc; /* The FROM clause of the subquery */
  70374. ExprList *pList; /* The result set of the outer query */
  70375. int iParent; /* VDBE cursor number of the pSub result set temp table */
  70376. int i; /* Loop counter */
  70377. Expr *pWhere; /* The WHERE clause */
  70378. struct SrcList_item *pSubitem; /* The subquery */
  70379. sqlite3 *db = pParse->db;
  70380. /* Check to see if flattening is permitted. Return 0 if not.
  70381. */
  70382. assert( p!=0 );
  70383. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  70384. pSrc = p->pSrc;
  70385. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  70386. pSubitem = &pSrc->a[iFrom];
  70387. iParent = pSubitem->iCursor;
  70388. pSub = pSubitem->pSelect;
  70389. assert( pSub!=0 );
  70390. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  70391. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  70392. pSubSrc = pSub->pSrc;
  70393. assert( pSubSrc );
  70394. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  70395. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  70396. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  70397. ** became arbitrary expressions, we were forced to add restrictions (13)
  70398. ** and (14). */
  70399. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  70400. if( pSub->pOffset ) return 0; /* Restriction (14) */
  70401. if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
  70402. return 0; /* Restriction (15) */
  70403. }
  70404. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  70405. if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
  70406. && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */
  70407. return 0;
  70408. }
  70409. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  70410. return 0; /* Restriction (6) */
  70411. }
  70412. if( p->pOrderBy && pSub->pOrderBy ){
  70413. return 0; /* Restriction (11) */
  70414. }
  70415. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  70416. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  70417. /* OBSOLETE COMMENT 1:
  70418. ** Restriction 3: If the subquery is a join, make sure the subquery is
  70419. ** not used as the right operand of an outer join. Examples of why this
  70420. ** is not allowed:
  70421. **
  70422. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  70423. **
  70424. ** If we flatten the above, we would get
  70425. **
  70426. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  70427. **
  70428. ** which is not at all the same thing.
  70429. **
  70430. ** OBSOLETE COMMENT 2:
  70431. ** Restriction 12: If the subquery is the right operand of a left outer
  70432. ** join, make sure the subquery has no WHERE clause.
  70433. ** An examples of why this is not allowed:
  70434. **
  70435. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  70436. **
  70437. ** If we flatten the above, we would get
  70438. **
  70439. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  70440. **
  70441. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  70442. ** effectively converts the OUTER JOIN into an INNER JOIN.
  70443. **
  70444. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  70445. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  70446. ** is fraught with danger. Best to avoid the whole thing. If the
  70447. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  70448. */
  70449. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  70450. return 0;
  70451. }
  70452. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  70453. ** use only the UNION ALL operator. And none of the simple select queries
  70454. ** that make up the compound SELECT are allowed to be aggregate or distinct
  70455. ** queries.
  70456. */
  70457. if( pSub->pPrior ){
  70458. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  70459. return 0;
  70460. }
  70461. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  70462. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  70463. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  70464. || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
  70465. ){
  70466. return 0;
  70467. }
  70468. }
  70469. /* Restriction 18. */
  70470. if( p->pOrderBy ){
  70471. int ii;
  70472. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  70473. if( p->pOrderBy->a[ii].iCol==0 ) return 0;
  70474. }
  70475. }
  70476. }
  70477. /***** If we reach this point, flattening is permitted. *****/
  70478. /* Authorize the subquery */
  70479. pParse->zAuthContext = pSubitem->zName;
  70480. sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  70481. pParse->zAuthContext = zSavedAuthContext;
  70482. /* If the sub-query is a compound SELECT statement, then (by restrictions
  70483. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  70484. ** be of the form:
  70485. **
  70486. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  70487. **
  70488. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  70489. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  70490. ** OFFSET clauses and joins them to the left-hand-side of the original
  70491. ** using UNION ALL operators. In this case N is the number of simple
  70492. ** select statements in the compound sub-query.
  70493. **
  70494. ** Example:
  70495. **
  70496. ** SELECT a+1 FROM (
  70497. ** SELECT x FROM tab
  70498. ** UNION ALL
  70499. ** SELECT y FROM tab
  70500. ** UNION ALL
  70501. ** SELECT abs(z*2) FROM tab2
  70502. ** ) WHERE a!=5 ORDER BY 1
  70503. **
  70504. ** Transformed into:
  70505. **
  70506. ** SELECT x+1 FROM tab WHERE x+1!=5
  70507. ** UNION ALL
  70508. ** SELECT y+1 FROM tab WHERE y+1!=5
  70509. ** UNION ALL
  70510. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  70511. ** ORDER BY 1
  70512. **
  70513. ** We call this the "compound-subquery flattening".
  70514. */
  70515. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  70516. Select *pNew;
  70517. ExprList *pOrderBy = p->pOrderBy;
  70518. Expr *pLimit = p->pLimit;
  70519. Select *pPrior = p->pPrior;
  70520. p->pOrderBy = 0;
  70521. p->pSrc = 0;
  70522. p->pPrior = 0;
  70523. p->pLimit = 0;
  70524. pNew = sqlite3SelectDup(db, p);
  70525. p->pLimit = pLimit;
  70526. p->pOrderBy = pOrderBy;
  70527. p->pSrc = pSrc;
  70528. p->op = TK_ALL;
  70529. p->pRightmost = 0;
  70530. if( pNew==0 ){
  70531. pNew = pPrior;
  70532. }else{
  70533. pNew->pPrior = pPrior;
  70534. pNew->pRightmost = 0;
  70535. }
  70536. p->pPrior = pNew;
  70537. if( db->mallocFailed ) return 1;
  70538. }
  70539. /* Begin flattening the iFrom-th entry of the FROM clause
  70540. ** in the outer query.
  70541. */
  70542. pSub = pSub1 = pSubitem->pSelect;
  70543. /* Delete the transient table structure associated with the
  70544. ** subquery
  70545. */
  70546. sqlite3DbFree(db, pSubitem->zDatabase);
  70547. sqlite3DbFree(db, pSubitem->zName);
  70548. sqlite3DbFree(db, pSubitem->zAlias);
  70549. pSubitem->zDatabase = 0;
  70550. pSubitem->zName = 0;
  70551. pSubitem->zAlias = 0;
  70552. pSubitem->pSelect = 0;
  70553. /* Defer deleting the Table object associated with the
  70554. ** subquery until code generation is
  70555. ** complete, since there may still exist Expr.pTab entries that
  70556. ** refer to the subquery even after flattening. Ticket #3346.
  70557. */
  70558. if( pSubitem->pTab!=0 ){
  70559. Table *pTabToDel = pSubitem->pTab;
  70560. if( pTabToDel->nRef==1 ){
  70561. pTabToDel->pNextZombie = pParse->pZombieTab;
  70562. pParse->pZombieTab = pTabToDel;
  70563. }else{
  70564. pTabToDel->nRef--;
  70565. }
  70566. pSubitem->pTab = 0;
  70567. }
  70568. /* The following loop runs once for each term in a compound-subquery
  70569. ** flattening (as described above). If we are doing a different kind
  70570. ** of flattening - a flattening other than a compound-subquery flattening -
  70571. ** then this loop only runs once.
  70572. **
  70573. ** This loop moves all of the FROM elements of the subquery into the
  70574. ** the FROM clause of the outer query. Before doing this, remember
  70575. ** the cursor number for the original outer query FROM element in
  70576. ** iParent. The iParent cursor will never be used. Subsequent code
  70577. ** will scan expressions looking for iParent references and replace
  70578. ** those references with expressions that resolve to the subquery FROM
  70579. ** elements we are now copying in.
  70580. */
  70581. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  70582. int nSubSrc;
  70583. u8 jointype = 0;
  70584. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  70585. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  70586. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  70587. if( pSrc ){
  70588. assert( pParent==p ); /* First time through the loop */
  70589. jointype = pSubitem->jointype;
  70590. }else{
  70591. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  70592. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  70593. if( pSrc==0 ){
  70594. assert( db->mallocFailed );
  70595. break;
  70596. }
  70597. }
  70598. /* The subquery uses a single slot of the FROM clause of the outer
  70599. ** query. If the subquery has more than one element in its FROM clause,
  70600. ** then expand the outer query to make space for it to hold all elements
  70601. ** of the subquery.
  70602. **
  70603. ** Example:
  70604. **
  70605. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  70606. **
  70607. ** The outer query has 3 slots in its FROM clause. One slot of the
  70608. ** outer query (the middle slot) is used by the subquery. The next
  70609. ** block of code will expand the out query to 4 slots. The middle
  70610. ** slot is expanded to two slots in order to make space for the
  70611. ** two elements in the FROM clause of the subquery.
  70612. */
  70613. if( nSubSrc>1 ){
  70614. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  70615. if( db->mallocFailed ){
  70616. break;
  70617. }
  70618. }
  70619. /* Transfer the FROM clause terms from the subquery into the
  70620. ** outer query.
  70621. */
  70622. for(i=0; i<nSubSrc; i++){
  70623. pSrc->a[i+iFrom] = pSubSrc->a[i];
  70624. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  70625. }
  70626. pSrc->a[iFrom].jointype = jointype;
  70627. /* Now begin substituting subquery result set expressions for
  70628. ** references to the iParent in the outer query.
  70629. **
  70630. ** Example:
  70631. **
  70632. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  70633. ** \ \_____________ subquery __________/ /
  70634. ** \_____________________ outer query ______________________________/
  70635. **
  70636. ** We look at every expression in the outer query and every place we see
  70637. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  70638. */
  70639. pList = pParent->pEList;
  70640. for(i=0; i<pList->nExpr; i++){
  70641. Expr *pExpr;
  70642. if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
  70643. pList->a[i].zName =
  70644. sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
  70645. }
  70646. }
  70647. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  70648. if( isAgg ){
  70649. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  70650. substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  70651. }
  70652. if( pSub->pOrderBy ){
  70653. assert( pParent->pOrderBy==0 );
  70654. pParent->pOrderBy = pSub->pOrderBy;
  70655. pSub->pOrderBy = 0;
  70656. }else if( pParent->pOrderBy ){
  70657. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  70658. }
  70659. if( pSub->pWhere ){
  70660. pWhere = sqlite3ExprDup(db, pSub->pWhere);
  70661. }else{
  70662. pWhere = 0;
  70663. }
  70664. if( subqueryIsAgg ){
  70665. assert( pParent->pHaving==0 );
  70666. pParent->pHaving = pParent->pWhere;
  70667. pParent->pWhere = pWhere;
  70668. substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  70669. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  70670. sqlite3ExprDup(db, pSub->pHaving));
  70671. assert( pParent->pGroupBy==0 );
  70672. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
  70673. }else{
  70674. substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  70675. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  70676. }
  70677. /* The flattened query is distinct if either the inner or the
  70678. ** outer query is distinct.
  70679. */
  70680. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  70681. /*
  70682. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  70683. **
  70684. ** One is tempted to try to add a and b to combine the limits. But this
  70685. ** does not work if either limit is negative.
  70686. */
  70687. if( pSub->pLimit ){
  70688. pParent->pLimit = pSub->pLimit;
  70689. pSub->pLimit = 0;
  70690. }
  70691. }
  70692. /* Finially, delete what is left of the subquery and return
  70693. ** success.
  70694. */
  70695. sqlite3SelectDelete(db, pSub1);
  70696. return 1;
  70697. }
  70698. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  70699. /*
  70700. ** Analyze the SELECT statement passed as an argument to see if it
  70701. ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
  70702. ** it is, or 0 otherwise. At present, a query is considered to be
  70703. ** a min()/max() query if:
  70704. **
  70705. ** 1. There is a single object in the FROM clause.
  70706. **
  70707. ** 2. There is a single expression in the result set, and it is
  70708. ** either min(x) or max(x), where x is a column reference.
  70709. */
  70710. static u8 minMaxQuery(Select *p){
  70711. Expr *pExpr;
  70712. ExprList *pEList = p->pEList;
  70713. if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
  70714. pExpr = pEList->a[0].pExpr;
  70715. pEList = pExpr->pList;
  70716. if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
  70717. if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
  70718. if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
  70719. if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
  70720. return WHERE_ORDERBY_MIN;
  70721. }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
  70722. return WHERE_ORDERBY_MAX;
  70723. }
  70724. return WHERE_ORDERBY_NORMAL;
  70725. }
  70726. /*
  70727. ** If the source-list item passed as an argument was augmented with an
  70728. ** INDEXED BY clause, then try to locate the specified index. If there
  70729. ** was such a clause and the named index cannot be found, return
  70730. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  70731. ** pFrom->pIndex and return SQLITE_OK.
  70732. */
  70733. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  70734. if( pFrom->pTab && pFrom->zIndex ){
  70735. Table *pTab = pFrom->pTab;
  70736. char *zIndex = pFrom->zIndex;
  70737. Index *pIdx;
  70738. for(pIdx=pTab->pIndex;
  70739. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  70740. pIdx=pIdx->pNext
  70741. );
  70742. if( !pIdx ){
  70743. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  70744. return SQLITE_ERROR;
  70745. }
  70746. pFrom->pIndex = pIdx;
  70747. }
  70748. return SQLITE_OK;
  70749. }
  70750. /*
  70751. ** This routine is a Walker callback for "expanding" a SELECT statement.
  70752. ** "Expanding" means to do the following:
  70753. **
  70754. ** (1) Make sure VDBE cursor numbers have been assigned to every
  70755. ** element of the FROM clause.
  70756. **
  70757. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  70758. ** defines FROM clause. When views appear in the FROM clause,
  70759. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  70760. ** that implements the view. A copy is made of the view's SELECT
  70761. ** statement so that we can freely modify or delete that statement
  70762. ** without worrying about messing up the presistent representation
  70763. ** of the view.
  70764. **
  70765. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  70766. ** on joins and the ON and USING clause of joins.
  70767. **
  70768. ** (4) Scan the list of columns in the result set (pEList) looking
  70769. ** for instances of the "*" operator or the TABLE.* operator.
  70770. ** If found, expand each "*" to be every column in every table
  70771. ** and TABLE.* to be every column in TABLE.
  70772. **
  70773. */
  70774. static int selectExpander(Walker *pWalker, Select *p){
  70775. Parse *pParse = pWalker->pParse;
  70776. int i, j, k;
  70777. SrcList *pTabList;
  70778. ExprList *pEList;
  70779. struct SrcList_item *pFrom;
  70780. sqlite3 *db = pParse->db;
  70781. if( db->mallocFailed ){
  70782. return WRC_Abort;
  70783. }
  70784. if( p->pSrc==0 || (p->selFlags & SF_Expanded)!=0 ){
  70785. return WRC_Prune;
  70786. }
  70787. p->selFlags |= SF_Expanded;
  70788. pTabList = p->pSrc;
  70789. pEList = p->pEList;
  70790. /* Make sure cursor numbers have been assigned to all entries in
  70791. ** the FROM clause of the SELECT statement.
  70792. */
  70793. sqlite3SrcListAssignCursors(pParse, pTabList);
  70794. /* Look up every table named in the FROM clause of the select. If
  70795. ** an entry of the FROM clause is a subquery instead of a table or view,
  70796. ** then create a transient table structure to describe the subquery.
  70797. */
  70798. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  70799. Table *pTab;
  70800. if( pFrom->pTab!=0 ){
  70801. /* This statement has already been prepared. There is no need
  70802. ** to go further. */
  70803. assert( i==0 );
  70804. return WRC_Prune;
  70805. }
  70806. if( pFrom->zName==0 ){
  70807. #ifndef SQLITE_OMIT_SUBQUERY
  70808. Select *pSel = pFrom->pSelect;
  70809. /* A sub-query in the FROM clause of a SELECT */
  70810. assert( pSel!=0 );
  70811. assert( pFrom->pTab==0 );
  70812. sqlite3WalkSelect(pWalker, pSel);
  70813. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  70814. if( pTab==0 ) return WRC_Abort;
  70815. pTab->db = db;
  70816. pTab->nRef = 1;
  70817. pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
  70818. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  70819. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  70820. pTab->iPKey = -1;
  70821. pTab->tabFlags |= TF_Ephemeral;
  70822. #endif
  70823. }else{
  70824. /* An ordinary table or view name in the FROM clause */
  70825. assert( pFrom->pTab==0 );
  70826. pFrom->pTab = pTab =
  70827. sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
  70828. if( pTab==0 ) return WRC_Abort;
  70829. pTab->nRef++;
  70830. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  70831. if( pTab->pSelect || IsVirtual(pTab) ){
  70832. /* We reach here if the named table is a really a view */
  70833. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  70834. /* If pFrom->pSelect!=0 it means we are dealing with a
  70835. ** view within a view. The SELECT structure has already been
  70836. ** copied by the outer view so we can skip the copy step here
  70837. ** in the inner view.
  70838. */
  70839. if( pFrom->pSelect==0 ){
  70840. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
  70841. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  70842. }
  70843. }
  70844. #endif
  70845. }
  70846. /* Locate the index named by the INDEXED BY clause, if any. */
  70847. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  70848. return WRC_Abort;
  70849. }
  70850. }
  70851. /* Process NATURAL keywords, and ON and USING clauses of joins.
  70852. */
  70853. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  70854. return WRC_Abort;
  70855. }
  70856. /* For every "*" that occurs in the column list, insert the names of
  70857. ** all columns in all tables. And for every TABLE.* insert the names
  70858. ** of all columns in TABLE. The parser inserted a special expression
  70859. ** with the TK_ALL operator for each "*" that it found in the column list.
  70860. ** The following code just has to locate the TK_ALL expressions and expand
  70861. ** each one to the list of all columns in all tables.
  70862. **
  70863. ** The first loop just checks to see if there are any "*" operators
  70864. ** that need expanding.
  70865. */
  70866. for(k=0; k<pEList->nExpr; k++){
  70867. Expr *pE = pEList->a[k].pExpr;
  70868. if( pE->op==TK_ALL ) break;
  70869. if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
  70870. && pE->pLeft && pE->pLeft->op==TK_ID ) break;
  70871. }
  70872. if( k<pEList->nExpr ){
  70873. /*
  70874. ** If we get here it means the result set contains one or more "*"
  70875. ** operators that need to be expanded. Loop through each expression
  70876. ** in the result set and expand them one by one.
  70877. */
  70878. struct ExprList_item *a = pEList->a;
  70879. ExprList *pNew = 0;
  70880. int flags = pParse->db->flags;
  70881. int longNames = (flags & SQLITE_FullColNames)!=0
  70882. && (flags & SQLITE_ShortColNames)==0;
  70883. for(k=0; k<pEList->nExpr; k++){
  70884. Expr *pE = a[k].pExpr;
  70885. if( pE->op!=TK_ALL &&
  70886. (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
  70887. /* This particular expression does not need to be expanded.
  70888. */
  70889. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
  70890. if( pNew ){
  70891. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  70892. }
  70893. a[k].pExpr = 0;
  70894. a[k].zName = 0;
  70895. }else{
  70896. /* This expression is a "*" or a "TABLE.*" and needs to be
  70897. ** expanded. */
  70898. int tableSeen = 0; /* Set to 1 when TABLE matches */
  70899. char *zTName; /* text of name of TABLE */
  70900. if( pE->op==TK_DOT && pE->pLeft ){
  70901. zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
  70902. }else{
  70903. zTName = 0;
  70904. }
  70905. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  70906. Table *pTab = pFrom->pTab;
  70907. char *zTabName = pFrom->zAlias;
  70908. if( zTabName==0 || zTabName[0]==0 ){
  70909. zTabName = pTab->zName;
  70910. }
  70911. if( db->mallocFailed ) break;
  70912. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  70913. continue;
  70914. }
  70915. tableSeen = 1;
  70916. for(j=0; j<pTab->nCol; j++){
  70917. Expr *pExpr, *pRight;
  70918. char *zName = pTab->aCol[j].zName;
  70919. /* If a column is marked as 'hidden' (currently only possible
  70920. ** for virtual tables), do not include it in the expanded
  70921. ** result-set list.
  70922. */
  70923. if( IsHiddenColumn(&pTab->aCol[j]) ){
  70924. assert(IsVirtual(pTab));
  70925. continue;
  70926. }
  70927. if( i>0 && zTName==0 ){
  70928. struct SrcList_item *pLeft = &pTabList->a[i-1];
  70929. if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
  70930. columnIndex(pLeft->pTab, zName)>=0 ){
  70931. /* In a NATURAL join, omit the join columns from the
  70932. ** table on the right */
  70933. continue;
  70934. }
  70935. if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
  70936. /* In a join with a USING clause, omit columns in the
  70937. ** using clause from the table on the right. */
  70938. continue;
  70939. }
  70940. }
  70941. pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  70942. if( pRight==0 ) break;
  70943. setQuotedToken(pParse, &pRight->token, zName);
  70944. if( longNames || pTabList->nSrc>1 ){
  70945. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  70946. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  70947. if( pExpr==0 ) break;
  70948. setQuotedToken(pParse, &pLeft->token, zTabName);
  70949. setToken(&pExpr->span,
  70950. sqlite3MPrintf(db, "%s.%s", zTabName, zName));
  70951. pExpr->span.dyn = 1;
  70952. pExpr->token.z = 0;
  70953. pExpr->token.n = 0;
  70954. pExpr->token.dyn = 0;
  70955. }else{
  70956. pExpr = pRight;
  70957. pExpr->span = pExpr->token;
  70958. pExpr->span.dyn = 0;
  70959. }
  70960. if( longNames ){
  70961. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
  70962. }else{
  70963. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
  70964. }
  70965. }
  70966. }
  70967. if( !tableSeen ){
  70968. if( zTName ){
  70969. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  70970. }else{
  70971. sqlite3ErrorMsg(pParse, "no tables specified");
  70972. }
  70973. }
  70974. sqlite3DbFree(db, zTName);
  70975. }
  70976. }
  70977. sqlite3ExprListDelete(db, pEList);
  70978. p->pEList = pNew;
  70979. }
  70980. #if SQLITE_MAX_COLUMN
  70981. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  70982. sqlite3ErrorMsg(pParse, "too many columns in result set");
  70983. }
  70984. #endif
  70985. return WRC_Continue;
  70986. }
  70987. /*
  70988. ** No-op routine for the parse-tree walker.
  70989. **
  70990. ** When this routine is the Walker.xExprCallback then expression trees
  70991. ** are walked without any actions being taken at each node. Presumably,
  70992. ** when this routine is used for Walker.xExprCallback then
  70993. ** Walker.xSelectCallback is set to do something useful for every
  70994. ** subquery in the parser tree.
  70995. */
  70996. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  70997. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  70998. return WRC_Continue;
  70999. }
  71000. /*
  71001. ** This routine "expands" a SELECT statement and all of its subqueries.
  71002. ** For additional information on what it means to "expand" a SELECT
  71003. ** statement, see the comment on the selectExpand worker callback above.
  71004. **
  71005. ** Expanding a SELECT statement is the first step in processing a
  71006. ** SELECT statement. The SELECT statement must be expanded before
  71007. ** name resolution is performed.
  71008. **
  71009. ** If anything goes wrong, an error message is written into pParse.
  71010. ** The calling function can detect the problem by looking at pParse->nErr
  71011. ** and/or pParse->db->mallocFailed.
  71012. */
  71013. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  71014. Walker w;
  71015. w.xSelectCallback = selectExpander;
  71016. w.xExprCallback = exprWalkNoop;
  71017. w.pParse = pParse;
  71018. sqlite3WalkSelect(&w, pSelect);
  71019. }
  71020. #ifndef SQLITE_OMIT_SUBQUERY
  71021. /*
  71022. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  71023. ** interface.
  71024. **
  71025. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  71026. ** information to the Table structure that represents the result set
  71027. ** of that subquery.
  71028. **
  71029. ** The Table structure that represents the result set was constructed
  71030. ** by selectExpander() but the type and collation information was omitted
  71031. ** at that point because identifiers had not yet been resolved. This
  71032. ** routine is called after identifier resolution.
  71033. */
  71034. static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  71035. Parse *pParse;
  71036. int i;
  71037. SrcList *pTabList;
  71038. struct SrcList_item *pFrom;
  71039. assert( p->selFlags & SF_Resolved );
  71040. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  71041. p->selFlags |= SF_HasTypeInfo;
  71042. pParse = pWalker->pParse;
  71043. pTabList = p->pSrc;
  71044. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  71045. Table *pTab = pFrom->pTab;
  71046. if( pTab && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  71047. /* A sub-query in the FROM clause of a SELECT */
  71048. Select *pSel = pFrom->pSelect;
  71049. assert( pSel );
  71050. while( pSel->pPrior ) pSel = pSel->pPrior;
  71051. selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
  71052. }
  71053. }
  71054. }
  71055. return WRC_Continue;
  71056. }
  71057. #endif
  71058. /*
  71059. ** This routine adds datatype and collating sequence information to
  71060. ** the Table structures of all FROM-clause subqueries in a
  71061. ** SELECT statement.
  71062. **
  71063. ** Use this routine after name resolution.
  71064. */
  71065. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  71066. #ifndef SQLITE_OMIT_SUBQUERY
  71067. Walker w;
  71068. w.xSelectCallback = selectAddSubqueryTypeInfo;
  71069. w.xExprCallback = exprWalkNoop;
  71070. w.pParse = pParse;
  71071. sqlite3WalkSelect(&w, pSelect);
  71072. #endif
  71073. }
  71074. /*
  71075. ** This routine sets of a SELECT statement for processing. The
  71076. ** following is accomplished:
  71077. **
  71078. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  71079. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  71080. ** * ON and USING clauses are shifted into WHERE statements
  71081. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  71082. ** * Identifiers in expression are matched to tables.
  71083. **
  71084. ** This routine acts recursively on all subqueries within the SELECT.
  71085. */
  71086. SQLITE_PRIVATE void sqlite3SelectPrep(
  71087. Parse *pParse, /* The parser context */
  71088. Select *p, /* The SELECT statement being coded. */
  71089. NameContext *pOuterNC /* Name context for container */
  71090. ){
  71091. sqlite3 *db;
  71092. if( p==0 ) return;
  71093. db = pParse->db;
  71094. if( p->selFlags & SF_HasTypeInfo ) return;
  71095. if( pParse->nErr || db->mallocFailed ) return;
  71096. sqlite3SelectExpand(pParse, p);
  71097. if( pParse->nErr || db->mallocFailed ) return;
  71098. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  71099. if( pParse->nErr || db->mallocFailed ) return;
  71100. sqlite3SelectAddTypeInfo(pParse, p);
  71101. }
  71102. /*
  71103. ** Reset the aggregate accumulator.
  71104. **
  71105. ** The aggregate accumulator is a set of memory cells that hold
  71106. ** intermediate results while calculating an aggregate. This
  71107. ** routine simply stores NULLs in all of those memory cells.
  71108. */
  71109. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  71110. Vdbe *v = pParse->pVdbe;
  71111. int i;
  71112. struct AggInfo_func *pFunc;
  71113. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  71114. return;
  71115. }
  71116. for(i=0; i<pAggInfo->nColumn; i++){
  71117. sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  71118. }
  71119. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  71120. sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  71121. if( pFunc->iDistinct>=0 ){
  71122. Expr *pE = pFunc->pExpr;
  71123. if( pE->pList==0 || pE->pList->nExpr!=1 ){
  71124. sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
  71125. "by an expression");
  71126. pFunc->iDistinct = -1;
  71127. }else{
  71128. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
  71129. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  71130. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  71131. }
  71132. }
  71133. }
  71134. }
  71135. /*
  71136. ** Invoke the OP_AggFinalize opcode for every aggregate function
  71137. ** in the AggInfo structure.
  71138. */
  71139. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  71140. Vdbe *v = pParse->pVdbe;
  71141. int i;
  71142. struct AggInfo_func *pF;
  71143. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  71144. ExprList *pList = pF->pExpr->pList;
  71145. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  71146. (void*)pF->pFunc, P4_FUNCDEF);
  71147. }
  71148. }
  71149. /*
  71150. ** Update the accumulator memory cells for an aggregate based on
  71151. ** the current cursor position.
  71152. */
  71153. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  71154. Vdbe *v = pParse->pVdbe;
  71155. int i;
  71156. struct AggInfo_func *pF;
  71157. struct AggInfo_col *pC;
  71158. pAggInfo->directMode = 1;
  71159. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  71160. int nArg;
  71161. int addrNext = 0;
  71162. int regAgg;
  71163. ExprList *pList = pF->pExpr->pList;
  71164. if( pList ){
  71165. nArg = pList->nExpr;
  71166. regAgg = sqlite3GetTempRange(pParse, nArg);
  71167. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
  71168. }else{
  71169. nArg = 0;
  71170. regAgg = 0;
  71171. }
  71172. if( pF->iDistinct>=0 ){
  71173. addrNext = sqlite3VdbeMakeLabel(v);
  71174. assert( nArg==1 );
  71175. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  71176. }
  71177. if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  71178. CollSeq *pColl = 0;
  71179. struct ExprList_item *pItem;
  71180. int j;
  71181. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  71182. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  71183. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  71184. }
  71185. if( !pColl ){
  71186. pColl = pParse->db->pDfltColl;
  71187. }
  71188. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  71189. }
  71190. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  71191. (void*)pF->pFunc, P4_FUNCDEF);
  71192. sqlite3VdbeChangeP5(v, (u8)nArg);
  71193. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  71194. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  71195. if( addrNext ){
  71196. sqlite3VdbeResolveLabel(v, addrNext);
  71197. }
  71198. }
  71199. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  71200. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  71201. }
  71202. pAggInfo->directMode = 0;
  71203. }
  71204. /*
  71205. ** Generate code for the SELECT statement given in the p argument.
  71206. **
  71207. ** The results are distributed in various ways depending on the
  71208. ** contents of the SelectDest structure pointed to by argument pDest
  71209. ** as follows:
  71210. **
  71211. ** pDest->eDest Result
  71212. ** ------------ -------------------------------------------
  71213. ** SRT_Output Generate a row of output (using the OP_ResultRow
  71214. ** opcode) for each row in the result set.
  71215. **
  71216. ** SRT_Mem Only valid if the result is a single column.
  71217. ** Store the first column of the first result row
  71218. ** in register pDest->iParm then abandon the rest
  71219. ** of the query. This destination implies "LIMIT 1".
  71220. **
  71221. ** SRT_Set The result must be a single column. Store each
  71222. ** row of result as the key in table pDest->iParm.
  71223. ** Apply the affinity pDest->affinity before storing
  71224. ** results. Used to implement "IN (SELECT ...)".
  71225. **
  71226. ** SRT_Union Store results as a key in a temporary table pDest->iParm.
  71227. **
  71228. ** SRT_Except Remove results from the temporary table pDest->iParm.
  71229. **
  71230. ** SRT_Table Store results in temporary table pDest->iParm.
  71231. ** This is like SRT_EphemTab except that the table
  71232. ** is assumed to already be open.
  71233. **
  71234. ** SRT_EphemTab Create an temporary table pDest->iParm and store
  71235. ** the result there. The cursor is left open after
  71236. ** returning. This is like SRT_Table except that
  71237. ** this destination uses OP_OpenEphemeral to create
  71238. ** the table first.
  71239. **
  71240. ** SRT_Coroutine Generate a co-routine that returns a new row of
  71241. ** results each time it is invoked. The entry point
  71242. ** of the co-routine is stored in register pDest->iParm.
  71243. **
  71244. ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result
  71245. ** set is not empty.
  71246. **
  71247. ** SRT_Discard Throw the results away. This is used by SELECT
  71248. ** statements within triggers whose only purpose is
  71249. ** the side-effects of functions.
  71250. **
  71251. ** This routine returns the number of errors. If any errors are
  71252. ** encountered, then an appropriate error message is left in
  71253. ** pParse->zErrMsg.
  71254. **
  71255. ** This routine does NOT free the Select structure passed in. The
  71256. ** calling function needs to do that.
  71257. */
  71258. SQLITE_PRIVATE int sqlite3Select(
  71259. Parse *pParse, /* The parser context */
  71260. Select *p, /* The SELECT statement being coded. */
  71261. SelectDest *pDest /* What to do with the query results */
  71262. ){
  71263. int i, j; /* Loop counters */
  71264. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  71265. Vdbe *v; /* The virtual machine under construction */
  71266. int isAgg; /* True for select lists like "count(*)" */
  71267. ExprList *pEList; /* List of columns to extract. */
  71268. SrcList *pTabList; /* List of tables to select from */
  71269. Expr *pWhere; /* The WHERE clause. May be NULL */
  71270. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  71271. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  71272. Expr *pHaving; /* The HAVING clause. May be NULL */
  71273. int isDistinct; /* True if the DISTINCT keyword is present */
  71274. int distinct; /* Table to use for the distinct set */
  71275. int rc = 1; /* Value to return from this function */
  71276. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  71277. AggInfo sAggInfo; /* Information used by aggregate queries */
  71278. int iEnd; /* Address of the end of the query */
  71279. sqlite3 *db; /* The database connection */
  71280. db = pParse->db;
  71281. if( p==0 || db->mallocFailed || pParse->nErr ){
  71282. return 1;
  71283. }
  71284. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  71285. memset(&sAggInfo, 0, sizeof(sAggInfo));
  71286. pOrderBy = p->pOrderBy;
  71287. if( IgnorableOrderby(pDest) ){
  71288. p->pOrderBy = 0;
  71289. /* In these cases the DISTINCT operator makes no difference to the
  71290. ** results, so remove it if it were specified.
  71291. */
  71292. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  71293. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  71294. p->selFlags &= ~SF_Distinct;
  71295. }
  71296. sqlite3SelectPrep(pParse, p, 0);
  71297. pTabList = p->pSrc;
  71298. pEList = p->pEList;
  71299. if( pParse->nErr || db->mallocFailed ){
  71300. goto select_end;
  71301. }
  71302. p->pOrderBy = pOrderBy;
  71303. isAgg = (p->selFlags & SF_Aggregate)!=0;
  71304. if( pEList==0 ) goto select_end;
  71305. /*
  71306. ** Do not even attempt to generate any code if we have already seen
  71307. ** errors before this routine starts.
  71308. */
  71309. if( pParse->nErr>0 ) goto select_end;
  71310. /* ORDER BY is ignored for some destinations.
  71311. */
  71312. if( IgnorableOrderby(pDest) ){
  71313. pOrderBy = 0;
  71314. }
  71315. /* Begin generating code.
  71316. */
  71317. v = sqlite3GetVdbe(pParse);
  71318. if( v==0 ) goto select_end;
  71319. /* Generate code for all sub-queries in the FROM clause
  71320. */
  71321. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  71322. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  71323. struct SrcList_item *pItem = &pTabList->a[i];
  71324. SelectDest dest;
  71325. Select *pSub = pItem->pSelect;
  71326. int isAggSub;
  71327. if( pSub==0 || pItem->isPopulated ) continue;
  71328. /* Increment Parse.nHeight by the height of the largest expression
  71329. ** tree refered to by this, the parent select. The child select
  71330. ** may contain expression trees of at most
  71331. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  71332. ** more conservative than necessary, but much easier than enforcing
  71333. ** an exact limit.
  71334. */
  71335. pParse->nHeight += sqlite3SelectExprHeight(p);
  71336. /* Check to see if the subquery can be absorbed into the parent. */
  71337. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  71338. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  71339. if( isAggSub ){
  71340. isAgg = 1;
  71341. p->selFlags |= SF_Aggregate;
  71342. }
  71343. i = -1;
  71344. }else{
  71345. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  71346. assert( pItem->isPopulated==0 );
  71347. sqlite3Select(pParse, pSub, &dest);
  71348. pItem->isPopulated = 1;
  71349. }
  71350. if( pParse->nErr || db->mallocFailed ){
  71351. goto select_end;
  71352. }
  71353. pParse->nHeight -= sqlite3SelectExprHeight(p);
  71354. pTabList = p->pSrc;
  71355. if( !IgnorableOrderby(pDest) ){
  71356. pOrderBy = p->pOrderBy;
  71357. }
  71358. }
  71359. pEList = p->pEList;
  71360. #endif
  71361. pWhere = p->pWhere;
  71362. pGroupBy = p->pGroupBy;
  71363. pHaving = p->pHaving;
  71364. isDistinct = (p->selFlags & SF_Distinct)!=0;
  71365. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  71366. /* If there is are a sequence of queries, do the earlier ones first.
  71367. */
  71368. if( p->pPrior ){
  71369. if( p->pRightmost==0 ){
  71370. Select *pLoop, *pRight = 0;
  71371. int cnt = 0;
  71372. int mxSelect;
  71373. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  71374. pLoop->pRightmost = p;
  71375. pLoop->pNext = pRight;
  71376. pRight = pLoop;
  71377. }
  71378. mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  71379. if( mxSelect && cnt>mxSelect ){
  71380. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  71381. return 1;
  71382. }
  71383. }
  71384. return multiSelect(pParse, p, pDest);
  71385. }
  71386. #endif
  71387. /* If writing to memory or generating a set
  71388. ** only a single column may be output.
  71389. */
  71390. #ifndef SQLITE_OMIT_SUBQUERY
  71391. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  71392. goto select_end;
  71393. }
  71394. #endif
  71395. /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
  71396. ** GROUP BY might use an index, DISTINCT never does.
  71397. */
  71398. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && !p->pGroupBy ){
  71399. p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
  71400. pGroupBy = p->pGroupBy;
  71401. p->selFlags &= ~SF_Distinct;
  71402. isDistinct = 0;
  71403. }
  71404. /* If there is an ORDER BY clause, then this sorting
  71405. ** index might end up being unused if the data can be
  71406. ** extracted in pre-sorted order. If that is the case, then the
  71407. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  71408. ** we figure out that the sorting index is not needed. The addrSortIndex
  71409. ** variable is used to facilitate that change.
  71410. */
  71411. if( pOrderBy ){
  71412. KeyInfo *pKeyInfo;
  71413. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  71414. pOrderBy->iECursor = pParse->nTab++;
  71415. p->addrOpenEphm[2] = addrSortIndex =
  71416. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  71417. pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  71418. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  71419. }else{
  71420. addrSortIndex = -1;
  71421. }
  71422. /* If the output is destined for a temporary table, open that table.
  71423. */
  71424. if( pDest->eDest==SRT_EphemTab ){
  71425. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
  71426. }
  71427. /* Set the limiter.
  71428. */
  71429. iEnd = sqlite3VdbeMakeLabel(v);
  71430. computeLimitRegisters(pParse, p, iEnd);
  71431. /* Open a virtual index to use for the distinct set.
  71432. */
  71433. if( isDistinct ){
  71434. KeyInfo *pKeyInfo;
  71435. assert( isAgg || pGroupBy );
  71436. distinct = pParse->nTab++;
  71437. pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
  71438. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
  71439. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  71440. }else{
  71441. distinct = -1;
  71442. }
  71443. /* Aggregate and non-aggregate queries are handled differently */
  71444. if( !isAgg && pGroupBy==0 ){
  71445. /* This case is for non-aggregate queries
  71446. ** Begin the database scan
  71447. */
  71448. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0, 0);
  71449. if( pWInfo==0 ) goto select_end;
  71450. /* If sorting index that was created by a prior OP_OpenEphemeral
  71451. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  71452. ** into an OP_Noop.
  71453. */
  71454. if( addrSortIndex>=0 && pOrderBy==0 ){
  71455. sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
  71456. p->addrOpenEphm[2] = -1;
  71457. }
  71458. /* Use the standard inner loop
  71459. */
  71460. assert(!isDistinct);
  71461. selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
  71462. pWInfo->iContinue, pWInfo->iBreak);
  71463. /* End the database scan loop.
  71464. */
  71465. sqlite3WhereEnd(pWInfo);
  71466. }else{
  71467. /* This is the processing for aggregate queries */
  71468. NameContext sNC; /* Name context for processing aggregate information */
  71469. int iAMem; /* First Mem address for storing current GROUP BY */
  71470. int iBMem; /* First Mem address for previous GROUP BY */
  71471. int iUseFlag; /* Mem address holding flag indicating that at least
  71472. ** one row of the input to the aggregator has been
  71473. ** processed */
  71474. int iAbortFlag; /* Mem address which causes query abort if positive */
  71475. int groupBySort; /* Rows come from source in GROUP BY order */
  71476. int addrEnd; /* End of processing for this SELECT */
  71477. /* Remove any and all aliases between the result set and the
  71478. ** GROUP BY clause.
  71479. */
  71480. if( pGroupBy ){
  71481. int k; /* Loop counter */
  71482. struct ExprList_item *pItem; /* For looping over expression in a list */
  71483. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  71484. pItem->iAlias = 0;
  71485. }
  71486. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  71487. pItem->iAlias = 0;
  71488. }
  71489. }
  71490. /* Create a label to jump to when we want to abort the query */
  71491. addrEnd = sqlite3VdbeMakeLabel(v);
  71492. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  71493. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  71494. ** SELECT statement.
  71495. */
  71496. memset(&sNC, 0, sizeof(sNC));
  71497. sNC.pParse = pParse;
  71498. sNC.pSrcList = pTabList;
  71499. sNC.pAggInfo = &sAggInfo;
  71500. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  71501. sAggInfo.pGroupBy = pGroupBy;
  71502. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  71503. sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  71504. if( pHaving ){
  71505. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  71506. }
  71507. sAggInfo.nAccumulator = sAggInfo.nColumn;
  71508. for(i=0; i<sAggInfo.nFunc; i++){
  71509. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
  71510. }
  71511. if( db->mallocFailed ) goto select_end;
  71512. /* Processing for aggregates with GROUP BY is very different and
  71513. ** much more complex than aggregates without a GROUP BY.
  71514. */
  71515. if( pGroupBy ){
  71516. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  71517. int j1; /* A-vs-B comparision jump */
  71518. int addrOutputRow; /* Start of subroutine that outputs a result row */
  71519. int regOutputRow; /* Return address register for output subroutine */
  71520. int addrSetAbort; /* Set the abort flag and return */
  71521. int addrTopOfLoop; /* Top of the input loop */
  71522. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  71523. int addrReset; /* Subroutine for resetting the accumulator */
  71524. int regReset; /* Return address register for reset subroutine */
  71525. /* If there is a GROUP BY clause we might need a sorting index to
  71526. ** implement it. Allocate that sorting index now. If it turns out
  71527. ** that we do not need it after all, the OpenEphemeral instruction
  71528. ** will be converted into a Noop.
  71529. */
  71530. sAggInfo.sortingIdx = pParse->nTab++;
  71531. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  71532. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  71533. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  71534. 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  71535. /* Initialize memory locations used by GROUP BY aggregate processing
  71536. */
  71537. iUseFlag = ++pParse->nMem;
  71538. iAbortFlag = ++pParse->nMem;
  71539. regOutputRow = ++pParse->nMem;
  71540. addrOutputRow = sqlite3VdbeMakeLabel(v);
  71541. regReset = ++pParse->nMem;
  71542. addrReset = sqlite3VdbeMakeLabel(v);
  71543. iAMem = pParse->nMem + 1;
  71544. pParse->nMem += pGroupBy->nExpr;
  71545. iBMem = pParse->nMem + 1;
  71546. pParse->nMem += pGroupBy->nExpr;
  71547. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  71548. VdbeComment((v, "clear abort flag"));
  71549. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  71550. VdbeComment((v, "indicate accumulator empty"));
  71551. /* Begin a loop that will extract all source rows in GROUP BY order.
  71552. ** This might involve two separate loops with an OP_Sort in between, or
  71553. ** it might be a single loop that uses an index to extract information
  71554. ** in the right order to begin with.
  71555. */
  71556. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  71557. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
  71558. if( pWInfo==0 ) goto select_end;
  71559. if( pGroupBy==0 ){
  71560. /* The optimizer is able to deliver rows in group by order so
  71561. ** we do not have to sort. The OP_OpenEphemeral table will be
  71562. ** cancelled later because we still need to use the pKeyInfo
  71563. */
  71564. pGroupBy = p->pGroupBy;
  71565. groupBySort = 0;
  71566. }else{
  71567. /* Rows are coming out in undetermined order. We have to push
  71568. ** each row into a sorting index, terminate the first loop,
  71569. ** then loop over the sorting index in order to get the output
  71570. ** in sorted order
  71571. */
  71572. int regBase;
  71573. int regRecord;
  71574. int nCol;
  71575. int nGroupBy;
  71576. groupBySort = 1;
  71577. nGroupBy = pGroupBy->nExpr;
  71578. nCol = nGroupBy + 1;
  71579. j = nGroupBy+1;
  71580. for(i=0; i<sAggInfo.nColumn; i++){
  71581. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  71582. nCol++;
  71583. j++;
  71584. }
  71585. }
  71586. regBase = sqlite3GetTempRange(pParse, nCol);
  71587. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  71588. sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  71589. j = nGroupBy+1;
  71590. for(i=0; i<sAggInfo.nColumn; i++){
  71591. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  71592. if( pCol->iSorterColumn>=j ){
  71593. int r1 = j + regBase;
  71594. int r2;
  71595. r2 = sqlite3ExprCodeGetColumn(pParse,
  71596. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  71597. if( r1!=r2 ){
  71598. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  71599. }
  71600. j++;
  71601. }
  71602. }
  71603. regRecord = sqlite3GetTempReg(pParse);
  71604. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  71605. sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
  71606. sqlite3ReleaseTempReg(pParse, regRecord);
  71607. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  71608. sqlite3WhereEnd(pWInfo);
  71609. sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
  71610. VdbeComment((v, "GROUP BY sort"));
  71611. sAggInfo.useSortingIdx = 1;
  71612. }
  71613. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  71614. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  71615. ** Then compare the current GROUP BY terms against the GROUP BY terms
  71616. ** from the previous row currently stored in a0, a1, a2...
  71617. */
  71618. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  71619. for(j=0; j<pGroupBy->nExpr; j++){
  71620. if( groupBySort ){
  71621. sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
  71622. }else{
  71623. sAggInfo.directMode = 1;
  71624. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  71625. }
  71626. }
  71627. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  71628. (char*)pKeyInfo, P4_KEYINFO);
  71629. j1 = sqlite3VdbeCurrentAddr(v);
  71630. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  71631. /* Generate code that runs whenever the GROUP BY changes.
  71632. ** Changes in the GROUP BY are detected by the previous code
  71633. ** block. If there were no changes, this block is skipped.
  71634. **
  71635. ** This code copies current group by terms in b0,b1,b2,...
  71636. ** over to a0,a1,a2. It then calls the output subroutine
  71637. ** and resets the aggregate accumulator registers in preparation
  71638. ** for the next GROUP BY batch.
  71639. */
  71640. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  71641. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  71642. VdbeComment((v, "output one row"));
  71643. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  71644. VdbeComment((v, "check abort flag"));
  71645. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  71646. VdbeComment((v, "reset accumulator"));
  71647. /* Update the aggregate accumulators based on the content of
  71648. ** the current row
  71649. */
  71650. sqlite3VdbeJumpHere(v, j1);
  71651. updateAccumulator(pParse, &sAggInfo);
  71652. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  71653. VdbeComment((v, "indicate data in accumulator"));
  71654. /* End of the loop
  71655. */
  71656. if( groupBySort ){
  71657. sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
  71658. }else{
  71659. sqlite3WhereEnd(pWInfo);
  71660. sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
  71661. }
  71662. /* Output the final row of result
  71663. */
  71664. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  71665. VdbeComment((v, "output final row"));
  71666. /* Jump over the subroutines
  71667. */
  71668. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  71669. /* Generate a subroutine that outputs a single row of the result
  71670. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  71671. ** is less than or equal to zero, the subroutine is a no-op. If
  71672. ** the processing calls for the query to abort, this subroutine
  71673. ** increments the iAbortFlag memory location before returning in
  71674. ** order to signal the caller to abort.
  71675. */
  71676. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  71677. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  71678. VdbeComment((v, "set abort flag"));
  71679. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  71680. sqlite3VdbeResolveLabel(v, addrOutputRow);
  71681. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  71682. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  71683. VdbeComment((v, "Groupby result generator entry point"));
  71684. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  71685. finalizeAggFunctions(pParse, &sAggInfo);
  71686. if( pHaving ){
  71687. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  71688. }
  71689. selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  71690. distinct, pDest,
  71691. addrOutputRow+1, addrSetAbort);
  71692. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  71693. VdbeComment((v, "end groupby result generator"));
  71694. /* Generate a subroutine that will reset the group-by accumulator
  71695. */
  71696. sqlite3VdbeResolveLabel(v, addrReset);
  71697. resetAccumulator(pParse, &sAggInfo);
  71698. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  71699. } /* endif pGroupBy */
  71700. else {
  71701. ExprList *pMinMax = 0;
  71702. ExprList *pDel = 0;
  71703. u8 flag;
  71704. /* Check if the query is of one of the following forms:
  71705. **
  71706. ** SELECT min(x) FROM ...
  71707. ** SELECT max(x) FROM ...
  71708. **
  71709. ** If it is, then ask the code in where.c to attempt to sort results
  71710. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  71711. ** If where.c is able to produce results sorted in this order, then
  71712. ** add vdbe code to break out of the processing loop after the
  71713. ** first iteration (since the first iteration of the loop is
  71714. ** guaranteed to operate on the row with the minimum or maximum
  71715. ** value of x, the only row required).
  71716. **
  71717. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  71718. ** modify behaviour as follows:
  71719. **
  71720. ** + If the query is a "SELECT min(x)", then the loop coded by
  71721. ** where.c should not iterate over any values with a NULL value
  71722. ** for x.
  71723. **
  71724. ** + The optimizer code in where.c (the thing that decides which
  71725. ** index or indices to use) should place a different priority on
  71726. ** satisfying the 'ORDER BY' clause than it does in other cases.
  71727. ** Refer to code and comments in where.c for details.
  71728. */
  71729. flag = minMaxQuery(p);
  71730. if( flag ){
  71731. pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
  71732. if( pMinMax && !db->mallocFailed ){
  71733. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  71734. pMinMax->a[0].pExpr->op = TK_COLUMN;
  71735. }
  71736. }
  71737. /* This case runs if the aggregate has no GROUP BY clause. The
  71738. ** processing is much simpler since there is only a single row
  71739. ** of output.
  71740. */
  71741. resetAccumulator(pParse, &sAggInfo);
  71742. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag, 0);
  71743. if( pWInfo==0 ){
  71744. sqlite3ExprListDelete(db, pDel);
  71745. goto select_end;
  71746. }
  71747. updateAccumulator(pParse, &sAggInfo);
  71748. if( !pMinMax && flag ){
  71749. sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
  71750. VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max")));
  71751. }
  71752. sqlite3WhereEnd(pWInfo);
  71753. finalizeAggFunctions(pParse, &sAggInfo);
  71754. pOrderBy = 0;
  71755. if( pHaving ){
  71756. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  71757. }
  71758. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
  71759. pDest, addrEnd, addrEnd);
  71760. sqlite3ExprListDelete(db, pDel);
  71761. }
  71762. sqlite3VdbeResolveLabel(v, addrEnd);
  71763. } /* endif aggregate query */
  71764. /* If there is an ORDER BY clause, then we need to sort the results
  71765. ** and send them to the callback one by one.
  71766. */
  71767. if( pOrderBy ){
  71768. generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  71769. }
  71770. /* Jump here to skip this query
  71771. */
  71772. sqlite3VdbeResolveLabel(v, iEnd);
  71773. /* The SELECT was successfully coded. Set the return code to 0
  71774. ** to indicate no errors.
  71775. */
  71776. rc = 0;
  71777. /* Control jumps to here if an error is encountered above, or upon
  71778. ** successful coding of the SELECT.
  71779. */
  71780. select_end:
  71781. /* Identify column names if results of the SELECT are to be output.
  71782. */
  71783. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  71784. generateColumnNames(pParse, pTabList, pEList);
  71785. }
  71786. sqlite3DbFree(db, sAggInfo.aCol);
  71787. sqlite3DbFree(db, sAggInfo.aFunc);
  71788. return rc;
  71789. }
  71790. #if defined(SQLITE_DEBUG)
  71791. /*
  71792. *******************************************************************************
  71793. ** The following code is used for testing and debugging only. The code
  71794. ** that follows does not appear in normal builds.
  71795. **
  71796. ** These routines are used to print out the content of all or part of a
  71797. ** parse structures such as Select or Expr. Such printouts are useful
  71798. ** for helping to understand what is happening inside the code generator
  71799. ** during the execution of complex SELECT statements.
  71800. **
  71801. ** These routine are not called anywhere from within the normal
  71802. ** code base. Then are intended to be called from within the debugger
  71803. ** or from temporary "printf" statements inserted for debugging.
  71804. */
  71805. SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
  71806. if( p->token.z && p->token.n>0 ){
  71807. sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
  71808. }else{
  71809. sqlite3DebugPrintf("(%d", p->op);
  71810. }
  71811. if( p->pLeft ){
  71812. sqlite3DebugPrintf(" ");
  71813. sqlite3PrintExpr(p->pLeft);
  71814. }
  71815. if( p->pRight ){
  71816. sqlite3DebugPrintf(" ");
  71817. sqlite3PrintExpr(p->pRight);
  71818. }
  71819. sqlite3DebugPrintf(")");
  71820. }
  71821. SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
  71822. int i;
  71823. for(i=0; i<pList->nExpr; i++){
  71824. sqlite3PrintExpr(pList->a[i].pExpr);
  71825. if( i<pList->nExpr-1 ){
  71826. sqlite3DebugPrintf(", ");
  71827. }
  71828. }
  71829. }
  71830. SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
  71831. sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
  71832. sqlite3PrintExprList(p->pEList);
  71833. sqlite3DebugPrintf("\n");
  71834. if( p->pSrc ){
  71835. char *zPrefix;
  71836. int i;
  71837. zPrefix = "FROM";
  71838. for(i=0; i<p->pSrc->nSrc; i++){
  71839. struct SrcList_item *pItem = &p->pSrc->a[i];
  71840. sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
  71841. zPrefix = "";
  71842. if( pItem->pSelect ){
  71843. sqlite3DebugPrintf("(\n");
  71844. sqlite3PrintSelect(pItem->pSelect, indent+10);
  71845. sqlite3DebugPrintf("%*s)", indent+8, "");
  71846. }else if( pItem->zName ){
  71847. sqlite3DebugPrintf("%s", pItem->zName);
  71848. }
  71849. if( pItem->pTab ){
  71850. sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
  71851. }
  71852. if( pItem->zAlias ){
  71853. sqlite3DebugPrintf(" AS %s", pItem->zAlias);
  71854. }
  71855. if( i<p->pSrc->nSrc-1 ){
  71856. sqlite3DebugPrintf(",");
  71857. }
  71858. sqlite3DebugPrintf("\n");
  71859. }
  71860. }
  71861. if( p->pWhere ){
  71862. sqlite3DebugPrintf("%*s WHERE ", indent, "");
  71863. sqlite3PrintExpr(p->pWhere);
  71864. sqlite3DebugPrintf("\n");
  71865. }
  71866. if( p->pGroupBy ){
  71867. sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
  71868. sqlite3PrintExprList(p->pGroupBy);
  71869. sqlite3DebugPrintf("\n");
  71870. }
  71871. if( p->pHaving ){
  71872. sqlite3DebugPrintf("%*s HAVING ", indent, "");
  71873. sqlite3PrintExpr(p->pHaving);
  71874. sqlite3DebugPrintf("\n");
  71875. }
  71876. if( p->pOrderBy ){
  71877. sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
  71878. sqlite3PrintExprList(p->pOrderBy);
  71879. sqlite3DebugPrintf("\n");
  71880. }
  71881. }
  71882. /* End of the structure debug printing code
  71883. *****************************************************************************/
  71884. #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  71885. /************** End of select.c **********************************************/
  71886. /************** Begin file table.c *******************************************/
  71887. /*
  71888. ** 2001 September 15
  71889. **
  71890. ** The author disclaims copyright to this source code. In place of
  71891. ** a legal notice, here is a blessing:
  71892. **
  71893. ** May you do good and not evil.
  71894. ** May you find forgiveness for yourself and forgive others.
  71895. ** May you share freely, never taking more than you give.
  71896. **
  71897. *************************************************************************
  71898. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  71899. ** interface routines. These are just wrappers around the main
  71900. ** interface routine of sqlite3_exec().
  71901. **
  71902. ** These routines are in a separate files so that they will not be linked
  71903. ** if they are not used.
  71904. **
  71905. ** $Id: table.c,v 1.38 2008/12/10 19:26:24 drh Exp $
  71906. */
  71907. #ifndef SQLITE_OMIT_GET_TABLE
  71908. /*
  71909. ** This structure is used to pass data from sqlite3_get_table() through
  71910. ** to the callback function is uses to build the result.
  71911. */
  71912. typedef struct TabResult {
  71913. char **azResult;
  71914. char *zErrMsg;
  71915. int nResult;
  71916. int nAlloc;
  71917. int nRow;
  71918. int nColumn;
  71919. int nData;
  71920. int rc;
  71921. } TabResult;
  71922. /*
  71923. ** This routine is called once for each row in the result table. Its job
  71924. ** is to fill in the TabResult structure appropriately, allocating new
  71925. ** memory as necessary.
  71926. */
  71927. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  71928. TabResult *p = (TabResult*)pArg;
  71929. int need;
  71930. int i;
  71931. char *z;
  71932. /* Make sure there is enough space in p->azResult to hold everything
  71933. ** we need to remember from this invocation of the callback.
  71934. */
  71935. if( p->nRow==0 && argv!=0 ){
  71936. need = nCol*2;
  71937. }else{
  71938. need = nCol;
  71939. }
  71940. if( p->nData + need >= p->nAlloc ){
  71941. char **azNew;
  71942. p->nAlloc = p->nAlloc*2 + need + 1;
  71943. azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
  71944. if( azNew==0 ) goto malloc_failed;
  71945. p->azResult = azNew;
  71946. }
  71947. /* If this is the first row, then generate an extra row containing
  71948. ** the names of all columns.
  71949. */
  71950. if( p->nRow==0 ){
  71951. p->nColumn = nCol;
  71952. for(i=0; i<nCol; i++){
  71953. z = sqlite3_mprintf("%s", colv[i]);
  71954. if( z==0 ) goto malloc_failed;
  71955. p->azResult[p->nData++] = z;
  71956. }
  71957. }else if( p->nColumn!=nCol ){
  71958. sqlite3_free(p->zErrMsg);
  71959. p->zErrMsg = sqlite3_mprintf(
  71960. "sqlite3_get_table() called with two or more incompatible queries"
  71961. );
  71962. p->rc = SQLITE_ERROR;
  71963. return 1;
  71964. }
  71965. /* Copy over the row data
  71966. */
  71967. if( argv!=0 ){
  71968. for(i=0; i<nCol; i++){
  71969. if( argv[i]==0 ){
  71970. z = 0;
  71971. }else{
  71972. int n = sqlite3Strlen30(argv[i])+1;
  71973. z = sqlite3_malloc( n );
  71974. if( z==0 ) goto malloc_failed;
  71975. memcpy(z, argv[i], n);
  71976. }
  71977. p->azResult[p->nData++] = z;
  71978. }
  71979. p->nRow++;
  71980. }
  71981. return 0;
  71982. malloc_failed:
  71983. p->rc = SQLITE_NOMEM;
  71984. return 1;
  71985. }
  71986. /*
  71987. ** Query the database. But instead of invoking a callback for each row,
  71988. ** malloc() for space to hold the result and return the entire results
  71989. ** at the conclusion of the call.
  71990. **
  71991. ** The result that is written to ***pazResult is held in memory obtained
  71992. ** from malloc(). But the caller cannot free this memory directly.
  71993. ** Instead, the entire table should be passed to sqlite3_free_table() when
  71994. ** the calling procedure is finished using it.
  71995. */
  71996. SQLITE_API int sqlite3_get_table(
  71997. sqlite3 *db, /* The database on which the SQL executes */
  71998. const char *zSql, /* The SQL to be executed */
  71999. char ***pazResult, /* Write the result table here */
  72000. int *pnRow, /* Write the number of rows in the result here */
  72001. int *pnColumn, /* Write the number of columns of result here */
  72002. char **pzErrMsg /* Write error messages here */
  72003. ){
  72004. int rc;
  72005. TabResult res;
  72006. *pazResult = 0;
  72007. if( pnColumn ) *pnColumn = 0;
  72008. if( pnRow ) *pnRow = 0;
  72009. res.zErrMsg = 0;
  72010. res.nResult = 0;
  72011. res.nRow = 0;
  72012. res.nColumn = 0;
  72013. res.nData = 1;
  72014. res.nAlloc = 20;
  72015. res.rc = SQLITE_OK;
  72016. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  72017. if( res.azResult==0 ){
  72018. db->errCode = SQLITE_NOMEM;
  72019. return SQLITE_NOMEM;
  72020. }
  72021. res.azResult[0] = 0;
  72022. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  72023. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  72024. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  72025. if( (rc&0xff)==SQLITE_ABORT ){
  72026. sqlite3_free_table(&res.azResult[1]);
  72027. if( res.zErrMsg ){
  72028. if( pzErrMsg ){
  72029. sqlite3_free(*pzErrMsg);
  72030. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  72031. }
  72032. sqlite3_free(res.zErrMsg);
  72033. }
  72034. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  72035. return res.rc;
  72036. }
  72037. sqlite3_free(res.zErrMsg);
  72038. if( rc!=SQLITE_OK ){
  72039. sqlite3_free_table(&res.azResult[1]);
  72040. return rc;
  72041. }
  72042. if( res.nAlloc>res.nData ){
  72043. char **azNew;
  72044. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
  72045. if( azNew==0 ){
  72046. sqlite3_free_table(&res.azResult[1]);
  72047. db->errCode = SQLITE_NOMEM;
  72048. return SQLITE_NOMEM;
  72049. }
  72050. res.nAlloc = res.nData+1;
  72051. res.azResult = azNew;
  72052. }
  72053. *pazResult = &res.azResult[1];
  72054. if( pnColumn ) *pnColumn = res.nColumn;
  72055. if( pnRow ) *pnRow = res.nRow;
  72056. return rc;
  72057. }
  72058. /*
  72059. ** This routine frees the space the sqlite3_get_table() malloced.
  72060. */
  72061. SQLITE_API void sqlite3_free_table(
  72062. char **azResult /* Result returned from from sqlite3_get_table() */
  72063. ){
  72064. if( azResult ){
  72065. int i, n;
  72066. azResult--;
  72067. assert( azResult!=0 );
  72068. n = SQLITE_PTR_TO_INT(azResult[0]);
  72069. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  72070. sqlite3_free(azResult);
  72071. }
  72072. }
  72073. #endif /* SQLITE_OMIT_GET_TABLE */
  72074. /************** End of table.c ***********************************************/
  72075. /************** Begin file trigger.c *****************************************/
  72076. /*
  72077. **
  72078. ** The author disclaims copyright to this source code. In place of
  72079. ** a legal notice, here is a blessing:
  72080. **
  72081. ** May you do good and not evil.
  72082. ** May you find forgiveness for yourself and forgive others.
  72083. ** May you share freely, never taking more than you give.
  72084. **
  72085. *************************************************************************
  72086. **
  72087. **
  72088. ** $Id: trigger.c,v 1.133 2008/12/26 07:56:39 danielk1977 Exp $
  72089. */
  72090. #ifndef SQLITE_OMIT_TRIGGER
  72091. /*
  72092. ** Delete a linked list of TriggerStep structures.
  72093. */
  72094. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  72095. while( pTriggerStep ){
  72096. TriggerStep * pTmp = pTriggerStep;
  72097. pTriggerStep = pTriggerStep->pNext;
  72098. if( pTmp->target.dyn ) sqlite3DbFree(db, (char*)pTmp->target.z);
  72099. sqlite3ExprDelete(db, pTmp->pWhere);
  72100. sqlite3ExprListDelete(db, pTmp->pExprList);
  72101. sqlite3SelectDelete(db, pTmp->pSelect);
  72102. sqlite3IdListDelete(db, pTmp->pIdList);
  72103. sqlite3DbFree(db, pTmp);
  72104. }
  72105. }
  72106. /*
  72107. ** This is called by the parser when it sees a CREATE TRIGGER statement
  72108. ** up to the point of the BEGIN before the trigger actions. A Trigger
  72109. ** structure is generated based on the information available and stored
  72110. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  72111. ** sqlite3FinishTrigger() function is called to complete the trigger
  72112. ** construction process.
  72113. */
  72114. SQLITE_PRIVATE void sqlite3BeginTrigger(
  72115. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  72116. Token *pName1, /* The name of the trigger */
  72117. Token *pName2, /* The name of the trigger */
  72118. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  72119. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  72120. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  72121. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  72122. Expr *pWhen, /* WHEN clause */
  72123. int isTemp, /* True if the TEMPORARY keyword is present */
  72124. int noErr /* Suppress errors if the trigger already exists */
  72125. ){
  72126. Trigger *pTrigger = 0;
  72127. Table *pTab;
  72128. char *zName = 0; /* Name of the trigger */
  72129. sqlite3 *db = pParse->db;
  72130. int iDb; /* The database to store the trigger in */
  72131. Token *pName; /* The unqualified db name */
  72132. DbFixer sFix;
  72133. int iTabDb;
  72134. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  72135. assert( pName2!=0 );
  72136. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  72137. assert( op>0 && op<0xff );
  72138. if( isTemp ){
  72139. /* If TEMP was specified, then the trigger name may not be qualified. */
  72140. if( pName2->n>0 ){
  72141. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  72142. goto trigger_cleanup;
  72143. }
  72144. iDb = 1;
  72145. pName = pName1;
  72146. }else{
  72147. /* Figure out the db that the the trigger will be created in */
  72148. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  72149. if( iDb<0 ){
  72150. goto trigger_cleanup;
  72151. }
  72152. }
  72153. /* If the trigger name was unqualified, and the table is a temp table,
  72154. ** then set iDb to 1 to create the trigger in the temporary database.
  72155. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  72156. ** exist, the error is caught by the block below.
  72157. */
  72158. if( !pTableName || db->mallocFailed ){
  72159. goto trigger_cleanup;
  72160. }
  72161. pTab = sqlite3SrcListLookup(pParse, pTableName);
  72162. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  72163. iDb = 1;
  72164. }
  72165. /* Ensure the table name matches database name and that the table exists */
  72166. if( db->mallocFailed ) goto trigger_cleanup;
  72167. assert( pTableName->nSrc==1 );
  72168. if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
  72169. sqlite3FixSrcList(&sFix, pTableName) ){
  72170. goto trigger_cleanup;
  72171. }
  72172. pTab = sqlite3SrcListLookup(pParse, pTableName);
  72173. if( !pTab ){
  72174. /* The table does not exist. */
  72175. goto trigger_cleanup;
  72176. }
  72177. if( IsVirtual(pTab) ){
  72178. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  72179. goto trigger_cleanup;
  72180. }
  72181. /* Check that the trigger name is not reserved and that no trigger of the
  72182. ** specified name exists */
  72183. zName = sqlite3NameFromToken(db, pName);
  72184. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  72185. goto trigger_cleanup;
  72186. }
  72187. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  72188. zName, sqlite3Strlen30(zName)) ){
  72189. if( !noErr ){
  72190. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  72191. }
  72192. goto trigger_cleanup;
  72193. }
  72194. /* Do not create a trigger on a system table */
  72195. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  72196. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  72197. pParse->nErr++;
  72198. goto trigger_cleanup;
  72199. }
  72200. /* INSTEAD of triggers are only for views and views only support INSTEAD
  72201. ** of triggers.
  72202. */
  72203. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  72204. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  72205. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  72206. goto trigger_cleanup;
  72207. }
  72208. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  72209. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  72210. " trigger on table: %S", pTableName, 0);
  72211. goto trigger_cleanup;
  72212. }
  72213. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  72214. #ifndef SQLITE_OMIT_AUTHORIZATION
  72215. {
  72216. int code = SQLITE_CREATE_TRIGGER;
  72217. const char *zDb = db->aDb[iTabDb].zName;
  72218. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  72219. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  72220. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  72221. goto trigger_cleanup;
  72222. }
  72223. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  72224. goto trigger_cleanup;
  72225. }
  72226. }
  72227. #endif
  72228. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  72229. ** cannot appear on views. So we might as well translate every
  72230. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  72231. ** elsewhere.
  72232. */
  72233. if (tr_tm == TK_INSTEAD){
  72234. tr_tm = TK_BEFORE;
  72235. }
  72236. /* Build the Trigger object */
  72237. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  72238. if( pTrigger==0 ) goto trigger_cleanup;
  72239. pTrigger->name = zName;
  72240. zName = 0;
  72241. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  72242. pTrigger->pSchema = db->aDb[iDb].pSchema;
  72243. pTrigger->pTabSchema = pTab->pSchema;
  72244. pTrigger->op = (u8)op;
  72245. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  72246. pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
  72247. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  72248. sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
  72249. assert( pParse->pNewTrigger==0 );
  72250. pParse->pNewTrigger = pTrigger;
  72251. trigger_cleanup:
  72252. sqlite3DbFree(db, zName);
  72253. sqlite3SrcListDelete(db, pTableName);
  72254. sqlite3IdListDelete(db, pColumns);
  72255. sqlite3ExprDelete(db, pWhen);
  72256. if( !pParse->pNewTrigger ){
  72257. sqlite3DeleteTrigger(db, pTrigger);
  72258. }else{
  72259. assert( pParse->pNewTrigger==pTrigger );
  72260. }
  72261. }
  72262. /*
  72263. ** This routine is called after all of the trigger actions have been parsed
  72264. ** in order to complete the process of building the trigger.
  72265. */
  72266. SQLITE_PRIVATE void sqlite3FinishTrigger(
  72267. Parse *pParse, /* Parser context */
  72268. TriggerStep *pStepList, /* The triggered program */
  72269. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  72270. ){
  72271. Trigger *pTrig = 0; /* The trigger whose construction is finishing up */
  72272. sqlite3 *db = pParse->db; /* The database */
  72273. DbFixer sFix;
  72274. int iDb; /* Database containing the trigger */
  72275. pTrig = pParse->pNewTrigger;
  72276. pParse->pNewTrigger = 0;
  72277. if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
  72278. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  72279. pTrig->step_list = pStepList;
  72280. while( pStepList ){
  72281. pStepList->pTrig = pTrig;
  72282. pStepList = pStepList->pNext;
  72283. }
  72284. if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken)
  72285. && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
  72286. goto triggerfinish_cleanup;
  72287. }
  72288. /* if we are not initializing, and this trigger is not on a TEMP table,
  72289. ** build the sqlite_master entry
  72290. */
  72291. if( !db->init.busy ){
  72292. Vdbe *v;
  72293. char *z;
  72294. /* Make an entry in the sqlite_master table */
  72295. v = sqlite3GetVdbe(pParse);
  72296. if( v==0 ) goto triggerfinish_cleanup;
  72297. sqlite3BeginWriteOperation(pParse, 0, iDb);
  72298. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  72299. sqlite3NestedParse(pParse,
  72300. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  72301. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrig->name,
  72302. pTrig->table, z);
  72303. sqlite3DbFree(db, z);
  72304. sqlite3ChangeCookie(pParse, iDb);
  72305. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
  72306. db, "type='trigger' AND name='%q'", pTrig->name), P4_DYNAMIC
  72307. );
  72308. }
  72309. if( db->init.busy ){
  72310. int n;
  72311. Table *pTab;
  72312. Trigger *pDel;
  72313. pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash,
  72314. pTrig->name, sqlite3Strlen30(pTrig->name), pTrig);
  72315. if( pDel ){
  72316. assert( pDel==pTrig );
  72317. db->mallocFailed = 1;
  72318. goto triggerfinish_cleanup;
  72319. }
  72320. n = sqlite3Strlen30(pTrig->table) + 1;
  72321. pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
  72322. assert( pTab!=0 );
  72323. pTrig->pNext = pTab->pTrigger;
  72324. pTab->pTrigger = pTrig;
  72325. pTrig = 0;
  72326. }
  72327. triggerfinish_cleanup:
  72328. sqlite3DeleteTrigger(db, pTrig);
  72329. assert( !pParse->pNewTrigger );
  72330. sqlite3DeleteTriggerStep(db, pStepList);
  72331. }
  72332. /*
  72333. ** Make a copy of all components of the given trigger step. This has
  72334. ** the effect of copying all Expr.token.z values into memory obtained
  72335. ** from sqlite3_malloc(). As initially created, the Expr.token.z values
  72336. ** all point to the input string that was fed to the parser. But that
  72337. ** string is ephemeral - it will go away as soon as the sqlite3_exec()
  72338. ** call that started the parser exits. This routine makes a persistent
  72339. ** copy of all the Expr.token.z strings so that the TriggerStep structure
  72340. ** will be valid even after the sqlite3_exec() call returns.
  72341. */
  72342. static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
  72343. if( p->target.z ){
  72344. p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
  72345. p->target.dyn = 1;
  72346. }
  72347. if( p->pSelect ){
  72348. Select *pNew = sqlite3SelectDup(db, p->pSelect);
  72349. sqlite3SelectDelete(db, p->pSelect);
  72350. p->pSelect = pNew;
  72351. }
  72352. if( p->pWhere ){
  72353. Expr *pNew = sqlite3ExprDup(db, p->pWhere);
  72354. sqlite3ExprDelete(db, p->pWhere);
  72355. p->pWhere = pNew;
  72356. }
  72357. if( p->pExprList ){
  72358. ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
  72359. sqlite3ExprListDelete(db, p->pExprList);
  72360. p->pExprList = pNew;
  72361. }
  72362. if( p->pIdList ){
  72363. IdList *pNew = sqlite3IdListDup(db, p->pIdList);
  72364. sqlite3IdListDelete(db, p->pIdList);
  72365. p->pIdList = pNew;
  72366. }
  72367. }
  72368. /*
  72369. ** Turn a SELECT statement (that the pSelect parameter points to) into
  72370. ** a trigger step. Return a pointer to a TriggerStep structure.
  72371. **
  72372. ** The parser calls this routine when it finds a SELECT statement in
  72373. ** body of a TRIGGER.
  72374. */
  72375. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  72376. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  72377. if( pTriggerStep==0 ) {
  72378. sqlite3SelectDelete(db, pSelect);
  72379. return 0;
  72380. }
  72381. pTriggerStep->op = TK_SELECT;
  72382. pTriggerStep->pSelect = pSelect;
  72383. pTriggerStep->orconf = OE_Default;
  72384. sqlitePersistTriggerStep(db, pTriggerStep);
  72385. return pTriggerStep;
  72386. }
  72387. /*
  72388. ** Build a trigger step out of an INSERT statement. Return a pointer
  72389. ** to the new trigger step.
  72390. **
  72391. ** The parser calls this routine when it sees an INSERT inside the
  72392. ** body of a trigger.
  72393. */
  72394. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  72395. sqlite3 *db, /* The database connection */
  72396. Token *pTableName, /* Name of the table into which we insert */
  72397. IdList *pColumn, /* List of columns in pTableName to insert into */
  72398. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  72399. Select *pSelect, /* A SELECT statement that supplies values */
  72400. int orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  72401. ){
  72402. TriggerStep *pTriggerStep;
  72403. assert(pEList == 0 || pSelect == 0);
  72404. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  72405. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  72406. if( pTriggerStep ){
  72407. pTriggerStep->op = TK_INSERT;
  72408. pTriggerStep->pSelect = pSelect;
  72409. pTriggerStep->target = *pTableName;
  72410. pTriggerStep->pIdList = pColumn;
  72411. pTriggerStep->pExprList = pEList;
  72412. pTriggerStep->orconf = orconf;
  72413. sqlitePersistTriggerStep(db, pTriggerStep);
  72414. }else{
  72415. sqlite3IdListDelete(db, pColumn);
  72416. sqlite3ExprListDelete(db, pEList);
  72417. sqlite3SelectDelete(db, pSelect);
  72418. }
  72419. return pTriggerStep;
  72420. }
  72421. /*
  72422. ** Construct a trigger step that implements an UPDATE statement and return
  72423. ** a pointer to that trigger step. The parser calls this routine when it
  72424. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  72425. */
  72426. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  72427. sqlite3 *db, /* The database connection */
  72428. Token *pTableName, /* Name of the table to be updated */
  72429. ExprList *pEList, /* The SET clause: list of column and new values */
  72430. Expr *pWhere, /* The WHERE clause */
  72431. int orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  72432. ){
  72433. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  72434. if( pTriggerStep==0 ){
  72435. sqlite3ExprListDelete(db, pEList);
  72436. sqlite3ExprDelete(db, pWhere);
  72437. return 0;
  72438. }
  72439. pTriggerStep->op = TK_UPDATE;
  72440. pTriggerStep->target = *pTableName;
  72441. pTriggerStep->pExprList = pEList;
  72442. pTriggerStep->pWhere = pWhere;
  72443. pTriggerStep->orconf = orconf;
  72444. sqlitePersistTriggerStep(db, pTriggerStep);
  72445. return pTriggerStep;
  72446. }
  72447. /*
  72448. ** Construct a trigger step that implements a DELETE statement and return
  72449. ** a pointer to that trigger step. The parser calls this routine when it
  72450. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  72451. */
  72452. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  72453. sqlite3 *db, /* Database connection */
  72454. Token *pTableName, /* The table from which rows are deleted */
  72455. Expr *pWhere /* The WHERE clause */
  72456. ){
  72457. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  72458. if( pTriggerStep==0 ){
  72459. sqlite3ExprDelete(db, pWhere);
  72460. return 0;
  72461. }
  72462. pTriggerStep->op = TK_DELETE;
  72463. pTriggerStep->target = *pTableName;
  72464. pTriggerStep->pWhere = pWhere;
  72465. pTriggerStep->orconf = OE_Default;
  72466. sqlitePersistTriggerStep(db, pTriggerStep);
  72467. return pTriggerStep;
  72468. }
  72469. /*
  72470. ** Recursively delete a Trigger structure
  72471. */
  72472. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  72473. if( pTrigger==0 ) return;
  72474. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  72475. sqlite3DbFree(db, pTrigger->name);
  72476. sqlite3DbFree(db, pTrigger->table);
  72477. sqlite3ExprDelete(db, pTrigger->pWhen);
  72478. sqlite3IdListDelete(db, pTrigger->pColumns);
  72479. if( pTrigger->nameToken.dyn ) sqlite3DbFree(db, (char*)pTrigger->nameToken.z);
  72480. sqlite3DbFree(db, pTrigger);
  72481. }
  72482. /*
  72483. ** This function is called to drop a trigger from the database schema.
  72484. **
  72485. ** This may be called directly from the parser and therefore identifies
  72486. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  72487. ** same job as this routine except it takes a pointer to the trigger
  72488. ** instead of the trigger name.
  72489. **/
  72490. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  72491. Trigger *pTrigger = 0;
  72492. int i;
  72493. const char *zDb;
  72494. const char *zName;
  72495. int nName;
  72496. sqlite3 *db = pParse->db;
  72497. if( db->mallocFailed ) goto drop_trigger_cleanup;
  72498. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  72499. goto drop_trigger_cleanup;
  72500. }
  72501. assert( pName->nSrc==1 );
  72502. zDb = pName->a[0].zDatabase;
  72503. zName = pName->a[0].zName;
  72504. nName = sqlite3Strlen30(zName);
  72505. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  72506. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  72507. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  72508. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  72509. if( pTrigger ) break;
  72510. }
  72511. if( !pTrigger ){
  72512. if( !noErr ){
  72513. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  72514. }
  72515. goto drop_trigger_cleanup;
  72516. }
  72517. sqlite3DropTriggerPtr(pParse, pTrigger);
  72518. drop_trigger_cleanup:
  72519. sqlite3SrcListDelete(db, pName);
  72520. }
  72521. /*
  72522. ** Return a pointer to the Table structure for the table that a trigger
  72523. ** is set on.
  72524. */
  72525. static Table *tableOfTrigger(Trigger *pTrigger){
  72526. int n = sqlite3Strlen30(pTrigger->table) + 1;
  72527. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  72528. }
  72529. /*
  72530. ** Drop a trigger given a pointer to that trigger.
  72531. */
  72532. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  72533. Table *pTable;
  72534. Vdbe *v;
  72535. sqlite3 *db = pParse->db;
  72536. int iDb;
  72537. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  72538. assert( iDb>=0 && iDb<db->nDb );
  72539. pTable = tableOfTrigger(pTrigger);
  72540. assert( pTable );
  72541. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  72542. #ifndef SQLITE_OMIT_AUTHORIZATION
  72543. {
  72544. int code = SQLITE_DROP_TRIGGER;
  72545. const char *zDb = db->aDb[iDb].zName;
  72546. const char *zTab = SCHEMA_TABLE(iDb);
  72547. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  72548. if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
  72549. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  72550. return;
  72551. }
  72552. }
  72553. #endif
  72554. /* Generate code to destroy the database record of the trigger.
  72555. */
  72556. assert( pTable!=0 );
  72557. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  72558. int base;
  72559. static const VdbeOpList dropTrigger[] = {
  72560. { OP_Rewind, 0, ADDR(9), 0},
  72561. { OP_String8, 0, 1, 0}, /* 1 */
  72562. { OP_Column, 0, 1, 2},
  72563. { OP_Ne, 2, ADDR(8), 1},
  72564. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  72565. { OP_Column, 0, 0, 2},
  72566. { OP_Ne, 2, ADDR(8), 1},
  72567. { OP_Delete, 0, 0, 0},
  72568. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  72569. };
  72570. sqlite3BeginWriteOperation(pParse, 0, iDb);
  72571. sqlite3OpenMasterTable(pParse, iDb);
  72572. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  72573. sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
  72574. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  72575. sqlite3ChangeCookie(pParse, iDb);
  72576. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  72577. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
  72578. }
  72579. }
  72580. /*
  72581. ** Remove a trigger from the hash tables of the sqlite* pointer.
  72582. */
  72583. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  72584. Trigger *pTrigger;
  72585. int nName = sqlite3Strlen30(zName);
  72586. pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
  72587. zName, nName, 0);
  72588. if( pTrigger ){
  72589. Table *pTable = tableOfTrigger(pTrigger);
  72590. assert( pTable!=0 );
  72591. if( pTable->pTrigger == pTrigger ){
  72592. pTable->pTrigger = pTrigger->pNext;
  72593. }else{
  72594. Trigger *cc = pTable->pTrigger;
  72595. while( cc ){
  72596. if( cc->pNext == pTrigger ){
  72597. cc->pNext = cc->pNext->pNext;
  72598. break;
  72599. }
  72600. cc = cc->pNext;
  72601. }
  72602. assert(cc);
  72603. }
  72604. sqlite3DeleteTrigger(db, pTrigger);
  72605. db->flags |= SQLITE_InternChanges;
  72606. }
  72607. }
  72608. /*
  72609. ** pEList is the SET clause of an UPDATE statement. Each entry
  72610. ** in pEList is of the format <id>=<expr>. If any of the entries
  72611. ** in pEList have an <id> which matches an identifier in pIdList,
  72612. ** then return TRUE. If pIdList==NULL, then it is considered a
  72613. ** wildcard that matches anything. Likewise if pEList==NULL then
  72614. ** it matches anything so always return true. Return false only
  72615. ** if there is no match.
  72616. */
  72617. static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
  72618. int e;
  72619. if( !pIdList || !pEList ) return 1;
  72620. for(e=0; e<pEList->nExpr; e++){
  72621. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  72622. }
  72623. return 0;
  72624. }
  72625. /*
  72626. ** Return a bit vector to indicate what kind of triggers exist for operation
  72627. ** "op" on table pTab. If pChanges is not NULL then it is a list of columns
  72628. ** that are being updated. Triggers only match if the ON clause of the
  72629. ** trigger definition overlaps the set of columns being updated.
  72630. **
  72631. ** The returned bit vector is some combination of TRIGGER_BEFORE and
  72632. ** TRIGGER_AFTER.
  72633. */
  72634. SQLITE_PRIVATE int sqlite3TriggersExist(
  72635. Table *pTab, /* The table the contains the triggers */
  72636. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  72637. ExprList *pChanges /* Columns that change in an UPDATE statement */
  72638. ){
  72639. Trigger *pTrigger;
  72640. int mask = 0;
  72641. pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
  72642. while( pTrigger ){
  72643. if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
  72644. mask |= pTrigger->tr_tm;
  72645. }
  72646. pTrigger = pTrigger->pNext;
  72647. }
  72648. return mask;
  72649. }
  72650. /*
  72651. ** Convert the pStep->target token into a SrcList and return a pointer
  72652. ** to that SrcList.
  72653. **
  72654. ** This routine adds a specific database name, if needed, to the target when
  72655. ** forming the SrcList. This prevents a trigger in one database from
  72656. ** referring to a target in another database. An exception is when the
  72657. ** trigger is in TEMP in which case it can refer to any other database it
  72658. ** wants.
  72659. */
  72660. static SrcList *targetSrcList(
  72661. Parse *pParse, /* The parsing context */
  72662. TriggerStep *pStep /* The trigger containing the target token */
  72663. ){
  72664. Token sDb; /* Dummy database name token */
  72665. int iDb; /* Index of the database to use */
  72666. SrcList *pSrc; /* SrcList to be returned */
  72667. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  72668. if( iDb==0 || iDb>=2 ){
  72669. assert( iDb<pParse->db->nDb );
  72670. sDb.z = (u8*)pParse->db->aDb[iDb].zName;
  72671. sDb.n = sqlite3Strlen30((char*)sDb.z);
  72672. pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
  72673. } else {
  72674. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  72675. }
  72676. return pSrc;
  72677. }
  72678. /*
  72679. ** Generate VDBE code for zero or more statements inside the body of a
  72680. ** trigger.
  72681. */
  72682. static int codeTriggerProgram(
  72683. Parse *pParse, /* The parser context */
  72684. TriggerStep *pStepList, /* List of statements inside the trigger body */
  72685. int orconfin /* Conflict algorithm. (OE_Abort, etc) */
  72686. ){
  72687. TriggerStep * pTriggerStep = pStepList;
  72688. int orconf;
  72689. Vdbe *v = pParse->pVdbe;
  72690. sqlite3 *db = pParse->db;
  72691. assert( pTriggerStep!=0 );
  72692. assert( v!=0 );
  72693. sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
  72694. VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
  72695. while( pTriggerStep ){
  72696. sqlite3ExprClearColumnCache(pParse, -1);
  72697. orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
  72698. pParse->trigStack->orconf = orconf;
  72699. switch( pTriggerStep->op ){
  72700. case TK_SELECT: {
  72701. Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
  72702. if( ss ){
  72703. SelectDest dest;
  72704. sqlite3SelectDestInit(&dest, SRT_Discard, 0);
  72705. sqlite3Select(pParse, ss, &dest);
  72706. sqlite3SelectDelete(db, ss);
  72707. }
  72708. break;
  72709. }
  72710. case TK_UPDATE: {
  72711. SrcList *pSrc;
  72712. pSrc = targetSrcList(pParse, pTriggerStep);
  72713. sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
  72714. sqlite3Update(pParse, pSrc,
  72715. sqlite3ExprListDup(db, pTriggerStep->pExprList),
  72716. sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
  72717. sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
  72718. break;
  72719. }
  72720. case TK_INSERT: {
  72721. SrcList *pSrc;
  72722. pSrc = targetSrcList(pParse, pTriggerStep);
  72723. sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
  72724. sqlite3Insert(pParse, pSrc,
  72725. sqlite3ExprListDup(db, pTriggerStep->pExprList),
  72726. sqlite3SelectDup(db, pTriggerStep->pSelect),
  72727. sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
  72728. sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
  72729. break;
  72730. }
  72731. case TK_DELETE: {
  72732. SrcList *pSrc;
  72733. sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
  72734. pSrc = targetSrcList(pParse, pTriggerStep);
  72735. sqlite3DeleteFrom(pParse, pSrc,
  72736. sqlite3ExprDup(db, pTriggerStep->pWhere));
  72737. sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
  72738. break;
  72739. }
  72740. default:
  72741. assert(0);
  72742. }
  72743. pTriggerStep = pTriggerStep->pNext;
  72744. }
  72745. sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
  72746. VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
  72747. return 0;
  72748. }
  72749. /*
  72750. ** This is called to code FOR EACH ROW triggers.
  72751. **
  72752. ** When the code that this function generates is executed, the following
  72753. ** must be true:
  72754. **
  72755. ** 1. No cursors may be open in the main database. (But newIdx and oldIdx
  72756. ** can be indices of cursors in temporary tables. See below.)
  72757. **
  72758. ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
  72759. ** a temporary vdbe cursor (index newIdx) must be open and pointing at
  72760. ** a row containing values to be substituted for new.* expressions in the
  72761. ** trigger program(s).
  72762. **
  72763. ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
  72764. ** a temporary vdbe cursor (index oldIdx) must be open and pointing at
  72765. ** a row containing values to be substituted for old.* expressions in the
  72766. ** trigger program(s).
  72767. **
  72768. ** If they are not NULL, the piOldColMask and piNewColMask output variables
  72769. ** are set to values that describe the columns used by the trigger program
  72770. ** in the OLD.* and NEW.* tables respectively. If column N of the
  72771. ** pseudo-table is read at least once, the corresponding bit of the output
  72772. ** mask is set. If a column with an index greater than 32 is read, the
  72773. ** output mask is set to the special value 0xffffffff.
  72774. **
  72775. */
  72776. SQLITE_PRIVATE int sqlite3CodeRowTrigger(
  72777. Parse *pParse, /* Parse context */
  72778. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  72779. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  72780. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  72781. Table *pTab, /* The table to code triggers from */
  72782. int newIdx, /* The indice of the "new" row to access */
  72783. int oldIdx, /* The indice of the "old" row to access */
  72784. int orconf, /* ON CONFLICT policy */
  72785. int ignoreJump, /* Instruction to jump to for RAISE(IGNORE) */
  72786. u32 *piOldColMask, /* OUT: Mask of columns used from the OLD.* table */
  72787. u32 *piNewColMask /* OUT: Mask of columns used from the NEW.* table */
  72788. ){
  72789. Trigger *p;
  72790. sqlite3 *db = pParse->db;
  72791. TriggerStack trigStackEntry;
  72792. trigStackEntry.oldColMask = 0;
  72793. trigStackEntry.newColMask = 0;
  72794. assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
  72795. assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
  72796. assert(newIdx != -1 || oldIdx != -1);
  72797. for(p=pTab->pTrigger; p; p=p->pNext){
  72798. int fire_this = 0;
  72799. /* Determine whether we should code this trigger */
  72800. if(
  72801. p->op==op &&
  72802. p->tr_tm==tr_tm &&
  72803. (p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
  72804. (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
  72805. ){
  72806. TriggerStack *pS; /* Pointer to trigger-stack entry */
  72807. for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
  72808. if( !pS ){
  72809. fire_this = 1;
  72810. }
  72811. #if 0 /* Give no warning for recursive triggers. Just do not do them */
  72812. else{
  72813. sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
  72814. p->name);
  72815. return SQLITE_ERROR;
  72816. }
  72817. #endif
  72818. }
  72819. if( fire_this ){
  72820. int endTrigger;
  72821. Expr * whenExpr;
  72822. AuthContext sContext;
  72823. NameContext sNC;
  72824. #ifndef SQLITE_OMIT_TRACE
  72825. sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
  72826. sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
  72827. P4_DYNAMIC);
  72828. #endif
  72829. memset(&sNC, 0, sizeof(sNC));
  72830. sNC.pParse = pParse;
  72831. /* Push an entry on to the trigger stack */
  72832. trigStackEntry.pTrigger = p;
  72833. trigStackEntry.newIdx = newIdx;
  72834. trigStackEntry.oldIdx = oldIdx;
  72835. trigStackEntry.pTab = pTab;
  72836. trigStackEntry.pNext = pParse->trigStack;
  72837. trigStackEntry.ignoreJump = ignoreJump;
  72838. pParse->trigStack = &trigStackEntry;
  72839. sqlite3AuthContextPush(pParse, &sContext, p->name);
  72840. /* code the WHEN clause */
  72841. endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
  72842. whenExpr = sqlite3ExprDup(db, p->pWhen);
  72843. if( db->mallocFailed || sqlite3ResolveExprNames(&sNC, whenExpr) ){
  72844. pParse->trigStack = trigStackEntry.pNext;
  72845. sqlite3ExprDelete(db, whenExpr);
  72846. return 1;
  72847. }
  72848. sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
  72849. sqlite3ExprDelete(db, whenExpr);
  72850. codeTriggerProgram(pParse, p->step_list, orconf);
  72851. /* Pop the entry off the trigger stack */
  72852. pParse->trigStack = trigStackEntry.pNext;
  72853. sqlite3AuthContextPop(&sContext);
  72854. sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
  72855. }
  72856. }
  72857. if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
  72858. if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
  72859. return 0;
  72860. }
  72861. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  72862. /************** End of trigger.c *********************************************/
  72863. /************** Begin file update.c ******************************************/
  72864. /*
  72865. ** 2001 September 15
  72866. **
  72867. ** The author disclaims copyright to this source code. In place of
  72868. ** a legal notice, here is a blessing:
  72869. **
  72870. ** May you do good and not evil.
  72871. ** May you find forgiveness for yourself and forgive others.
  72872. ** May you share freely, never taking more than you give.
  72873. **
  72874. *************************************************************************
  72875. ** This file contains C code routines that are called by the parser
  72876. ** to handle UPDATE statements.
  72877. **
  72878. ** $Id: update.c,v 1.191 2008/12/23 23:56:22 drh Exp $
  72879. */
  72880. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72881. /* Forward declaration */
  72882. static void updateVirtualTable(
  72883. Parse *pParse, /* The parsing context */
  72884. SrcList *pSrc, /* The virtual table to be modified */
  72885. Table *pTab, /* The virtual table */
  72886. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  72887. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  72888. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  72889. Expr *pWhere /* WHERE clause of the UPDATE statement */
  72890. );
  72891. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  72892. /*
  72893. ** The most recently coded instruction was an OP_Column to retrieve the
  72894. ** i-th column of table pTab. This routine sets the P4 parameter of the
  72895. ** OP_Column to the default value, if any.
  72896. **
  72897. ** The default value of a column is specified by a DEFAULT clause in the
  72898. ** column definition. This was either supplied by the user when the table
  72899. ** was created, or added later to the table definition by an ALTER TABLE
  72900. ** command. If the latter, then the row-records in the table btree on disk
  72901. ** may not contain a value for the column and the default value, taken
  72902. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  72903. ** If the former, then all row-records are guaranteed to include a value
  72904. ** for the column and the P4 value is not required.
  72905. **
  72906. ** Column definitions created by an ALTER TABLE command may only have
  72907. ** literal default values specified: a number, null or a string. (If a more
  72908. ** complicated default expression value was provided, it is evaluated
  72909. ** when the ALTER TABLE is executed and one of the literal values written
  72910. ** into the sqlite_master table.)
  72911. **
  72912. ** Therefore, the P4 parameter is only required if the default value for
  72913. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  72914. ** function is capable of transforming these types of expressions into
  72915. ** sqlite3_value objects.
  72916. */
  72917. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
  72918. if( pTab && !pTab->pSelect ){
  72919. sqlite3_value *pValue;
  72920. u8 enc = ENC(sqlite3VdbeDb(v));
  72921. Column *pCol = &pTab->aCol[i];
  72922. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  72923. assert( i<pTab->nCol );
  72924. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  72925. pCol->affinity, &pValue);
  72926. if( pValue ){
  72927. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  72928. }
  72929. }
  72930. }
  72931. /*
  72932. ** Process an UPDATE statement.
  72933. **
  72934. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  72935. ** \_______/ \________/ \______/ \________________/
  72936. * onError pTabList pChanges pWhere
  72937. */
  72938. SQLITE_PRIVATE void sqlite3Update(
  72939. Parse *pParse, /* The parser context */
  72940. SrcList *pTabList, /* The table in which we should change things */
  72941. ExprList *pChanges, /* Things to be changed */
  72942. Expr *pWhere, /* The WHERE clause. May be null */
  72943. int onError /* How to handle constraint errors */
  72944. ){
  72945. int i, j; /* Loop counters */
  72946. Table *pTab; /* The table to be updated */
  72947. int addr = 0; /* VDBE instruction address of the start of the loop */
  72948. WhereInfo *pWInfo; /* Information about the WHERE clause */
  72949. Vdbe *v; /* The virtual database engine */
  72950. Index *pIdx; /* For looping over indices */
  72951. int nIdx; /* Number of indices that need updating */
  72952. int iCur; /* VDBE Cursor number of pTab */
  72953. sqlite3 *db; /* The database structure */
  72954. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  72955. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  72956. ** an expression for the i-th column of the table.
  72957. ** aXRef[i]==-1 if the i-th column is not changed. */
  72958. int chngRowid; /* True if the record number is being changed */
  72959. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  72960. int openAll = 0; /* True if all indices need to be opened */
  72961. AuthContext sContext; /* The authorization context */
  72962. NameContext sNC; /* The name-context to resolve expressions in */
  72963. int iDb; /* Database containing the table being updated */
  72964. int j1; /* Addresses of jump instructions */
  72965. int okOnePass; /* True for one-pass algorithm without the FIFO */
  72966. #ifndef SQLITE_OMIT_TRIGGER
  72967. int isView; /* Trying to update a view */
  72968. int triggers_exist = 0; /* True if any row triggers exist */
  72969. #endif
  72970. int iBeginAfterTrigger = 0; /* Address of after trigger program */
  72971. int iEndAfterTrigger = 0; /* Exit of after trigger program */
  72972. int iBeginBeforeTrigger = 0; /* Address of before trigger program */
  72973. int iEndBeforeTrigger = 0; /* Exit of before trigger program */
  72974. u32 old_col_mask = 0; /* Mask of OLD.* columns in use */
  72975. u32 new_col_mask = 0; /* Mask of NEW.* columns in use */
  72976. int newIdx = -1; /* index of trigger "new" temp table */
  72977. int oldIdx = -1; /* index of trigger "old" temp table */
  72978. /* Register Allocations */
  72979. int regRowCount = 0; /* A count of rows changed */
  72980. int regOldRowid; /* The old rowid */
  72981. int regNewRowid; /* The new rowid */
  72982. int regData; /* New data for the row */
  72983. int regRowSet = 0; /* Rowset of rows to be updated */
  72984. sContext.pParse = 0;
  72985. db = pParse->db;
  72986. if( pParse->nErr || db->mallocFailed ){
  72987. goto update_cleanup;
  72988. }
  72989. assert( pTabList->nSrc==1 );
  72990. /* Locate the table which we want to update.
  72991. */
  72992. pTab = sqlite3SrcListLookup(pParse, pTabList);
  72993. if( pTab==0 ) goto update_cleanup;
  72994. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  72995. /* Figure out if we have any triggers and if the table being
  72996. ** updated is a view
  72997. */
  72998. #ifndef SQLITE_OMIT_TRIGGER
  72999. triggers_exist = sqlite3TriggersExist(pTab, TK_UPDATE, pChanges);
  73000. isView = pTab->pSelect!=0;
  73001. #else
  73002. # define triggers_exist 0
  73003. # define isView 0
  73004. #endif
  73005. #ifdef SQLITE_OMIT_VIEW
  73006. # undef isView
  73007. # define isView 0
  73008. #endif
  73009. if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
  73010. goto update_cleanup;
  73011. }
  73012. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  73013. goto update_cleanup;
  73014. }
  73015. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  73016. if( aXRef==0 ) goto update_cleanup;
  73017. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  73018. /* If there are FOR EACH ROW triggers, allocate cursors for the
  73019. ** special OLD and NEW tables
  73020. */
  73021. if( triggers_exist ){
  73022. newIdx = pParse->nTab++;
  73023. oldIdx = pParse->nTab++;
  73024. }
  73025. /* Allocate a cursors for the main database table and for all indices.
  73026. ** The index cursors might not be used, but if they are used they
  73027. ** need to occur right after the database cursor. So go ahead and
  73028. ** allocate enough space, just in case.
  73029. */
  73030. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  73031. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  73032. pParse->nTab++;
  73033. }
  73034. /* Initialize the name-context */
  73035. memset(&sNC, 0, sizeof(sNC));
  73036. sNC.pParse = pParse;
  73037. sNC.pSrcList = pTabList;
  73038. /* Resolve the column names in all the expressions of the
  73039. ** of the UPDATE statement. Also find the column index
  73040. ** for each column to be updated in the pChanges array. For each
  73041. ** column to be updated, make sure we have authorization to change
  73042. ** that column.
  73043. */
  73044. chngRowid = 0;
  73045. for(i=0; i<pChanges->nExpr; i++){
  73046. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  73047. goto update_cleanup;
  73048. }
  73049. for(j=0; j<pTab->nCol; j++){
  73050. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  73051. if( j==pTab->iPKey ){
  73052. chngRowid = 1;
  73053. pRowidExpr = pChanges->a[i].pExpr;
  73054. }
  73055. aXRef[j] = i;
  73056. break;
  73057. }
  73058. }
  73059. if( j>=pTab->nCol ){
  73060. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  73061. chngRowid = 1;
  73062. pRowidExpr = pChanges->a[i].pExpr;
  73063. }else{
  73064. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  73065. goto update_cleanup;
  73066. }
  73067. }
  73068. #ifndef SQLITE_OMIT_AUTHORIZATION
  73069. {
  73070. int rc;
  73071. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  73072. pTab->aCol[j].zName, db->aDb[iDb].zName);
  73073. if( rc==SQLITE_DENY ){
  73074. goto update_cleanup;
  73075. }else if( rc==SQLITE_IGNORE ){
  73076. aXRef[j] = -1;
  73077. }
  73078. }
  73079. #endif
  73080. }
  73081. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  73082. ** array for each index associated with table being updated. Fill in
  73083. ** the value with a register number for indices that are to be used
  73084. ** and with zero for unused indices.
  73085. */
  73086. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  73087. if( nIdx>0 ){
  73088. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  73089. if( aRegIdx==0 ) goto update_cleanup;
  73090. }
  73091. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  73092. int reg;
  73093. if( chngRowid ){
  73094. reg = ++pParse->nMem;
  73095. }else{
  73096. reg = 0;
  73097. for(i=0; i<pIdx->nColumn; i++){
  73098. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  73099. reg = ++pParse->nMem;
  73100. break;
  73101. }
  73102. }
  73103. }
  73104. aRegIdx[j] = reg;
  73105. }
  73106. /* Allocate a block of register used to store the change record
  73107. ** sent to sqlite3GenerateConstraintChecks(). There are either
  73108. ** one or two registers for holding the rowid. One rowid register
  73109. ** is used if chngRowid is false and two are used if chngRowid is
  73110. ** true. Following these are pTab->nCol register holding column
  73111. ** data.
  73112. */
  73113. regOldRowid = regNewRowid = pParse->nMem + 1;
  73114. pParse->nMem += pTab->nCol + 1;
  73115. if( chngRowid ){
  73116. regNewRowid++;
  73117. pParse->nMem++;
  73118. }
  73119. regData = regNewRowid+1;
  73120. /* Begin generating code.
  73121. */
  73122. v = sqlite3GetVdbe(pParse);
  73123. if( v==0 ) goto update_cleanup;
  73124. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  73125. sqlite3BeginWriteOperation(pParse, 1, iDb);
  73126. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73127. /* Virtual tables must be handled separately */
  73128. if( IsVirtual(pTab) ){
  73129. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  73130. pWhere);
  73131. pWhere = 0;
  73132. pTabList = 0;
  73133. goto update_cleanup;
  73134. }
  73135. #endif
  73136. /* Start the view context
  73137. */
  73138. if( isView ){
  73139. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  73140. }
  73141. /* Generate the code for triggers.
  73142. */
  73143. if( triggers_exist ){
  73144. int iGoto;
  73145. /* Create pseudo-tables for NEW and OLD
  73146. */
  73147. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
  73148. sqlite3VdbeAddOp2(v, OP_OpenPseudo, oldIdx, 0);
  73149. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
  73150. sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
  73151. iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  73152. addr = sqlite3VdbeMakeLabel(v);
  73153. iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
  73154. if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
  73155. newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
  73156. goto update_cleanup;
  73157. }
  73158. iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  73159. iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
  73160. if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab,
  73161. newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
  73162. goto update_cleanup;
  73163. }
  73164. iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  73165. sqlite3VdbeJumpHere(v, iGoto);
  73166. }
  73167. /* If we are trying to update a view, realize that view into
  73168. ** a ephemeral table.
  73169. */
  73170. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  73171. if( isView ){
  73172. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  73173. }
  73174. #endif
  73175. /* Resolve the column names in all the expressions in the
  73176. ** WHERE clause.
  73177. */
  73178. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  73179. goto update_cleanup;
  73180. }
  73181. /* Begin the database scan
  73182. */
  73183. sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
  73184. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
  73185. WHERE_ONEPASS_DESIRED, 0);
  73186. if( pWInfo==0 ) goto update_cleanup;
  73187. okOnePass = pWInfo->okOnePass;
  73188. /* Remember the rowid of every item to be updated.
  73189. */
  73190. sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
  73191. if( !okOnePass ){
  73192. regRowSet = ++pParse->nMem;
  73193. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  73194. }
  73195. /* End the database scan loop.
  73196. */
  73197. sqlite3WhereEnd(pWInfo);
  73198. /* Initialize the count of updated rows
  73199. */
  73200. if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
  73201. regRowCount = ++pParse->nMem;
  73202. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  73203. }
  73204. if( !isView && !IsVirtual(pTab) ){
  73205. /*
  73206. ** Open every index that needs updating. Note that if any
  73207. ** index could potentially invoke a REPLACE conflict resolution
  73208. ** action, then we need to open all indices because we might need
  73209. ** to be deleting some records.
  73210. */
  73211. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  73212. if( onError==OE_Replace ){
  73213. openAll = 1;
  73214. }else{
  73215. openAll = 0;
  73216. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  73217. if( pIdx->onError==OE_Replace ){
  73218. openAll = 1;
  73219. break;
  73220. }
  73221. }
  73222. }
  73223. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  73224. if( openAll || aRegIdx[i]>0 ){
  73225. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  73226. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  73227. (char*)pKey, P4_KEYINFO_HANDOFF);
  73228. assert( pParse->nTab>iCur+i+1 );
  73229. }
  73230. }
  73231. }
  73232. /* Jump back to this point if a trigger encounters an IGNORE constraint. */
  73233. if( triggers_exist ){
  73234. sqlite3VdbeResolveLabel(v, addr);
  73235. }
  73236. /* Top of the update loop */
  73237. if( okOnePass ){
  73238. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  73239. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  73240. sqlite3VdbeJumpHere(v, a1);
  73241. }else{
  73242. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  73243. }
  73244. if( triggers_exist ){
  73245. int regRowid;
  73246. int regRow;
  73247. int regCols;
  73248. /* Make cursor iCur point to the record that is being updated.
  73249. */
  73250. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  73251. /* Generate the OLD table
  73252. */
  73253. regRowid = sqlite3GetTempReg(pParse);
  73254. regRow = sqlite3GetTempReg(pParse);
  73255. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
  73256. if( !old_col_mask ){
  73257. sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
  73258. }else{
  73259. sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
  73260. }
  73261. sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
  73262. /* Generate the NEW table
  73263. */
  73264. if( chngRowid ){
  73265. sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
  73266. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  73267. }else{
  73268. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
  73269. }
  73270. regCols = sqlite3GetTempRange(pParse, pTab->nCol);
  73271. for(i=0; i<pTab->nCol; i++){
  73272. if( i==pTab->iPKey ){
  73273. sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
  73274. continue;
  73275. }
  73276. j = aXRef[i];
  73277. if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
  73278. if( j<0 ){
  73279. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
  73280. sqlite3ColumnDefault(v, pTab, i);
  73281. }else{
  73282. sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
  73283. }
  73284. }else{
  73285. sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
  73286. }
  73287. }
  73288. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
  73289. if( !isView ){
  73290. sqlite3TableAffinityStr(v, pTab);
  73291. sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol);
  73292. }
  73293. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
  73294. /* if( pParse->nErr ) goto update_cleanup; */
  73295. sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
  73296. sqlite3ReleaseTempReg(pParse, regRowid);
  73297. sqlite3ReleaseTempReg(pParse, regRow);
  73298. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
  73299. sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
  73300. }
  73301. if( !isView && !IsVirtual(pTab) ){
  73302. /* Loop over every record that needs updating. We have to load
  73303. ** the old data for each record to be updated because some columns
  73304. ** might not change and we will need to copy the old value.
  73305. ** Also, the old data is needed to delete the old index entries.
  73306. ** So make the cursor point at the old record.
  73307. */
  73308. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  73309. /* If the record number will change, push the record number as it
  73310. ** will be after the update. (The old record number is currently
  73311. ** on top of the stack.)
  73312. */
  73313. if( chngRowid ){
  73314. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  73315. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  73316. }
  73317. /* Compute new data for this record.
  73318. */
  73319. for(i=0; i<pTab->nCol; i++){
  73320. if( i==pTab->iPKey ){
  73321. sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
  73322. continue;
  73323. }
  73324. j = aXRef[i];
  73325. if( j<0 ){
  73326. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
  73327. sqlite3ColumnDefault(v, pTab, i);
  73328. }else{
  73329. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
  73330. }
  73331. }
  73332. /* Do constraint checks
  73333. */
  73334. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  73335. aRegIdx, chngRowid, 1,
  73336. onError, addr);
  73337. /* Delete the old indices for the current record.
  73338. */
  73339. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  73340. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  73341. /* If changing the record number, delete the old record.
  73342. */
  73343. if( chngRowid ){
  73344. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  73345. }
  73346. sqlite3VdbeJumpHere(v, j1);
  73347. /* Create the new index entries and the new record.
  73348. */
  73349. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid,
  73350. aRegIdx, 1, -1, 0);
  73351. }
  73352. /* Increment the row counter
  73353. */
  73354. if( db->flags & SQLITE_CountRows && !pParse->trigStack){
  73355. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  73356. }
  73357. /* If there are triggers, close all the cursors after each iteration
  73358. ** through the loop. The fire the after triggers.
  73359. */
  73360. if( triggers_exist ){
  73361. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
  73362. sqlite3VdbeJumpHere(v, iEndAfterTrigger);
  73363. }
  73364. /* Repeat the above with the next record to be updated, until
  73365. ** all record selected by the WHERE clause have been updated.
  73366. */
  73367. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  73368. sqlite3VdbeJumpHere(v, addr);
  73369. /* Close all tables */
  73370. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  73371. if( openAll || aRegIdx[i]>0 ){
  73372. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  73373. }
  73374. }
  73375. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  73376. if( triggers_exist ){
  73377. sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
  73378. sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
  73379. }
  73380. /*
  73381. ** Return the number of rows that were changed. If this routine is
  73382. ** generating code because of a call to sqlite3NestedParse(), do not
  73383. ** invoke the callback function.
  73384. */
  73385. if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
  73386. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  73387. sqlite3VdbeSetNumCols(v, 1);
  73388. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  73389. }
  73390. update_cleanup:
  73391. sqlite3AuthContextPop(&sContext);
  73392. sqlite3DbFree(db, aRegIdx);
  73393. sqlite3DbFree(db, aXRef);
  73394. sqlite3SrcListDelete(db, pTabList);
  73395. sqlite3ExprListDelete(db, pChanges);
  73396. sqlite3ExprDelete(db, pWhere);
  73397. return;
  73398. }
  73399. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73400. /*
  73401. ** Generate code for an UPDATE of a virtual table.
  73402. **
  73403. ** The strategy is that we create an ephemerial table that contains
  73404. ** for each row to be changed:
  73405. **
  73406. ** (A) The original rowid of that row.
  73407. ** (B) The revised rowid for the row. (note1)
  73408. ** (C) The content of every column in the row.
  73409. **
  73410. ** Then we loop over this ephemeral table and for each row in
  73411. ** the ephermeral table call VUpdate.
  73412. **
  73413. ** When finished, drop the ephemeral table.
  73414. **
  73415. ** (note1) Actually, if we know in advance that (A) is always the same
  73416. ** as (B) we only store (A), then duplicate (A) when pulling
  73417. ** it out of the ephemeral table before calling VUpdate.
  73418. */
  73419. static void updateVirtualTable(
  73420. Parse *pParse, /* The parsing context */
  73421. SrcList *pSrc, /* The virtual table to be modified */
  73422. Table *pTab, /* The virtual table */
  73423. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  73424. Expr *pRowid, /* Expression used to recompute the rowid */
  73425. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  73426. Expr *pWhere /* WHERE clause of the UPDATE statement */
  73427. ){
  73428. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  73429. ExprList *pEList = 0; /* The result set of the SELECT statement */
  73430. Select *pSelect = 0; /* The SELECT statement */
  73431. Expr *pExpr; /* Temporary expression */
  73432. int ephemTab; /* Table holding the result of the SELECT */
  73433. int i; /* Loop counter */
  73434. int addr; /* Address of top of loop */
  73435. int iReg; /* First register in set passed to OP_VUpdate */
  73436. sqlite3 *db = pParse->db; /* Database connection */
  73437. const char *pVtab = (const char*)pTab->pVtab;
  73438. SelectDest dest;
  73439. /* Construct the SELECT statement that will find the new values for
  73440. ** all updated rows.
  73441. */
  73442. pEList = sqlite3ExprListAppend(pParse, 0,
  73443. sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
  73444. if( pRowid ){
  73445. pEList = sqlite3ExprListAppend(pParse, pEList,
  73446. sqlite3ExprDup(db, pRowid), 0);
  73447. }
  73448. assert( pTab->iPKey<0 );
  73449. for(i=0; i<pTab->nCol; i++){
  73450. if( aXRef[i]>=0 ){
  73451. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr);
  73452. }else{
  73453. pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
  73454. }
  73455. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
  73456. }
  73457. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  73458. /* Create the ephemeral table into which the update results will
  73459. ** be stored.
  73460. */
  73461. assert( v );
  73462. ephemTab = pParse->nTab++;
  73463. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  73464. /* fill the ephemeral table
  73465. */
  73466. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  73467. sqlite3Select(pParse, pSelect, &dest);
  73468. /* Generate code to scan the ephemeral table and call VUpdate. */
  73469. iReg = ++pParse->nMem;
  73470. pParse->nMem += pTab->nCol+1;
  73471. sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  73472. addr = sqlite3VdbeCurrentAddr(v);
  73473. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  73474. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  73475. for(i=0; i<pTab->nCol; i++){
  73476. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  73477. }
  73478. sqlite3VtabMakeWritable(pParse, pTab);
  73479. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB);
  73480. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr);
  73481. sqlite3VdbeJumpHere(v, addr-1);
  73482. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  73483. /* Cleanup */
  73484. sqlite3SelectDelete(db, pSelect);
  73485. }
  73486. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73487. /* Make sure "isView" gets undefined in case this file becomes part of
  73488. ** the amalgamation - so that subsequent files do not see isView as a
  73489. ** macro. */
  73490. #undef isView
  73491. /************** End of update.c **********************************************/
  73492. /************** Begin file vacuum.c ******************************************/
  73493. /*
  73494. ** 2003 April 6
  73495. **
  73496. ** The author disclaims copyright to this source code. In place of
  73497. ** a legal notice, here is a blessing:
  73498. **
  73499. ** May you do good and not evil.
  73500. ** May you find forgiveness for yourself and forgive others.
  73501. ** May you share freely, never taking more than you give.
  73502. **
  73503. *************************************************************************
  73504. ** This file contains code used to implement the VACUUM command.
  73505. **
  73506. ** Most of the code in this file may be omitted by defining the
  73507. ** SQLITE_OMIT_VACUUM macro.
  73508. **
  73509. ** $Id: vacuum.c,v 1.84 2008/11/17 19:18:55 danielk1977 Exp $
  73510. */
  73511. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  73512. /*
  73513. ** Execute zSql on database db. Return an error code.
  73514. */
  73515. static int execSql(sqlite3 *db, const char *zSql){
  73516. sqlite3_stmt *pStmt;
  73517. if( !zSql ){
  73518. return SQLITE_NOMEM;
  73519. }
  73520. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  73521. return sqlite3_errcode(db);
  73522. }
  73523. while( SQLITE_ROW==sqlite3_step(pStmt) ){}
  73524. return sqlite3_finalize(pStmt);
  73525. }
  73526. /*
  73527. ** Execute zSql on database db. The statement returns exactly
  73528. ** one column. Execute this as SQL on the same database.
  73529. */
  73530. static int execExecSql(sqlite3 *db, const char *zSql){
  73531. sqlite3_stmt *pStmt;
  73532. int rc;
  73533. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  73534. if( rc!=SQLITE_OK ) return rc;
  73535. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  73536. rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
  73537. if( rc!=SQLITE_OK ){
  73538. sqlite3_finalize(pStmt);
  73539. return rc;
  73540. }
  73541. }
  73542. return sqlite3_finalize(pStmt);
  73543. }
  73544. /*
  73545. ** The non-standard VACUUM command is used to clean up the database,
  73546. ** collapse free space, etc. It is modelled after the VACUUM command
  73547. ** in PostgreSQL.
  73548. **
  73549. ** In version 1.0.x of SQLite, the VACUUM command would call
  73550. ** gdbm_reorganize() on all the database tables. But beginning
  73551. ** with 2.0.0, SQLite no longer uses GDBM so this command has
  73552. ** become a no-op.
  73553. */
  73554. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  73555. Vdbe *v = sqlite3GetVdbe(pParse);
  73556. if( v ){
  73557. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  73558. }
  73559. return;
  73560. }
  73561. /*
  73562. ** This routine implements the OP_Vacuum opcode of the VDBE.
  73563. */
  73564. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  73565. int rc = SQLITE_OK; /* Return code from service routines */
  73566. Btree *pMain; /* The database being vacuumed */
  73567. Pager *pMainPager; /* Pager for database being vacuumed */
  73568. Btree *pTemp; /* The temporary database we vacuum into */
  73569. char *zSql = 0; /* SQL statements */
  73570. int saved_flags; /* Saved value of the db->flags */
  73571. int saved_nChange; /* Saved value of db->nChange */
  73572. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  73573. Db *pDb = 0; /* Database to detach at end of vacuum */
  73574. int isMemDb; /* True is vacuuming a :memory: database */
  73575. int nRes;
  73576. /* Save the current value of the write-schema flag before setting it. */
  73577. saved_flags = db->flags;
  73578. saved_nChange = db->nChange;
  73579. saved_nTotalChange = db->nTotalChange;
  73580. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
  73581. if( !db->autoCommit ){
  73582. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  73583. rc = SQLITE_ERROR;
  73584. goto end_of_vacuum;
  73585. }
  73586. pMain = db->aDb[0].pBt;
  73587. pMainPager = sqlite3BtreePager(pMain);
  73588. isMemDb = sqlite3PagerFile(pMainPager)->pMethods==0;
  73589. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  73590. ** can be set to 'off' for this file, as it is not recovered if a crash
  73591. ** occurs anyway. The integrity of the database is maintained by a
  73592. ** (possibly synchronous) transaction opened on the main database before
  73593. ** sqlite3BtreeCopyFile() is called.
  73594. **
  73595. ** An optimisation would be to use a non-journaled pager.
  73596. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  73597. ** that actually made the VACUUM run slower. Very little journalling
  73598. ** actually occurs when doing a vacuum since the vacuum_db is initially
  73599. ** empty. Only the journal header is written. Apparently it takes more
  73600. ** time to parse and run the PRAGMA to turn journalling off than it does
  73601. ** to write the journal header file.
  73602. */
  73603. zSql = "ATTACH '' AS vacuum_db;";
  73604. rc = execSql(db, zSql);
  73605. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73606. pDb = &db->aDb[db->nDb-1];
  73607. assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
  73608. pTemp = db->aDb[db->nDb-1].pBt;
  73609. nRes = sqlite3BtreeGetReserve(pMain);
  73610. /* A VACUUM cannot change the pagesize of an encrypted database. */
  73611. #ifdef SQLITE_HAS_CODEC
  73612. if( db->nextPagesize ){
  73613. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  73614. int nKey;
  73615. char *zKey;
  73616. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  73617. if( nKey ) db->nextPagesize = 0;
  73618. }
  73619. #endif
  73620. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes)
  73621. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes))
  73622. || db->mallocFailed
  73623. ){
  73624. rc = SQLITE_NOMEM;
  73625. goto end_of_vacuum;
  73626. }
  73627. rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
  73628. if( rc!=SQLITE_OK ){
  73629. goto end_of_vacuum;
  73630. }
  73631. #ifndef SQLITE_OMIT_AUTOVACUUM
  73632. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  73633. sqlite3BtreeGetAutoVacuum(pMain));
  73634. #endif
  73635. /* Begin a transaction */
  73636. rc = execSql(db, "BEGIN EXCLUSIVE;");
  73637. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73638. /* Query the schema of the main database. Create a mirror schema
  73639. ** in the temporary database.
  73640. */
  73641. rc = execExecSql(db,
  73642. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  73643. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  73644. " AND rootpage>0"
  73645. );
  73646. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73647. rc = execExecSql(db,
  73648. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  73649. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  73650. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73651. rc = execExecSql(db,
  73652. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  73653. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  73654. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73655. /* Loop through the tables in the main database. For each, do
  73656. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
  73657. ** the contents to the temporary database.
  73658. */
  73659. rc = execExecSql(db,
  73660. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  73661. "|| ' SELECT * FROM ' || quote(name) || ';'"
  73662. "FROM sqlite_master "
  73663. "WHERE type = 'table' AND name!='sqlite_sequence' "
  73664. " AND rootpage>0"
  73665. );
  73666. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73667. /* Copy over the sequence table
  73668. */
  73669. rc = execExecSql(db,
  73670. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  73671. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  73672. );
  73673. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73674. rc = execExecSql(db,
  73675. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  73676. "|| ' SELECT * FROM ' || quote(name) || ';' "
  73677. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  73678. );
  73679. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73680. /* Copy the triggers, views, and virtual tables from the main database
  73681. ** over to the temporary database. None of these objects has any
  73682. ** associated storage, so all we have to do is copy their entries
  73683. ** from the SQLITE_MASTER table.
  73684. */
  73685. rc = execSql(db,
  73686. "INSERT INTO vacuum_db.sqlite_master "
  73687. " SELECT type, name, tbl_name, rootpage, sql"
  73688. " FROM sqlite_master"
  73689. " WHERE type='view' OR type='trigger'"
  73690. " OR (type='table' AND rootpage=0)"
  73691. );
  73692. if( rc ) goto end_of_vacuum;
  73693. /* At this point, unless the main db was completely empty, there is now a
  73694. ** transaction open on the vacuum database, but not on the main database.
  73695. ** Open a btree level transaction on the main database. This allows a
  73696. ** call to sqlite3BtreeCopyFile(). The main database btree level
  73697. ** transaction is then committed, so the SQL level never knows it was
  73698. ** opened for writing. This way, the SQL transaction used to create the
  73699. ** temporary database never needs to be committed.
  73700. */
  73701. if( rc==SQLITE_OK ){
  73702. u32 meta;
  73703. int i;
  73704. /* This array determines which meta meta values are preserved in the
  73705. ** vacuum. Even entries are the meta value number and odd entries
  73706. ** are an increment to apply to the meta value after the vacuum.
  73707. ** The increment is used to increase the schema cookie so that other
  73708. ** connections to the same database will know to reread the schema.
  73709. */
  73710. static const unsigned char aCopy[] = {
  73711. 1, 1, /* Add one to the old schema cookie */
  73712. 3, 0, /* Preserve the default page cache size */
  73713. 5, 0, /* Preserve the default text encoding */
  73714. 6, 0, /* Preserve the user version */
  73715. };
  73716. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  73717. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  73718. /* Copy Btree meta values */
  73719. for(i=0; i<ArraySize(aCopy); i+=2){
  73720. rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  73721. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73722. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  73723. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73724. }
  73725. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  73726. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73727. rc = sqlite3BtreeCommit(pTemp);
  73728. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  73729. #ifndef SQLITE_OMIT_AUTOVACUUM
  73730. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  73731. #endif
  73732. rc = sqlite3BtreeCommit(pMain);
  73733. }
  73734. if( rc==SQLITE_OK ){
  73735. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes);
  73736. }
  73737. end_of_vacuum:
  73738. /* Restore the original value of db->flags */
  73739. db->flags = saved_flags;
  73740. db->nChange = saved_nChange;
  73741. db->nTotalChange = saved_nTotalChange;
  73742. /* Currently there is an SQL level transaction open on the vacuum
  73743. ** database. No locks are held on any other files (since the main file
  73744. ** was committed at the btree level). So it safe to end the transaction
  73745. ** by manually setting the autoCommit flag to true and detaching the
  73746. ** vacuum database. The vacuum_db journal file is deleted when the pager
  73747. ** is closed by the DETACH.
  73748. */
  73749. db->autoCommit = 1;
  73750. if( pDb ){
  73751. sqlite3BtreeClose(pDb->pBt);
  73752. pDb->pBt = 0;
  73753. pDb->pSchema = 0;
  73754. }
  73755. sqlite3ResetInternalSchema(db, 0);
  73756. return rc;
  73757. }
  73758. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  73759. /************** End of vacuum.c **********************************************/
  73760. /************** Begin file vtab.c ********************************************/
  73761. /*
  73762. ** 2006 June 10
  73763. **
  73764. ** The author disclaims copyright to this source code. In place of
  73765. ** a legal notice, here is a blessing:
  73766. **
  73767. ** May you do good and not evil.
  73768. ** May you find forgiveness for yourself and forgive others.
  73769. ** May you share freely, never taking more than you give.
  73770. **
  73771. *************************************************************************
  73772. ** This file contains code used to help implement virtual tables.
  73773. **
  73774. ** $Id: vtab.c,v 1.81 2008/12/10 19:26:24 drh Exp $
  73775. */
  73776. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73777. static int createModule(
  73778. sqlite3 *db, /* Database in which module is registered */
  73779. const char *zName, /* Name assigned to this module */
  73780. const sqlite3_module *pModule, /* The definition of the module */
  73781. void *pAux, /* Context pointer for xCreate/xConnect */
  73782. void (*xDestroy)(void *) /* Module destructor function */
  73783. ) {
  73784. int rc, nName;
  73785. Module *pMod;
  73786. sqlite3_mutex_enter(db->mutex);
  73787. nName = sqlite3Strlen30(zName);
  73788. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  73789. if( pMod ){
  73790. Module *pDel;
  73791. char *zCopy = (char *)(&pMod[1]);
  73792. memcpy(zCopy, zName, nName+1);
  73793. pMod->zName = zCopy;
  73794. pMod->pModule = pModule;
  73795. pMod->pAux = pAux;
  73796. pMod->xDestroy = xDestroy;
  73797. pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
  73798. if( pDel && pDel->xDestroy ){
  73799. pDel->xDestroy(pDel->pAux);
  73800. }
  73801. sqlite3DbFree(db, pDel);
  73802. if( pDel==pMod ){
  73803. db->mallocFailed = 1;
  73804. }
  73805. sqlite3ResetInternalSchema(db, 0);
  73806. }else if( xDestroy ){
  73807. xDestroy(pAux);
  73808. }
  73809. rc = sqlite3ApiExit(db, SQLITE_OK);
  73810. sqlite3_mutex_leave(db->mutex);
  73811. return rc;
  73812. }
  73813. /*
  73814. ** External API function used to create a new virtual-table module.
  73815. */
  73816. SQLITE_API int sqlite3_create_module(
  73817. sqlite3 *db, /* Database in which module is registered */
  73818. const char *zName, /* Name assigned to this module */
  73819. const sqlite3_module *pModule, /* The definition of the module */
  73820. void *pAux /* Context pointer for xCreate/xConnect */
  73821. ){
  73822. return createModule(db, zName, pModule, pAux, 0);
  73823. }
  73824. /*
  73825. ** External API function used to create a new virtual-table module.
  73826. */
  73827. SQLITE_API int sqlite3_create_module_v2(
  73828. sqlite3 *db, /* Database in which module is registered */
  73829. const char *zName, /* Name assigned to this module */
  73830. const sqlite3_module *pModule, /* The definition of the module */
  73831. void *pAux, /* Context pointer for xCreate/xConnect */
  73832. void (*xDestroy)(void *) /* Module destructor function */
  73833. ){
  73834. return createModule(db, zName, pModule, pAux, xDestroy);
  73835. }
  73836. /*
  73837. ** Lock the virtual table so that it cannot be disconnected.
  73838. ** Locks nest. Every lock should have a corresponding unlock.
  73839. ** If an unlock is omitted, resources leaks will occur.
  73840. **
  73841. ** If a disconnect is attempted while a virtual table is locked,
  73842. ** the disconnect is deferred until all locks have been removed.
  73843. */
  73844. SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
  73845. pVtab->nRef++;
  73846. }
  73847. /*
  73848. ** Unlock a virtual table. When the last lock is removed,
  73849. ** disconnect the virtual table.
  73850. */
  73851. SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
  73852. pVtab->nRef--;
  73853. assert(db);
  73854. assert( sqlite3SafetyCheckOk(db) );
  73855. if( pVtab->nRef==0 ){
  73856. if( db->magic==SQLITE_MAGIC_BUSY ){
  73857. (void)sqlite3SafetyOff(db);
  73858. pVtab->pModule->xDisconnect(pVtab);
  73859. (void)sqlite3SafetyOn(db);
  73860. } else {
  73861. pVtab->pModule->xDisconnect(pVtab);
  73862. }
  73863. }
  73864. }
  73865. /*
  73866. ** Clear any and all virtual-table information from the Table record.
  73867. ** This routine is called, for example, just before deleting the Table
  73868. ** record.
  73869. */
  73870. SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
  73871. sqlite3_vtab *pVtab = p->pVtab;
  73872. sqlite3 *db = p->db;
  73873. if( pVtab ){
  73874. assert( p->pMod && p->pMod->pModule );
  73875. sqlite3VtabUnlock(db, pVtab);
  73876. p->pVtab = 0;
  73877. }
  73878. if( p->azModuleArg ){
  73879. int i;
  73880. for(i=0; i<p->nModuleArg; i++){
  73881. sqlite3DbFree(db, p->azModuleArg[i]);
  73882. }
  73883. sqlite3DbFree(db, p->azModuleArg);
  73884. }
  73885. }
  73886. /*
  73887. ** Add a new module argument to pTable->azModuleArg[].
  73888. ** The string is not copied - the pointer is stored. The
  73889. ** string will be freed automatically when the table is
  73890. ** deleted.
  73891. */
  73892. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  73893. int i = pTable->nModuleArg++;
  73894. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  73895. char **azModuleArg;
  73896. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  73897. if( azModuleArg==0 ){
  73898. int j;
  73899. for(j=0; j<i; j++){
  73900. sqlite3DbFree(db, pTable->azModuleArg[j]);
  73901. }
  73902. sqlite3DbFree(db, zArg);
  73903. sqlite3DbFree(db, pTable->azModuleArg);
  73904. pTable->nModuleArg = 0;
  73905. }else{
  73906. azModuleArg[i] = zArg;
  73907. azModuleArg[i+1] = 0;
  73908. }
  73909. pTable->azModuleArg = azModuleArg;
  73910. }
  73911. /*
  73912. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  73913. ** statement. The module name has been parsed, but the optional list
  73914. ** of parameters that follow the module name are still pending.
  73915. */
  73916. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  73917. Parse *pParse, /* Parsing context */
  73918. Token *pName1, /* Name of new table, or database name */
  73919. Token *pName2, /* Name of new table or NULL */
  73920. Token *pModuleName /* Name of the module for the virtual table */
  73921. ){
  73922. int iDb; /* The database the table is being created in */
  73923. Table *pTable; /* The new virtual table */
  73924. sqlite3 *db; /* Database connection */
  73925. if( pParse->db->flags & SQLITE_SharedCache ){
  73926. sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
  73927. return;
  73928. }
  73929. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
  73930. pTable = pParse->pNewTable;
  73931. if( pTable==0 || pParse->nErr ) return;
  73932. assert( 0==pTable->pIndex );
  73933. db = pParse->db;
  73934. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  73935. assert( iDb>=0 );
  73936. pTable->tabFlags |= TF_Virtual;
  73937. pTable->nModuleArg = 0;
  73938. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  73939. addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
  73940. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  73941. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  73942. #ifndef SQLITE_OMIT_AUTHORIZATION
  73943. /* Creating a virtual table invokes the authorization callback twice.
  73944. ** The first invocation, to obtain permission to INSERT a row into the
  73945. ** sqlite_master table, has already been made by sqlite3StartTable().
  73946. ** The second call, to obtain permission to create the table, is made now.
  73947. */
  73948. if( pTable->azModuleArg ){
  73949. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  73950. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  73951. }
  73952. #endif
  73953. }
  73954. /*
  73955. ** This routine takes the module argument that has been accumulating
  73956. ** in pParse->zArg[] and appends it to the list of arguments on the
  73957. ** virtual table currently under construction in pParse->pTable.
  73958. */
  73959. static void addArgumentToVtab(Parse *pParse){
  73960. if( pParse->sArg.z && pParse->pNewTable ){
  73961. const char *z = (const char*)pParse->sArg.z;
  73962. int n = pParse->sArg.n;
  73963. sqlite3 *db = pParse->db;
  73964. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  73965. }
  73966. }
  73967. /*
  73968. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  73969. ** has been completely parsed.
  73970. */
  73971. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  73972. Table *pTab; /* The table being constructed */
  73973. sqlite3 *db; /* The database connection */
  73974. char *zModule; /* The module name of the table: USING modulename */
  73975. Module *pMod = 0;
  73976. addArgumentToVtab(pParse);
  73977. pParse->sArg.z = 0;
  73978. /* Lookup the module name. */
  73979. pTab = pParse->pNewTable;
  73980. if( pTab==0 ) return;
  73981. db = pParse->db;
  73982. if( pTab->nModuleArg<1 ) return;
  73983. zModule = pTab->azModuleArg[0];
  73984. pMod = (Module*)sqlite3HashFind(&db->aModule, zModule,
  73985. sqlite3Strlen30(zModule));
  73986. pTab->pMod = pMod;
  73987. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  73988. ** first time (in other words if the virtual table is actually being
  73989. ** created now instead of just being read out of sqlite_master) then
  73990. ** do additional initialization work and store the statement text
  73991. ** in the sqlite_master table.
  73992. */
  73993. if( !db->init.busy ){
  73994. char *zStmt;
  73995. char *zWhere;
  73996. int iDb;
  73997. Vdbe *v;
  73998. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  73999. if( pEnd ){
  74000. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  74001. }
  74002. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  74003. /* A slot for the record has already been allocated in the
  74004. ** SQLITE_MASTER table. We just need to update that slot with all
  74005. ** the information we've collected.
  74006. **
  74007. ** The VM register number pParse->regRowid holds the rowid of an
  74008. ** entry in the sqlite_master table tht was created for this vtab
  74009. ** by sqlite3StartTable().
  74010. */
  74011. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  74012. sqlite3NestedParse(pParse,
  74013. "UPDATE %Q.%s "
  74014. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  74015. "WHERE rowid=#%d",
  74016. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  74017. pTab->zName,
  74018. pTab->zName,
  74019. zStmt,
  74020. pParse->regRowid
  74021. );
  74022. sqlite3DbFree(db, zStmt);
  74023. v = sqlite3GetVdbe(pParse);
  74024. sqlite3ChangeCookie(pParse, iDb);
  74025. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  74026. zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
  74027. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
  74028. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  74029. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  74030. }
  74031. /* If we are rereading the sqlite_master table create the in-memory
  74032. ** record of the table. If the module has already been registered,
  74033. ** also call the xConnect method here.
  74034. */
  74035. else {
  74036. Table *pOld;
  74037. Schema *pSchema = pTab->pSchema;
  74038. const char *zName = pTab->zName;
  74039. int nName = sqlite3Strlen30(zName) + 1;
  74040. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
  74041. if( pOld ){
  74042. db->mallocFailed = 1;
  74043. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  74044. return;
  74045. }
  74046. pSchema->db = pParse->db;
  74047. pParse->pNewTable = 0;
  74048. }
  74049. }
  74050. /*
  74051. ** The parser calls this routine when it sees the first token
  74052. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  74053. */
  74054. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  74055. addArgumentToVtab(pParse);
  74056. pParse->sArg.z = 0;
  74057. pParse->sArg.n = 0;
  74058. }
  74059. /*
  74060. ** The parser calls this routine for each token after the first token
  74061. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  74062. */
  74063. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  74064. Token *pArg = &pParse->sArg;
  74065. if( pArg->z==0 ){
  74066. pArg->z = p->z;
  74067. pArg->n = p->n;
  74068. }else{
  74069. assert(pArg->z < p->z);
  74070. pArg->n = (int)(&p->z[p->n] - pArg->z);
  74071. }
  74072. }
  74073. /*
  74074. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  74075. ** pointer to the function to invoke is passed as the fourth parameter
  74076. ** to this procedure.
  74077. */
  74078. static int vtabCallConstructor(
  74079. sqlite3 *db,
  74080. Table *pTab,
  74081. Module *pMod,
  74082. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  74083. char **pzErr
  74084. ){
  74085. int rc;
  74086. int rc2;
  74087. sqlite3_vtab *pVtab = 0;
  74088. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  74089. int nArg = pTab->nModuleArg;
  74090. char *zErr = 0;
  74091. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  74092. if( !zModuleName ){
  74093. return SQLITE_NOMEM;
  74094. }
  74095. assert( !db->pVTab );
  74096. assert( xConstruct );
  74097. db->pVTab = pTab;
  74098. rc = sqlite3SafetyOff(db);
  74099. assert( rc==SQLITE_OK );
  74100. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
  74101. rc2 = sqlite3SafetyOn(db);
  74102. if( rc==SQLITE_OK && pVtab ){
  74103. pVtab->pModule = pMod->pModule;
  74104. pVtab->nRef = 1;
  74105. pTab->pVtab = pVtab;
  74106. }
  74107. if( SQLITE_OK!=rc ){
  74108. if( zErr==0 ){
  74109. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  74110. }else {
  74111. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  74112. sqlite3DbFree(db, zErr);
  74113. }
  74114. }else if( db->pVTab ){
  74115. const char *zFormat = "vtable constructor did not declare schema: %s";
  74116. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  74117. rc = SQLITE_ERROR;
  74118. }
  74119. if( rc==SQLITE_OK ){
  74120. rc = rc2;
  74121. }
  74122. db->pVTab = 0;
  74123. sqlite3DbFree(db, zModuleName);
  74124. /* If everything went according to plan, loop through the columns
  74125. ** of the table to see if any of them contain the token "hidden".
  74126. ** If so, set the Column.isHidden flag and remove the token from
  74127. ** the type string.
  74128. */
  74129. if( rc==SQLITE_OK ){
  74130. int iCol;
  74131. for(iCol=0; iCol<pTab->nCol; iCol++){
  74132. char *zType = pTab->aCol[iCol].zType;
  74133. int nType;
  74134. int i = 0;
  74135. if( !zType ) continue;
  74136. nType = sqlite3Strlen30(zType);
  74137. if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
  74138. for(i=0; i<nType; i++){
  74139. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  74140. && (zType[i+7]=='\0' || zType[i+7]==' ')
  74141. ){
  74142. i++;
  74143. break;
  74144. }
  74145. }
  74146. }
  74147. if( i<nType ){
  74148. int j;
  74149. int nDel = 6 + (zType[i+6] ? 1 : 0);
  74150. for(j=i; (j+nDel)<=nType; j++){
  74151. zType[j] = zType[j+nDel];
  74152. }
  74153. if( zType[i]=='\0' && i>0 ){
  74154. assert(zType[i-1]==' ');
  74155. zType[i-1] = '\0';
  74156. }
  74157. pTab->aCol[iCol].isHidden = 1;
  74158. }
  74159. }
  74160. }
  74161. return rc;
  74162. }
  74163. /*
  74164. ** This function is invoked by the parser to call the xConnect() method
  74165. ** of the virtual table pTab. If an error occurs, an error code is returned
  74166. ** and an error left in pParse.
  74167. **
  74168. ** This call is a no-op if table pTab is not a virtual table.
  74169. */
  74170. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  74171. Module *pMod;
  74172. int rc = SQLITE_OK;
  74173. if( !pTab || (pTab->tabFlags & TF_Virtual)==0 || pTab->pVtab ){
  74174. return SQLITE_OK;
  74175. }
  74176. pMod = pTab->pMod;
  74177. if( !pMod ){
  74178. const char *zModule = pTab->azModuleArg[0];
  74179. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  74180. rc = SQLITE_ERROR;
  74181. } else {
  74182. char *zErr = 0;
  74183. sqlite3 *db = pParse->db;
  74184. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  74185. if( rc!=SQLITE_OK ){
  74186. sqlite3ErrorMsg(pParse, "%s", zErr);
  74187. }
  74188. sqlite3DbFree(db, zErr);
  74189. }
  74190. return rc;
  74191. }
  74192. /*
  74193. ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
  74194. */
  74195. static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
  74196. const int ARRAY_INCR = 5;
  74197. /* Grow the sqlite3.aVTrans array if required */
  74198. if( (db->nVTrans%ARRAY_INCR)==0 ){
  74199. sqlite3_vtab **aVTrans;
  74200. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  74201. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  74202. if( !aVTrans ){
  74203. return SQLITE_NOMEM;
  74204. }
  74205. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  74206. db->aVTrans = aVTrans;
  74207. }
  74208. /* Add pVtab to the end of sqlite3.aVTrans */
  74209. db->aVTrans[db->nVTrans++] = pVtab;
  74210. sqlite3VtabLock(pVtab);
  74211. return SQLITE_OK;
  74212. }
  74213. /*
  74214. ** This function is invoked by the vdbe to call the xCreate method
  74215. ** of the virtual table named zTab in database iDb.
  74216. **
  74217. ** If an error occurs, *pzErr is set to point an an English language
  74218. ** description of the error and an SQLITE_XXX error code is returned.
  74219. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  74220. */
  74221. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  74222. int rc = SQLITE_OK;
  74223. Table *pTab;
  74224. Module *pMod;
  74225. const char *zModule;
  74226. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  74227. assert(pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVtab);
  74228. pMod = pTab->pMod;
  74229. zModule = pTab->azModuleArg[0];
  74230. /* If the module has been registered and includes a Create method,
  74231. ** invoke it now. If the module has not been registered, return an
  74232. ** error. Otherwise, do nothing.
  74233. */
  74234. if( !pMod ){
  74235. *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
  74236. rc = SQLITE_ERROR;
  74237. }else{
  74238. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  74239. }
  74240. if( rc==SQLITE_OK && pTab->pVtab ){
  74241. rc = addToVTrans(db, pTab->pVtab);
  74242. }
  74243. return rc;
  74244. }
  74245. /*
  74246. ** This function is used to set the schema of a virtual table. It is only
  74247. ** valid to call this function from within the xCreate() or xConnect() of a
  74248. ** virtual table module.
  74249. */
  74250. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  74251. Parse sParse;
  74252. int rc = SQLITE_OK;
  74253. Table *pTab;
  74254. char *zErr = 0;
  74255. sqlite3_mutex_enter(db->mutex);
  74256. pTab = db->pVTab;
  74257. if( !pTab ){
  74258. sqlite3Error(db, SQLITE_MISUSE, 0);
  74259. sqlite3_mutex_leave(db->mutex);
  74260. return SQLITE_MISUSE;
  74261. }
  74262. assert((pTab->tabFlags & TF_Virtual)!=0 && pTab->nCol==0 && pTab->aCol==0);
  74263. memset(&sParse, 0, sizeof(Parse));
  74264. sParse.declareVtab = 1;
  74265. sParse.db = db;
  74266. if(
  74267. SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) &&
  74268. sParse.pNewTable &&
  74269. !sParse.pNewTable->pSelect &&
  74270. (sParse.pNewTable->tabFlags & TF_Virtual)==0
  74271. ){
  74272. pTab->aCol = sParse.pNewTable->aCol;
  74273. pTab->nCol = sParse.pNewTable->nCol;
  74274. sParse.pNewTable->nCol = 0;
  74275. sParse.pNewTable->aCol = 0;
  74276. db->pVTab = 0;
  74277. } else {
  74278. sqlite3Error(db, SQLITE_ERROR, zErr);
  74279. sqlite3DbFree(db, zErr);
  74280. rc = SQLITE_ERROR;
  74281. }
  74282. sParse.declareVtab = 0;
  74283. sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
  74284. sqlite3DeleteTable(sParse.pNewTable);
  74285. sParse.pNewTable = 0;
  74286. assert( (rc&0xff)==rc );
  74287. rc = sqlite3ApiExit(db, rc);
  74288. sqlite3_mutex_leave(db->mutex);
  74289. return rc;
  74290. }
  74291. /*
  74292. ** This function is invoked by the vdbe to call the xDestroy method
  74293. ** of the virtual table named zTab in database iDb. This occurs
  74294. ** when a DROP TABLE is mentioned.
  74295. **
  74296. ** This call is a no-op if zTab is not a virtual table.
  74297. */
  74298. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
  74299. {
  74300. int rc = SQLITE_OK;
  74301. Table *pTab;
  74302. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  74303. assert(pTab);
  74304. if( pTab->pVtab ){
  74305. int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
  74306. rc = sqlite3SafetyOff(db);
  74307. assert( rc==SQLITE_OK );
  74308. if( xDestroy ){
  74309. rc = xDestroy(pTab->pVtab);
  74310. }
  74311. (void)sqlite3SafetyOn(db);
  74312. if( rc==SQLITE_OK ){
  74313. int i;
  74314. for(i=0; i<db->nVTrans; i++){
  74315. if( db->aVTrans[i]==pTab->pVtab ){
  74316. db->aVTrans[i] = db->aVTrans[--db->nVTrans];
  74317. break;
  74318. }
  74319. }
  74320. pTab->pVtab = 0;
  74321. }
  74322. }
  74323. return rc;
  74324. }
  74325. /*
  74326. ** This function invokes either the xRollback or xCommit method
  74327. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  74328. ** called is identified by the second argument, "offset", which is
  74329. ** the offset of the method to call in the sqlite3_module structure.
  74330. **
  74331. ** The array is cleared after invoking the callbacks.
  74332. */
  74333. static void callFinaliser(sqlite3 *db, int offset){
  74334. int i;
  74335. if( db->aVTrans ){
  74336. for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
  74337. sqlite3_vtab *pVtab = db->aVTrans[i];
  74338. int (*x)(sqlite3_vtab *);
  74339. x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
  74340. if( x ) x(pVtab);
  74341. sqlite3VtabUnlock(db, pVtab);
  74342. }
  74343. sqlite3DbFree(db, db->aVTrans);
  74344. db->nVTrans = 0;
  74345. db->aVTrans = 0;
  74346. }
  74347. }
  74348. /*
  74349. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  74350. ** array. Return the error code for the first error that occurs, or
  74351. ** SQLITE_OK if all xSync operations are successful.
  74352. **
  74353. ** Set *pzErrmsg to point to a buffer that should be released using
  74354. ** sqlite3DbFree() containing an error message, if one is available.
  74355. */
  74356. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
  74357. int i;
  74358. int rc = SQLITE_OK;
  74359. int rcsafety;
  74360. sqlite3_vtab **aVTrans = db->aVTrans;
  74361. rc = sqlite3SafetyOff(db);
  74362. db->aVTrans = 0;
  74363. for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
  74364. sqlite3_vtab *pVtab = aVTrans[i];
  74365. int (*x)(sqlite3_vtab *);
  74366. x = pVtab->pModule->xSync;
  74367. if( x ){
  74368. rc = x(pVtab);
  74369. sqlite3DbFree(db, *pzErrmsg);
  74370. *pzErrmsg = pVtab->zErrMsg;
  74371. pVtab->zErrMsg = 0;
  74372. }
  74373. }
  74374. db->aVTrans = aVTrans;
  74375. rcsafety = sqlite3SafetyOn(db);
  74376. if( rc==SQLITE_OK ){
  74377. rc = rcsafety;
  74378. }
  74379. return rc;
  74380. }
  74381. /*
  74382. ** Invoke the xRollback method of all virtual tables in the
  74383. ** sqlite3.aVTrans array. Then clear the array itself.
  74384. */
  74385. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  74386. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  74387. return SQLITE_OK;
  74388. }
  74389. /*
  74390. ** Invoke the xCommit method of all virtual tables in the
  74391. ** sqlite3.aVTrans array. Then clear the array itself.
  74392. */
  74393. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  74394. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  74395. return SQLITE_OK;
  74396. }
  74397. /*
  74398. ** If the virtual table pVtab supports the transaction interface
  74399. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  74400. ** not currently open, invoke the xBegin method now.
  74401. **
  74402. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  74403. ** in the sqlite3.aVTrans array.
  74404. */
  74405. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
  74406. int rc = SQLITE_OK;
  74407. const sqlite3_module *pModule;
  74408. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  74409. ** than zero, then this function is being called from within a
  74410. ** virtual module xSync() callback. It is illegal to write to
  74411. ** virtual module tables in this case, so return SQLITE_LOCKED.
  74412. */
  74413. if( sqlite3VtabInSync(db) ){
  74414. return SQLITE_LOCKED;
  74415. }
  74416. if( !pVtab ){
  74417. return SQLITE_OK;
  74418. }
  74419. pModule = pVtab->pModule;
  74420. if( pModule->xBegin ){
  74421. int i;
  74422. /* If pVtab is already in the aVTrans array, return early */
  74423. for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
  74424. if( db->aVTrans[i]==pVtab ){
  74425. return SQLITE_OK;
  74426. }
  74427. }
  74428. /* Invoke the xBegin method */
  74429. rc = pModule->xBegin(pVtab);
  74430. if( rc==SQLITE_OK ){
  74431. rc = addToVTrans(db, pVtab);
  74432. }
  74433. }
  74434. return rc;
  74435. }
  74436. /*
  74437. ** The first parameter (pDef) is a function implementation. The
  74438. ** second parameter (pExpr) is the first argument to this function.
  74439. ** If pExpr is a column in a virtual table, then let the virtual
  74440. ** table implementation have an opportunity to overload the function.
  74441. **
  74442. ** This routine is used to allow virtual table implementations to
  74443. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  74444. **
  74445. ** Return either the pDef argument (indicating no change) or a
  74446. ** new FuncDef structure that is marked as ephemeral using the
  74447. ** SQLITE_FUNC_EPHEM flag.
  74448. */
  74449. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  74450. sqlite3 *db, /* Database connection for reporting malloc problems */
  74451. FuncDef *pDef, /* Function to possibly overload */
  74452. int nArg, /* Number of arguments to the function */
  74453. Expr *pExpr /* First argument to the function */
  74454. ){
  74455. Table *pTab;
  74456. sqlite3_vtab *pVtab;
  74457. sqlite3_module *pMod;
  74458. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  74459. void *pArg = 0;
  74460. FuncDef *pNew;
  74461. int rc = 0;
  74462. char *zLowerName;
  74463. unsigned char *z;
  74464. /* Check to see the left operand is a column in a virtual table */
  74465. if( pExpr==0 ) return pDef;
  74466. if( pExpr->op!=TK_COLUMN ) return pDef;
  74467. pTab = pExpr->pTab;
  74468. if( pTab==0 ) return pDef;
  74469. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  74470. pVtab = pTab->pVtab;
  74471. assert( pVtab!=0 );
  74472. assert( pVtab->pModule!=0 );
  74473. pMod = (sqlite3_module *)pVtab->pModule;
  74474. if( pMod->xFindFunction==0 ) return pDef;
  74475. /* Call the xFindFunction method on the virtual table implementation
  74476. ** to see if the implementation wants to overload this function
  74477. */
  74478. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  74479. if( zLowerName ){
  74480. for(z=(unsigned char*)zLowerName; *z; z++){
  74481. *z = sqlite3UpperToLower[*z];
  74482. }
  74483. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  74484. sqlite3DbFree(db, zLowerName);
  74485. if( pVtab->zErrMsg ){
  74486. sqlite3Error(db, rc, "%s", pVtab->zErrMsg);
  74487. sqlite3DbFree(db, pVtab->zErrMsg);
  74488. pVtab->zErrMsg = 0;
  74489. }
  74490. }
  74491. if( rc==0 ){
  74492. return pDef;
  74493. }
  74494. /* Create a new ephemeral function definition for the overloaded
  74495. ** function */
  74496. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  74497. + sqlite3Strlen30(pDef->zName) );
  74498. if( pNew==0 ){
  74499. return pDef;
  74500. }
  74501. *pNew = *pDef;
  74502. pNew->zName = (char *)&pNew[1];
  74503. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  74504. pNew->xFunc = xFunc;
  74505. pNew->pUserData = pArg;
  74506. pNew->flags |= SQLITE_FUNC_EPHEM;
  74507. return pNew;
  74508. }
  74509. /*
  74510. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  74511. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  74512. ** array if it is missing. If pTab is already in the array, this routine
  74513. ** is a no-op.
  74514. */
  74515. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  74516. int i, n;
  74517. assert( IsVirtual(pTab) );
  74518. for(i=0; i<pParse->nVtabLock; i++){
  74519. if( pTab==pParse->apVtabLock[i] ) return;
  74520. }
  74521. n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]);
  74522. pParse->apVtabLock = sqlite3_realloc(pParse->apVtabLock, n);
  74523. if( pParse->apVtabLock ){
  74524. pParse->apVtabLock[pParse->nVtabLock++] = pTab;
  74525. }else{
  74526. pParse->db->mallocFailed = 1;
  74527. }
  74528. }
  74529. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74530. /************** End of vtab.c ************************************************/
  74531. /************** Begin file where.c *******************************************/
  74532. /*
  74533. ** 2001 September 15
  74534. **
  74535. ** The author disclaims copyright to this source code. In place of
  74536. ** a legal notice, here is a blessing:
  74537. **
  74538. ** May you do good and not evil.
  74539. ** May you find forgiveness for yourself and forgive others.
  74540. ** May you share freely, never taking more than you give.
  74541. **
  74542. *************************************************************************
  74543. ** This module contains C code that generates VDBE code used to process
  74544. ** the WHERE clause of SQL statements. This module is responsible for
  74545. ** generating the code that loops through a table looking for applicable
  74546. ** rows. Indices are selected and used to speed the search when doing
  74547. ** so is applicable. Because this module is responsible for selecting
  74548. ** indices, you might also think of this module as the "query optimizer".
  74549. **
  74550. ** $Id: where.c,v 1.364 2009/01/14 00:55:10 drh Exp $
  74551. */
  74552. /*
  74553. ** Trace output macros
  74554. */
  74555. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  74556. SQLITE_PRIVATE int sqlite3WhereTrace = 0;
  74557. #endif
  74558. #if 0
  74559. # define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
  74560. #else
  74561. # define WHERETRACE(X)
  74562. #endif
  74563. /* Forward reference
  74564. */
  74565. typedef struct WhereClause WhereClause;
  74566. typedef struct WhereMaskSet WhereMaskSet;
  74567. typedef struct WhereOrInfo WhereOrInfo;
  74568. typedef struct WhereAndInfo WhereAndInfo;
  74569. typedef struct WhereCost WhereCost;
  74570. /*
  74571. ** The query generator uses an array of instances of this structure to
  74572. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  74573. ** clause subexpression is separated from the others by AND operators.
  74574. ** (Note: the same data structure is also reused to hold a group of terms
  74575. ** separated by OR operators. But at the top-level, everything is AND
  74576. ** separated.)
  74577. **
  74578. ** All WhereTerms are collected into a single WhereClause structure.
  74579. ** The following identity holds:
  74580. **
  74581. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  74582. **
  74583. ** When a term is of the form:
  74584. **
  74585. ** X <op> <expr>
  74586. **
  74587. ** where X is a column name and <op> is one of certain operators,
  74588. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  74589. ** cursor number and column number for X. WhereTerm.eOperator records
  74590. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  74591. ** use of a bitmask encoding for the operator allows us to search
  74592. ** quickly for terms that match any of several different operators.
  74593. **
  74594. ** A WhereTerm might also be two or more subterms connected by OR:
  74595. **
  74596. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  74597. **
  74598. ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
  74599. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  74600. ** is collected about the
  74601. **
  74602. ** If a term in the WHERE clause does not match either of the two previous
  74603. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  74604. ** to the original subexpression content and wtFlags is set up appropriately
  74605. ** but no other fields in the WhereTerm object are meaningful.
  74606. **
  74607. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  74608. ** but they do so indirectly. A single WhereMaskSet structure translates
  74609. ** cursor number into bits and the translated bit is stored in the prereq
  74610. ** fields. The translation is used in order to maximize the number of
  74611. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  74612. ** spread out over the non-negative integers. For example, the cursor
  74613. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  74614. ** translates these sparse cursor numbers into consecutive integers
  74615. ** beginning with 0 in order to make the best possible use of the available
  74616. ** bits in the Bitmask. So, in the example above, the cursor numbers
  74617. ** would be mapped into integers 0 through 7.
  74618. **
  74619. ** The number of terms in a join is limited by the number of bits
  74620. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  74621. ** is only able to process joins with 64 or fewer tables.
  74622. */
  74623. typedef struct WhereTerm WhereTerm;
  74624. struct WhereTerm {
  74625. Expr *pExpr; /* Pointer to the subexpression that is this term */
  74626. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  74627. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  74628. union {
  74629. int leftColumn; /* Column number of X in "X <op> <expr>" */
  74630. WhereOrInfo *pOrInfo; /* Extra information if eOperator==WO_OR */
  74631. WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
  74632. } u;
  74633. u16 eOperator; /* A WO_xx value describing <op> */
  74634. u8 wtFlags; /* TERM_xxx bit flags. See below */
  74635. u8 nChild; /* Number of children that must disable us */
  74636. WhereClause *pWC; /* The clause this term is part of */
  74637. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  74638. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  74639. };
  74640. /*
  74641. ** Allowed values of WhereTerm.wtFlags
  74642. */
  74643. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  74644. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  74645. #define TERM_CODED 0x04 /* This term is already coded */
  74646. #define TERM_COPIED 0x08 /* Has a child */
  74647. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  74648. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  74649. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  74650. /*
  74651. ** An instance of the following structure holds all information about a
  74652. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  74653. */
  74654. struct WhereClause {
  74655. Parse *pParse; /* The parser context */
  74656. WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
  74657. u8 op; /* Split operator. TK_AND or TK_OR */
  74658. int nTerm; /* Number of terms */
  74659. int nSlot; /* Number of entries in a[] */
  74660. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  74661. WhereTerm aStatic[4]; /* Initial static space for a[] */
  74662. };
  74663. /*
  74664. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  74665. ** a dynamically allocated instance of the following structure.
  74666. */
  74667. struct WhereOrInfo {
  74668. WhereClause wc; /* Decomposition into subterms */
  74669. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  74670. };
  74671. /*
  74672. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  74673. ** a dynamically allocated instance of the following structure.
  74674. */
  74675. struct WhereAndInfo {
  74676. WhereClause wc; /* The subexpression broken out */
  74677. };
  74678. /*
  74679. ** An instance of the following structure keeps track of a mapping
  74680. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  74681. **
  74682. ** The VDBE cursor numbers are small integers contained in
  74683. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  74684. ** clause, the cursor numbers might not begin with 0 and they might
  74685. ** contain gaps in the numbering sequence. But we want to make maximum
  74686. ** use of the bits in our bitmasks. This structure provides a mapping
  74687. ** from the sparse cursor numbers into consecutive integers beginning
  74688. ** with 0.
  74689. **
  74690. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  74691. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  74692. **
  74693. ** For example, if the WHERE clause expression used these VDBE
  74694. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  74695. ** would map those cursor numbers into bits 0 through 5.
  74696. **
  74697. ** Note that the mapping is not necessarily ordered. In the example
  74698. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  74699. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  74700. ** does not really matter. What is important is that sparse cursor
  74701. ** numbers all get mapped into bit numbers that begin with 0 and contain
  74702. ** no gaps.
  74703. */
  74704. struct WhereMaskSet {
  74705. int n; /* Number of assigned cursor values */
  74706. int ix[BMS]; /* Cursor assigned to each bit */
  74707. };
  74708. /*
  74709. ** A WhereCost object records a lookup strategy and the estimated
  74710. ** cost of pursuing that strategy.
  74711. */
  74712. struct WhereCost {
  74713. WherePlan plan; /* The lookup strategy */
  74714. double rCost; /* Overall cost of pursuing this search strategy */
  74715. double nRow; /* Estimated number of output rows */
  74716. };
  74717. /*
  74718. ** Bitmasks for the operators that indices are able to exploit. An
  74719. ** OR-ed combination of these values can be used when searching for
  74720. ** terms in the where clause.
  74721. */
  74722. #define WO_IN 0x001
  74723. #define WO_EQ 0x002
  74724. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  74725. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  74726. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  74727. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  74728. #define WO_MATCH 0x040
  74729. #define WO_ISNULL 0x080
  74730. #define WO_OR 0x100 /* Two or more OR-connected terms */
  74731. #define WO_AND 0x200 /* Two or more AND-connected terms */
  74732. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  74733. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  74734. /*
  74735. ** Value for wsFlags returned by bestIndex() and stored in
  74736. ** WhereLevel.wsFlags. These flags determine which search
  74737. ** strategies are appropriate.
  74738. **
  74739. ** The least significant 12 bits is reserved as a mask for WO_ values above.
  74740. ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
  74741. ** But if the table is the right table of a left join, WhereLevel.wsFlags
  74742. ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
  74743. ** the "op" parameter to findTerm when we are resolving equality constraints.
  74744. ** ISNULL constraints will then not be used on the right table of a left
  74745. ** join. Tickets #2177 and #2189.
  74746. */
  74747. #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
  74748. #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
  74749. #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) */
  74750. #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
  74751. #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
  74752. #define WHERE_INDEXED 0x00070000 /* Anything that uses an index */
  74753. #define WHERE_IN_ABLE 0x00071000 /* Able to support an IN operator */
  74754. #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
  74755. #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
  74756. #define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
  74757. #define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
  74758. #define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
  74759. #define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */
  74760. #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
  74761. #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
  74762. /*
  74763. ** Initialize a preallocated WhereClause structure.
  74764. */
  74765. static void whereClauseInit(
  74766. WhereClause *pWC, /* The WhereClause to be initialized */
  74767. Parse *pParse, /* The parsing context */
  74768. WhereMaskSet *pMaskSet /* Mapping from table cursor numbers to bitmasks */
  74769. ){
  74770. pWC->pParse = pParse;
  74771. pWC->pMaskSet = pMaskSet;
  74772. pWC->nTerm = 0;
  74773. pWC->nSlot = ArraySize(pWC->aStatic);
  74774. pWC->a = pWC->aStatic;
  74775. }
  74776. /* Forward reference */
  74777. static void whereClauseClear(WhereClause*);
  74778. /*
  74779. ** Deallocate all memory associated with a WhereOrInfo object.
  74780. */
  74781. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  74782. whereClauseClear(&p->wc);
  74783. sqlite3DbFree(db, p);
  74784. }
  74785. /*
  74786. ** Deallocate all memory associated with a WhereAndInfo object.
  74787. */
  74788. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  74789. whereClauseClear(&p->wc);
  74790. sqlite3DbFree(db, p);
  74791. }
  74792. /*
  74793. ** Deallocate a WhereClause structure. The WhereClause structure
  74794. ** itself is not freed. This routine is the inverse of whereClauseInit().
  74795. */
  74796. static void whereClauseClear(WhereClause *pWC){
  74797. int i;
  74798. WhereTerm *a;
  74799. sqlite3 *db = pWC->pParse->db;
  74800. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  74801. if( a->wtFlags & TERM_DYNAMIC ){
  74802. sqlite3ExprDelete(db, a->pExpr);
  74803. }
  74804. if( a->wtFlags & TERM_ORINFO ){
  74805. whereOrInfoDelete(db, a->u.pOrInfo);
  74806. }else if( a->wtFlags & TERM_ANDINFO ){
  74807. whereAndInfoDelete(db, a->u.pAndInfo);
  74808. }
  74809. }
  74810. if( pWC->a!=pWC->aStatic ){
  74811. sqlite3DbFree(db, pWC->a);
  74812. }
  74813. }
  74814. /*
  74815. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  74816. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  74817. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  74818. ** 0 is returned if the new WhereTerm could not be added due to a memory
  74819. ** allocation error. The memory allocation failure will be recorded in
  74820. ** the db->mallocFailed flag so that higher-level functions can detect it.
  74821. **
  74822. ** This routine will increase the size of the pWC->a[] array as necessary.
  74823. **
  74824. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  74825. ** for freeing the expression p is assumed by the WhereClause object pWC.
  74826. ** This is true even if this routine fails to allocate a new WhereTerm.
  74827. **
  74828. ** WARNING: This routine might reallocate the space used to store
  74829. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  74830. ** calling this routine. Such pointers may be reinitialized by referencing
  74831. ** the pWC->a[] array.
  74832. */
  74833. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  74834. WhereTerm *pTerm;
  74835. int idx;
  74836. if( pWC->nTerm>=pWC->nSlot ){
  74837. WhereTerm *pOld = pWC->a;
  74838. sqlite3 *db = pWC->pParse->db;
  74839. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  74840. if( pWC->a==0 ){
  74841. if( wtFlags & TERM_DYNAMIC ){
  74842. sqlite3ExprDelete(db, p);
  74843. }
  74844. pWC->a = pOld;
  74845. return 0;
  74846. }
  74847. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  74848. if( pOld!=pWC->aStatic ){
  74849. sqlite3DbFree(db, pOld);
  74850. }
  74851. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  74852. }
  74853. pTerm = &pWC->a[idx = pWC->nTerm++];
  74854. pTerm->pExpr = p;
  74855. pTerm->wtFlags = wtFlags;
  74856. pTerm->pWC = pWC;
  74857. pTerm->iParent = -1;
  74858. return idx;
  74859. }
  74860. /*
  74861. ** This routine identifies subexpressions in the WHERE clause where
  74862. ** each subexpression is separated by the AND operator or some other
  74863. ** operator specified in the op parameter. The WhereClause structure
  74864. ** is filled with pointers to subexpressions. For example:
  74865. **
  74866. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  74867. ** \________/ \_______________/ \________________/
  74868. ** slot[0] slot[1] slot[2]
  74869. **
  74870. ** The original WHERE clause in pExpr is unaltered. All this routine
  74871. ** does is make slot[] entries point to substructure within pExpr.
  74872. **
  74873. ** In the previous sentence and in the diagram, "slot[]" refers to
  74874. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  74875. ** all terms of the WHERE clause.
  74876. */
  74877. static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
  74878. pWC->op = (u8)op;
  74879. if( pExpr==0 ) return;
  74880. if( pExpr->op!=op ){
  74881. whereClauseInsert(pWC, pExpr, 0);
  74882. }else{
  74883. whereSplit(pWC, pExpr->pLeft, op);
  74884. whereSplit(pWC, pExpr->pRight, op);
  74885. }
  74886. }
  74887. /*
  74888. ** Initialize an expression mask set
  74889. */
  74890. #define initMaskSet(P) memset(P, 0, sizeof(*P))
  74891. /*
  74892. ** Return the bitmask for the given cursor number. Return 0 if
  74893. ** iCursor is not in the set.
  74894. */
  74895. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  74896. int i;
  74897. for(i=0; i<pMaskSet->n; i++){
  74898. if( pMaskSet->ix[i]==iCursor ){
  74899. return ((Bitmask)1)<<i;
  74900. }
  74901. }
  74902. return 0;
  74903. }
  74904. /*
  74905. ** Create a new mask for cursor iCursor.
  74906. **
  74907. ** There is one cursor per table in the FROM clause. The number of
  74908. ** tables in the FROM clause is limited by a test early in the
  74909. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  74910. ** array will never overflow.
  74911. */
  74912. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  74913. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  74914. pMaskSet->ix[pMaskSet->n++] = iCursor;
  74915. }
  74916. /*
  74917. ** This routine walks (recursively) an expression tree and generates
  74918. ** a bitmask indicating which tables are used in that expression
  74919. ** tree.
  74920. **
  74921. ** In order for this routine to work, the calling function must have
  74922. ** previously invoked sqlite3ResolveExprNames() on the expression. See
  74923. ** the header comment on that routine for additional information.
  74924. ** The sqlite3ResolveExprNames() routines looks for column names and
  74925. ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
  74926. ** the VDBE cursor number of the table. This routine just has to
  74927. ** translate the cursor numbers into bitmask values and OR all
  74928. ** the bitmasks together.
  74929. */
  74930. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  74931. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  74932. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  74933. Bitmask mask = 0;
  74934. if( p==0 ) return 0;
  74935. if( p->op==TK_COLUMN ){
  74936. mask = getMask(pMaskSet, p->iTable);
  74937. return mask;
  74938. }
  74939. mask = exprTableUsage(pMaskSet, p->pRight);
  74940. mask |= exprTableUsage(pMaskSet, p->pLeft);
  74941. mask |= exprListTableUsage(pMaskSet, p->pList);
  74942. mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
  74943. return mask;
  74944. }
  74945. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  74946. int i;
  74947. Bitmask mask = 0;
  74948. if( pList ){
  74949. for(i=0; i<pList->nExpr; i++){
  74950. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  74951. }
  74952. }
  74953. return mask;
  74954. }
  74955. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  74956. Bitmask mask = 0;
  74957. while( pS ){
  74958. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  74959. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  74960. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  74961. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  74962. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  74963. pS = pS->pPrior;
  74964. }
  74965. return mask;
  74966. }
  74967. /*
  74968. ** Return TRUE if the given operator is one of the operators that is
  74969. ** allowed for an indexable WHERE clause term. The allowed operators are
  74970. ** "=", "<", ">", "<=", ">=", and "IN".
  74971. */
  74972. static int allowedOp(int op){
  74973. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  74974. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  74975. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  74976. assert( TK_GE==TK_EQ+4 );
  74977. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  74978. }
  74979. /*
  74980. ** Swap two objects of type TYPE.
  74981. */
  74982. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  74983. /*
  74984. ** Commute a comparison operator. Expressions of the form "X op Y"
  74985. ** are converted into "Y op X".
  74986. **
  74987. ** If a collation sequence is associated with either the left or right
  74988. ** side of the comparison, it remains associated with the same side after
  74989. ** the commutation. So "Y collate NOCASE op X" becomes
  74990. ** "X collate NOCASE op Y". This is because any collation sequence on
  74991. ** the left hand side of a comparison overrides any collation sequence
  74992. ** attached to the right. For the same reason the EP_ExpCollate flag
  74993. ** is not commuted.
  74994. */
  74995. static void exprCommute(Parse *pParse, Expr *pExpr){
  74996. u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
  74997. u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
  74998. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  74999. pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
  75000. pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  75001. SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
  75002. pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
  75003. pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
  75004. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  75005. if( pExpr->op>=TK_GT ){
  75006. assert( TK_LT==TK_GT+2 );
  75007. assert( TK_GE==TK_LE+2 );
  75008. assert( TK_GT>TK_EQ );
  75009. assert( TK_GT<TK_LE );
  75010. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  75011. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  75012. }
  75013. }
  75014. /*
  75015. ** Translate from TK_xx operator to WO_xx bitmask.
  75016. */
  75017. static u16 operatorMask(int op){
  75018. u16 c;
  75019. assert( allowedOp(op) );
  75020. if( op==TK_IN ){
  75021. c = WO_IN;
  75022. }else if( op==TK_ISNULL ){
  75023. c = WO_ISNULL;
  75024. }else{
  75025. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  75026. c = (u16)(WO_EQ<<(op-TK_EQ));
  75027. }
  75028. assert( op!=TK_ISNULL || c==WO_ISNULL );
  75029. assert( op!=TK_IN || c==WO_IN );
  75030. assert( op!=TK_EQ || c==WO_EQ );
  75031. assert( op!=TK_LT || c==WO_LT );
  75032. assert( op!=TK_LE || c==WO_LE );
  75033. assert( op!=TK_GT || c==WO_GT );
  75034. assert( op!=TK_GE || c==WO_GE );
  75035. return c;
  75036. }
  75037. /*
  75038. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  75039. ** where X is a reference to the iColumn of table iCur and <op> is one of
  75040. ** the WO_xx operator codes specified by the op parameter.
  75041. ** Return a pointer to the term. Return 0 if not found.
  75042. */
  75043. static WhereTerm *findTerm(
  75044. WhereClause *pWC, /* The WHERE clause to be searched */
  75045. int iCur, /* Cursor number of LHS */
  75046. int iColumn, /* Column number of LHS */
  75047. Bitmask notReady, /* RHS must not overlap with this mask */
  75048. u32 op, /* Mask of WO_xx values describing operator */
  75049. Index *pIdx /* Must be compatible with this index, if not NULL */
  75050. ){
  75051. WhereTerm *pTerm;
  75052. int k;
  75053. assert( iCur>=0 );
  75054. op &= WO_ALL;
  75055. for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
  75056. if( pTerm->leftCursor==iCur
  75057. && (pTerm->prereqRight & notReady)==0
  75058. && pTerm->u.leftColumn==iColumn
  75059. && (pTerm->eOperator & op)!=0
  75060. ){
  75061. if( pIdx && pTerm->eOperator!=WO_ISNULL ){
  75062. Expr *pX = pTerm->pExpr;
  75063. CollSeq *pColl;
  75064. char idxaff;
  75065. int j;
  75066. Parse *pParse = pWC->pParse;
  75067. idxaff = pIdx->pTable->aCol[iColumn].affinity;
  75068. if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
  75069. /* Figure out the collation sequence required from an index for
  75070. ** it to be useful for optimising expression pX. Store this
  75071. ** value in variable pColl.
  75072. */
  75073. assert(pX->pLeft);
  75074. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  75075. assert(pColl || pParse->nErr);
  75076. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  75077. if( NEVER(j>=pIdx->nColumn) ) return 0;
  75078. }
  75079. if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
  75080. }
  75081. return pTerm;
  75082. }
  75083. }
  75084. return 0;
  75085. }
  75086. /* Forward reference */
  75087. static void exprAnalyze(SrcList*, WhereClause*, int);
  75088. /*
  75089. ** Call exprAnalyze on all terms in a WHERE clause.
  75090. **
  75091. **
  75092. */
  75093. static void exprAnalyzeAll(
  75094. SrcList *pTabList, /* the FROM clause */
  75095. WhereClause *pWC /* the WHERE clause to be analyzed */
  75096. ){
  75097. int i;
  75098. for(i=pWC->nTerm-1; i>=0; i--){
  75099. exprAnalyze(pTabList, pWC, i);
  75100. }
  75101. }
  75102. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  75103. /*
  75104. ** Check to see if the given expression is a LIKE or GLOB operator that
  75105. ** can be optimized using inequality constraints. Return TRUE if it is
  75106. ** so and false if not.
  75107. **
  75108. ** In order for the operator to be optimizible, the RHS must be a string
  75109. ** literal that does not begin with a wildcard.
  75110. */
  75111. static int isLikeOrGlob(
  75112. Parse *pParse, /* Parsing and code generating context */
  75113. Expr *pExpr, /* Test this expression */
  75114. int *pnPattern, /* Number of non-wildcard prefix characters */
  75115. int *pisComplete, /* True if the only wildcard is % in the last character */
  75116. int *pnoCase /* True if uppercase is equivalent to lowercase */
  75117. ){
  75118. const char *z; /* String on RHS of LIKE operator */
  75119. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  75120. ExprList *pList; /* List of operands to the LIKE operator */
  75121. int c; /* One character in z[] */
  75122. int cnt; /* Number of non-wildcard prefix characters */
  75123. char wc[3]; /* Wildcard characters */
  75124. CollSeq *pColl; /* Collating sequence for LHS */
  75125. sqlite3 *db = pParse->db; /* Database connection */
  75126. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  75127. return 0;
  75128. }
  75129. #ifdef SQLITE_EBCDIC
  75130. if( *pnoCase ) return 0;
  75131. #endif
  75132. pList = pExpr->pList;
  75133. pRight = pList->a[0].pExpr;
  75134. if( pRight->op!=TK_STRING ){
  75135. return 0;
  75136. }
  75137. pLeft = pList->a[1].pExpr;
  75138. if( pLeft->op!=TK_COLUMN ){
  75139. return 0;
  75140. }
  75141. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  75142. assert( pColl!=0 || pLeft->iColumn==-1 );
  75143. if( pColl==0 ){
  75144. /* No collation is defined for the ROWID. Use the default. */
  75145. pColl = db->pDfltColl;
  75146. }
  75147. if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
  75148. (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
  75149. return 0;
  75150. }
  75151. sqlite3DequoteExpr(db, pRight);
  75152. z = (char *)pRight->token.z;
  75153. cnt = 0;
  75154. if( z ){
  75155. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
  75156. }
  75157. if( cnt==0 || 255==(u8)z[cnt-1] ){
  75158. return 0;
  75159. }
  75160. *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
  75161. *pnPattern = cnt;
  75162. return 1;
  75163. }
  75164. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  75165. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75166. /*
  75167. ** Check to see if the given expression is of the form
  75168. **
  75169. ** column MATCH expr
  75170. **
  75171. ** If it is then return TRUE. If not, return FALSE.
  75172. */
  75173. static int isMatchOfColumn(
  75174. Expr *pExpr /* Test this expression */
  75175. ){
  75176. ExprList *pList;
  75177. if( pExpr->op!=TK_FUNCTION ){
  75178. return 0;
  75179. }
  75180. if( pExpr->token.n!=5 ||
  75181. sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
  75182. return 0;
  75183. }
  75184. pList = pExpr->pList;
  75185. if( pList->nExpr!=2 ){
  75186. return 0;
  75187. }
  75188. if( pList->a[1].pExpr->op != TK_COLUMN ){
  75189. return 0;
  75190. }
  75191. return 1;
  75192. }
  75193. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75194. /*
  75195. ** If the pBase expression originated in the ON or USING clause of
  75196. ** a join, then transfer the appropriate markings over to derived.
  75197. */
  75198. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  75199. pDerived->flags |= pBase->flags & EP_FromJoin;
  75200. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  75201. }
  75202. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  75203. /*
  75204. ** Analyze a term that consists of two or more OR-connected
  75205. ** subterms. So in:
  75206. **
  75207. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  75208. ** ^^^^^^^^^^^^^^^^^^^^
  75209. **
  75210. ** This routine analyzes terms such as the middle term in the above example.
  75211. ** A WhereOrTerm object is computed and attached to the term under
  75212. ** analysis, regardless of the outcome of the analysis. Hence:
  75213. **
  75214. ** WhereTerm.wtFlags |= TERM_ORINFO
  75215. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  75216. **
  75217. ** The term being analyzed must have two or more of OR-connected subterms.
  75218. ** A single subterm might be a set of AND-connected sub-subterms.
  75219. ** Examples of terms under analysis:
  75220. **
  75221. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  75222. ** (B) x=expr1 OR expr2=x OR x=expr3
  75223. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  75224. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  75225. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  75226. **
  75227. ** CASE 1:
  75228. **
  75229. ** If all subterms are of the form T.C=expr for some single column of C
  75230. ** a single table T (as shown in example B above) then create a new virtual
  75231. ** term that is an equivalent IN expression. In other words, if the term
  75232. ** being analyzed is:
  75233. **
  75234. ** x = expr1 OR expr2 = x OR x = expr3
  75235. **
  75236. ** then create a new virtual term like this:
  75237. **
  75238. ** x IN (expr1,expr2,expr3)
  75239. **
  75240. ** CASE 2:
  75241. **
  75242. ** If all subterms are indexable by a single table T, then set
  75243. **
  75244. ** WhereTerm.eOperator = WO_OR
  75245. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  75246. **
  75247. ** A subterm is "indexable" if it is of the form
  75248. ** "T.C <op> <expr>" where C is any column of table T and
  75249. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  75250. ** A subterm is also indexable if it is an AND of two or more
  75251. ** subsubterms at least one of which is indexable. Indexable AND
  75252. ** subterms have their eOperator set to WO_AND and they have
  75253. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  75254. **
  75255. ** From another point of view, "indexable" means that the subterm could
  75256. ** potentially be used with an index if an appropriate index exists.
  75257. ** This analysis does not consider whether or not the index exists; that
  75258. ** is something the bestIndex() routine will determine. This analysis
  75259. ** only looks at whether subterms appropriate for indexing exist.
  75260. **
  75261. ** All examples A through E above all satisfy case 2. But if a term
  75262. ** also statisfies case 1 (such as B) we know that the optimizer will
  75263. ** always prefer case 1, so in that case we pretend that case 2 is not
  75264. ** satisfied.
  75265. **
  75266. ** It might be the case that multiple tables are indexable. For example,
  75267. ** (E) above is indexable on tables P, Q, and R.
  75268. **
  75269. ** Terms that satisfy case 2 are candidates for lookup by using
  75270. ** separate indices to find rowids for each subterm and composing
  75271. ** the union of all rowids using a RowSet object. This is similar
  75272. ** to "bitmap indices" in other database engines.
  75273. **
  75274. ** OTHERWISE:
  75275. **
  75276. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  75277. ** zero. This term is not useful for search.
  75278. */
  75279. static void exprAnalyzeOrTerm(
  75280. SrcList *pSrc, /* the FROM clause */
  75281. WhereClause *pWC, /* the complete WHERE clause */
  75282. int idxTerm /* Index of the OR-term to be analyzed */
  75283. ){
  75284. Parse *pParse = pWC->pParse; /* Parser context */
  75285. sqlite3 *db = pParse->db; /* Database connection */
  75286. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  75287. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  75288. WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
  75289. int i; /* Loop counters */
  75290. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  75291. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  75292. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  75293. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  75294. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  75295. /*
  75296. ** Break the OR clause into its separate subterms. The subterms are
  75297. ** stored in a WhereClause structure containing within the WhereOrInfo
  75298. ** object that is attached to the original OR clause term.
  75299. */
  75300. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  75301. assert( pExpr->op==TK_OR );
  75302. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  75303. if( pOrInfo==0 ) return;
  75304. pTerm->wtFlags |= TERM_ORINFO;
  75305. pOrWc = &pOrInfo->wc;
  75306. whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
  75307. whereSplit(pOrWc, pExpr, TK_OR);
  75308. exprAnalyzeAll(pSrc, pOrWc);
  75309. if( db->mallocFailed ) return;
  75310. assert( pOrWc->nTerm>=2 );
  75311. /*
  75312. ** Compute the set of tables that might satisfy cases 1 or 2.
  75313. */
  75314. indexable = chngToIN = ~(Bitmask)0;
  75315. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  75316. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  75317. WhereAndInfo *pAndInfo;
  75318. assert( pOrTerm->eOperator==0 );
  75319. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  75320. chngToIN = 0;
  75321. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  75322. if( pAndInfo ){
  75323. WhereClause *pAndWC;
  75324. WhereTerm *pAndTerm;
  75325. int j;
  75326. Bitmask b = 0;
  75327. pOrTerm->u.pAndInfo = pAndInfo;
  75328. pOrTerm->wtFlags |= TERM_ANDINFO;
  75329. pOrTerm->eOperator = WO_AND;
  75330. pAndWC = &pAndInfo->wc;
  75331. whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
  75332. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  75333. exprAnalyzeAll(pSrc, pAndWC);
  75334. testcase( db->mallocFailed );
  75335. if( !db->mallocFailed ){
  75336. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  75337. assert( pAndTerm->pExpr );
  75338. if( allowedOp(pAndTerm->pExpr->op) ){
  75339. b |= getMask(pMaskSet, pAndTerm->leftCursor);
  75340. }
  75341. }
  75342. }
  75343. indexable &= b;
  75344. }
  75345. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  75346. /* Skip this term for now. We revisit it when we process the
  75347. ** corresponding TERM_VIRTUAL term */
  75348. }else{
  75349. Bitmask b;
  75350. b = getMask(pMaskSet, pOrTerm->leftCursor);
  75351. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  75352. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  75353. b |= getMask(pMaskSet, pOther->leftCursor);
  75354. }
  75355. indexable &= b;
  75356. if( pOrTerm->eOperator!=WO_EQ ){
  75357. chngToIN = 0;
  75358. }else{
  75359. chngToIN &= b;
  75360. }
  75361. }
  75362. }
  75363. /*
  75364. ** Record the set of tables that satisfy case 2. The set might be
  75365. ** empty.
  75366. */
  75367. pOrInfo->indexable = indexable;
  75368. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  75369. /*
  75370. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  75371. ** we have to do some additional checking to see if case 1 really
  75372. ** is satisfied.
  75373. */
  75374. if( chngToIN ){
  75375. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  75376. int iColumn = -1; /* Column index on lhs of IN operator */
  75377. int iCursor; /* Table cursor common to all terms */
  75378. int j = 0; /* Loop counter */
  75379. /* Search for a table and column that appears on one side or the
  75380. ** other of the == operator in every subterm. That table and column
  75381. ** will be recorded in iCursor and iColumn. There might not be any
  75382. ** such table and column. Set okToChngToIN if an appropriate table
  75383. ** and column is found but leave okToChngToIN false if not found.
  75384. */
  75385. for(j=0; j<2 && !okToChngToIN; j++){
  75386. pOrTerm = pOrWc->a;
  75387. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  75388. assert( pOrTerm->eOperator==WO_EQ );
  75389. pOrTerm->wtFlags &= ~TERM_OR_OK;
  75390. if( pOrTerm->leftCursor==iColumn ) continue;
  75391. if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ) continue;
  75392. iColumn = pOrTerm->u.leftColumn;
  75393. iCursor = pOrTerm->leftCursor;
  75394. break;
  75395. }
  75396. if( i<0 ){
  75397. assert( j==1 );
  75398. assert( (chngToIN&(chngToIN-1))==0 );
  75399. assert( chngToIN==getMask(pMaskSet, iColumn) );
  75400. break;
  75401. }
  75402. okToChngToIN = 1;
  75403. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  75404. assert( pOrTerm->eOperator==WO_EQ );
  75405. if( pOrTerm->leftCursor!=iCursor ){
  75406. pOrTerm->wtFlags &= ~TERM_OR_OK;
  75407. }else if( pOrTerm->u.leftColumn!=iColumn ){
  75408. okToChngToIN = 0;
  75409. }else{
  75410. int affLeft, affRight;
  75411. /* If the right-hand side is also a column, then the affinities
  75412. ** of both right and left sides must be such that no type
  75413. ** conversions are required on the right. (Ticket #2249)
  75414. */
  75415. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  75416. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  75417. if( affRight!=0 && affRight!=affLeft ){
  75418. okToChngToIN = 0;
  75419. }else{
  75420. pOrTerm->wtFlags |= TERM_OR_OK;
  75421. }
  75422. }
  75423. }
  75424. }
  75425. /* At this point, okToChngToIN is true if original pTerm satisfies
  75426. ** case 1. In that case, construct a new virtual term that is
  75427. ** pTerm converted into an IN operator.
  75428. */
  75429. if( okToChngToIN ){
  75430. Expr *pDup; /* A transient duplicate expression */
  75431. ExprList *pList = 0; /* The RHS of the IN operator */
  75432. Expr *pLeft = 0; /* The LHS of the IN operator */
  75433. Expr *pNew; /* The complete IN operator */
  75434. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  75435. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  75436. assert( pOrTerm->eOperator==WO_EQ );
  75437. assert( pOrTerm->leftCursor==iCursor );
  75438. assert( pOrTerm->u.leftColumn==iColumn );
  75439. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
  75440. pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
  75441. pLeft = pOrTerm->pExpr->pLeft;
  75442. }
  75443. assert( pLeft!=0 );
  75444. pDup = sqlite3ExprDup(db, pLeft);
  75445. pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
  75446. if( pNew ){
  75447. int idxNew;
  75448. transferJoinMarkings(pNew, pExpr);
  75449. pNew->pList = pList;
  75450. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  75451. testcase( idxNew==0 );
  75452. exprAnalyze(pSrc, pWC, idxNew);
  75453. pTerm = &pWC->a[idxTerm];
  75454. pWC->a[idxNew].iParent = idxTerm;
  75455. pTerm->nChild = 1;
  75456. }else{
  75457. sqlite3ExprListDelete(db, pList);
  75458. }
  75459. pTerm->eOperator = 0; /* case 1 trumps case 2 */
  75460. }
  75461. }
  75462. }
  75463. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  75464. /*
  75465. ** The input to this routine is an WhereTerm structure with only the
  75466. ** "pExpr" field filled in. The job of this routine is to analyze the
  75467. ** subexpression and populate all the other fields of the WhereTerm
  75468. ** structure.
  75469. **
  75470. ** If the expression is of the form "<expr> <op> X" it gets commuted
  75471. ** to the standard form of "X <op> <expr>".
  75472. **
  75473. ** If the expression is of the form "X <op> Y" where both X and Y are
  75474. ** columns, then the original expression is unchanged and a new virtual
  75475. ** term of the form "Y <op> X" is added to the WHERE clause and
  75476. ** analyzed separately. The original term is marked with TERM_COPIED
  75477. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  75478. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  75479. ** is a commuted copy of a prior term.) The original term has nChild=1
  75480. ** and the copy has idxParent set to the index of the original term.
  75481. */
  75482. static void exprAnalyze(
  75483. SrcList *pSrc, /* the FROM clause */
  75484. WhereClause *pWC, /* the WHERE clause */
  75485. int idxTerm /* Index of the term to be analyzed */
  75486. ){
  75487. WhereTerm *pTerm; /* The term to be analyzed */
  75488. WhereMaskSet *pMaskSet; /* Set of table index masks */
  75489. Expr *pExpr; /* The expression to be analyzed */
  75490. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  75491. Bitmask prereqAll; /* Prerequesites of pExpr */
  75492. Bitmask extraRight = 0;
  75493. int nPattern;
  75494. int isComplete;
  75495. int noCase;
  75496. int op; /* Top-level operator. pExpr->op */
  75497. Parse *pParse = pWC->pParse; /* Parsing context */
  75498. sqlite3 *db = pParse->db; /* Database connection */
  75499. if( db->mallocFailed ){
  75500. return;
  75501. }
  75502. pTerm = &pWC->a[idxTerm];
  75503. pMaskSet = pWC->pMaskSet;
  75504. pExpr = pTerm->pExpr;
  75505. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  75506. op = pExpr->op;
  75507. if( op==TK_IN ){
  75508. assert( pExpr->pRight==0 );
  75509. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
  75510. | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
  75511. }else if( op==TK_ISNULL ){
  75512. pTerm->prereqRight = 0;
  75513. }else{
  75514. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  75515. }
  75516. prereqAll = exprTableUsage(pMaskSet, pExpr);
  75517. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  75518. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  75519. prereqAll |= x;
  75520. extraRight = x-1; /* ON clause terms may not be used with an index
  75521. ** on left table of a LEFT JOIN. Ticket #3015 */
  75522. }
  75523. pTerm->prereqAll = prereqAll;
  75524. pTerm->leftCursor = -1;
  75525. pTerm->iParent = -1;
  75526. pTerm->eOperator = 0;
  75527. if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
  75528. Expr *pLeft = pExpr->pLeft;
  75529. Expr *pRight = pExpr->pRight;
  75530. if( pLeft->op==TK_COLUMN ){
  75531. pTerm->leftCursor = pLeft->iTable;
  75532. pTerm->u.leftColumn = pLeft->iColumn;
  75533. pTerm->eOperator = operatorMask(op);
  75534. }
  75535. if( pRight && pRight->op==TK_COLUMN ){
  75536. WhereTerm *pNew;
  75537. Expr *pDup;
  75538. if( pTerm->leftCursor>=0 ){
  75539. int idxNew;
  75540. pDup = sqlite3ExprDup(db, pExpr);
  75541. if( db->mallocFailed ){
  75542. sqlite3ExprDelete(db, pDup);
  75543. return;
  75544. }
  75545. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  75546. if( idxNew==0 ) return;
  75547. pNew = &pWC->a[idxNew];
  75548. pNew->iParent = idxTerm;
  75549. pTerm = &pWC->a[idxTerm];
  75550. pTerm->nChild = 1;
  75551. pTerm->wtFlags |= TERM_COPIED;
  75552. }else{
  75553. pDup = pExpr;
  75554. pNew = pTerm;
  75555. }
  75556. exprCommute(pParse, pDup);
  75557. pLeft = pDup->pLeft;
  75558. pNew->leftCursor = pLeft->iTable;
  75559. pNew->u.leftColumn = pLeft->iColumn;
  75560. pNew->prereqRight = prereqLeft;
  75561. pNew->prereqAll = prereqAll;
  75562. pNew->eOperator = operatorMask(pDup->op);
  75563. }
  75564. }
  75565. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  75566. /* If a term is the BETWEEN operator, create two new virtual terms
  75567. ** that define the range that the BETWEEN implements. For example:
  75568. **
  75569. ** a BETWEEN b AND c
  75570. **
  75571. ** is converted into:
  75572. **
  75573. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  75574. **
  75575. ** The two new terms are added onto the end of the WhereClause object.
  75576. ** The new terms are "dynamic" and are children of the original BETWEEN
  75577. ** term. That means that if the BETWEEN term is coded, the children are
  75578. ** skipped. Or, if the children are satisfied by an index, the original
  75579. ** BETWEEN term is skipped.
  75580. */
  75581. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  75582. ExprList *pList = pExpr->pList;
  75583. int i;
  75584. static const u8 ops[] = {TK_GE, TK_LE};
  75585. assert( pList!=0 );
  75586. assert( pList->nExpr==2 );
  75587. for(i=0; i<2; i++){
  75588. Expr *pNewExpr;
  75589. int idxNew;
  75590. pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
  75591. sqlite3ExprDup(db, pList->a[i].pExpr), 0);
  75592. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  75593. testcase( idxNew==0 );
  75594. exprAnalyze(pSrc, pWC, idxNew);
  75595. pTerm = &pWC->a[idxTerm];
  75596. pWC->a[idxNew].iParent = idxTerm;
  75597. }
  75598. pTerm->nChild = 2;
  75599. }
  75600. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  75601. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  75602. /* Analyze a term that is composed of two or more subterms connected by
  75603. ** an OR operator.
  75604. */
  75605. else if( pExpr->op==TK_OR ){
  75606. assert( pWC->op==TK_AND );
  75607. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  75608. }
  75609. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  75610. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  75611. /* Add constraints to reduce the search space on a LIKE or GLOB
  75612. ** operator.
  75613. **
  75614. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  75615. **
  75616. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  75617. **
  75618. ** The last character of the prefix "abc" is incremented to form the
  75619. ** termination condition "abd".
  75620. */
  75621. if( isLikeOrGlob(pParse, pExpr, &nPattern, &isComplete, &noCase)
  75622. && pWC->op==TK_AND ){
  75623. Expr *pLeft, *pRight;
  75624. Expr *pStr1, *pStr2;
  75625. Expr *pNewExpr1, *pNewExpr2;
  75626. int idxNew1, idxNew2;
  75627. pLeft = pExpr->pList->a[1].pExpr;
  75628. pRight = pExpr->pList->a[0].pExpr;
  75629. pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
  75630. if( pStr1 ){
  75631. sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
  75632. pStr1->token.n = nPattern;
  75633. pStr1->flags = EP_Dequoted;
  75634. }
  75635. pStr2 = sqlite3ExprDup(db, pStr1);
  75636. if( !db->mallocFailed ){
  75637. u8 c, *pC;
  75638. assert( pStr2->token.dyn );
  75639. pC = (u8*)&pStr2->token.z[nPattern-1];
  75640. c = *pC;
  75641. if( noCase ){
  75642. if( c=='@' ) isComplete = 0;
  75643. c = sqlite3UpperToLower[c];
  75644. }
  75645. *pC = c + 1;
  75646. }
  75647. pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
  75648. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  75649. testcase( idxNew1==0 );
  75650. exprAnalyze(pSrc, pWC, idxNew1);
  75651. pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
  75652. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  75653. testcase( idxNew2==0 );
  75654. exprAnalyze(pSrc, pWC, idxNew2);
  75655. pTerm = &pWC->a[idxTerm];
  75656. if( isComplete ){
  75657. pWC->a[idxNew1].iParent = idxTerm;
  75658. pWC->a[idxNew2].iParent = idxTerm;
  75659. pTerm->nChild = 2;
  75660. }
  75661. }
  75662. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  75663. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75664. /* Add a WO_MATCH auxiliary term to the constraint set if the
  75665. ** current expression is of the form: column MATCH expr.
  75666. ** This information is used by the xBestIndex methods of
  75667. ** virtual tables. The native query optimizer does not attempt
  75668. ** to do anything with MATCH functions.
  75669. */
  75670. if( isMatchOfColumn(pExpr) ){
  75671. int idxNew;
  75672. Expr *pRight, *pLeft;
  75673. WhereTerm *pNewTerm;
  75674. Bitmask prereqColumn, prereqExpr;
  75675. pRight = pExpr->pList->a[0].pExpr;
  75676. pLeft = pExpr->pList->a[1].pExpr;
  75677. prereqExpr = exprTableUsage(pMaskSet, pRight);
  75678. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  75679. if( (prereqExpr & prereqColumn)==0 ){
  75680. Expr *pNewExpr;
  75681. pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
  75682. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  75683. testcase( idxNew==0 );
  75684. pNewTerm = &pWC->a[idxNew];
  75685. pNewTerm->prereqRight = prereqExpr;
  75686. pNewTerm->leftCursor = pLeft->iTable;
  75687. pNewTerm->u.leftColumn = pLeft->iColumn;
  75688. pNewTerm->eOperator = WO_MATCH;
  75689. pNewTerm->iParent = idxTerm;
  75690. pTerm = &pWC->a[idxTerm];
  75691. pTerm->nChild = 1;
  75692. pTerm->wtFlags |= TERM_COPIED;
  75693. pNewTerm->prereqAll = pTerm->prereqAll;
  75694. }
  75695. }
  75696. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75697. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  75698. ** an index for tables to the left of the join.
  75699. */
  75700. pTerm->prereqRight |= extraRight;
  75701. }
  75702. /*
  75703. ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
  75704. ** a reference to any table other than the iBase table.
  75705. */
  75706. static int referencesOtherTables(
  75707. ExprList *pList, /* Search expressions in ths list */
  75708. WhereMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
  75709. int iFirst, /* Be searching with the iFirst-th expression */
  75710. int iBase /* Ignore references to this table */
  75711. ){
  75712. Bitmask allowed = ~getMask(pMaskSet, iBase);
  75713. while( iFirst<pList->nExpr ){
  75714. if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
  75715. return 1;
  75716. }
  75717. }
  75718. return 0;
  75719. }
  75720. /*
  75721. ** This routine decides if pIdx can be used to satisfy the ORDER BY
  75722. ** clause. If it can, it returns 1. If pIdx cannot satisfy the
  75723. ** ORDER BY clause, this routine returns 0.
  75724. **
  75725. ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
  75726. ** left-most table in the FROM clause of that same SELECT statement and
  75727. ** the table has a cursor number of "base". pIdx is an index on pTab.
  75728. **
  75729. ** nEqCol is the number of columns of pIdx that are used as equality
  75730. ** constraints. Any of these columns may be missing from the ORDER BY
  75731. ** clause and the match can still be a success.
  75732. **
  75733. ** All terms of the ORDER BY that match against the index must be either
  75734. ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
  75735. ** index do not need to satisfy this constraint.) The *pbRev value is
  75736. ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
  75737. ** the ORDER BY clause is all ASC.
  75738. */
  75739. static int isSortingIndex(
  75740. Parse *pParse, /* Parsing context */
  75741. WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
  75742. Index *pIdx, /* The index we are testing */
  75743. int base, /* Cursor number for the table to be sorted */
  75744. ExprList *pOrderBy, /* The ORDER BY clause */
  75745. int nEqCol, /* Number of index columns with == constraints */
  75746. int *pbRev /* Set to 1 if ORDER BY is DESC */
  75747. ){
  75748. int i, j; /* Loop counters */
  75749. int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
  75750. int nTerm; /* Number of ORDER BY terms */
  75751. struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
  75752. sqlite3 *db = pParse->db;
  75753. assert( pOrderBy!=0 );
  75754. nTerm = pOrderBy->nExpr;
  75755. assert( nTerm>0 );
  75756. /* Match terms of the ORDER BY clause against columns of
  75757. ** the index.
  75758. **
  75759. ** Note that indices have pIdx->nColumn regular columns plus
  75760. ** one additional column containing the rowid. The rowid column
  75761. ** of the index is also allowed to match against the ORDER BY
  75762. ** clause.
  75763. */
  75764. for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
  75765. Expr *pExpr; /* The expression of the ORDER BY pTerm */
  75766. CollSeq *pColl; /* The collating sequence of pExpr */
  75767. int termSortOrder; /* Sort order for this term */
  75768. int iColumn; /* The i-th column of the index. -1 for rowid */
  75769. int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
  75770. const char *zColl; /* Name of the collating sequence for i-th index term */
  75771. pExpr = pTerm->pExpr;
  75772. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
  75773. /* Can not use an index sort on anything that is not a column in the
  75774. ** left-most table of the FROM clause */
  75775. break;
  75776. }
  75777. pColl = sqlite3ExprCollSeq(pParse, pExpr);
  75778. if( !pColl ){
  75779. pColl = db->pDfltColl;
  75780. }
  75781. if( i<pIdx->nColumn ){
  75782. iColumn = pIdx->aiColumn[i];
  75783. if( iColumn==pIdx->pTable->iPKey ){
  75784. iColumn = -1;
  75785. }
  75786. iSortOrder = pIdx->aSortOrder[i];
  75787. zColl = pIdx->azColl[i];
  75788. }else{
  75789. iColumn = -1;
  75790. iSortOrder = 0;
  75791. zColl = pColl->zName;
  75792. }
  75793. if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
  75794. /* Term j of the ORDER BY clause does not match column i of the index */
  75795. if( i<nEqCol ){
  75796. /* If an index column that is constrained by == fails to match an
  75797. ** ORDER BY term, that is OK. Just ignore that column of the index
  75798. */
  75799. continue;
  75800. }else if( i==pIdx->nColumn ){
  75801. /* Index column i is the rowid. All other terms match. */
  75802. break;
  75803. }else{
  75804. /* If an index column fails to match and is not constrained by ==
  75805. ** then the index cannot satisfy the ORDER BY constraint.
  75806. */
  75807. return 0;
  75808. }
  75809. }
  75810. assert( pIdx->aSortOrder!=0 );
  75811. assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
  75812. assert( iSortOrder==0 || iSortOrder==1 );
  75813. termSortOrder = iSortOrder ^ pTerm->sortOrder;
  75814. if( i>nEqCol ){
  75815. if( termSortOrder!=sortOrder ){
  75816. /* Indices can only be used if all ORDER BY terms past the
  75817. ** equality constraints are all either DESC or ASC. */
  75818. return 0;
  75819. }
  75820. }else{
  75821. sortOrder = termSortOrder;
  75822. }
  75823. j++;
  75824. pTerm++;
  75825. if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
  75826. /* If the indexed column is the primary key and everything matches
  75827. ** so far and none of the ORDER BY terms to the right reference other
  75828. ** tables in the join, then we are assured that the index can be used
  75829. ** to sort because the primary key is unique and so none of the other
  75830. ** columns will make any difference
  75831. */
  75832. j = nTerm;
  75833. }
  75834. }
  75835. *pbRev = sortOrder!=0;
  75836. if( j>=nTerm ){
  75837. /* All terms of the ORDER BY clause are covered by this index so
  75838. ** this index can be used for sorting. */
  75839. return 1;
  75840. }
  75841. if( pIdx->onError!=OE_None && i==pIdx->nColumn
  75842. && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
  75843. /* All terms of this index match some prefix of the ORDER BY clause
  75844. ** and the index is UNIQUE and no terms on the tail of the ORDER BY
  75845. ** clause reference other tables in a join. If this is all true then
  75846. ** the order by clause is superfluous. */
  75847. return 1;
  75848. }
  75849. return 0;
  75850. }
  75851. /*
  75852. ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
  75853. ** by sorting in order of ROWID. Return true if so and set *pbRev to be
  75854. ** true for reverse ROWID and false for forward ROWID order.
  75855. */
  75856. static int sortableByRowid(
  75857. int base, /* Cursor number for table to be sorted */
  75858. ExprList *pOrderBy, /* The ORDER BY clause */
  75859. WhereMaskSet *pMaskSet, /* Mapping from table cursors to bitmaps */
  75860. int *pbRev /* Set to 1 if ORDER BY is DESC */
  75861. ){
  75862. Expr *p;
  75863. assert( pOrderBy!=0 );
  75864. assert( pOrderBy->nExpr>0 );
  75865. p = pOrderBy->a[0].pExpr;
  75866. if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
  75867. && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
  75868. *pbRev = pOrderBy->a[0].sortOrder;
  75869. return 1;
  75870. }
  75871. return 0;
  75872. }
  75873. /*
  75874. ** Prepare a crude estimate of the logarithm of the input value.
  75875. ** The results need not be exact. This is only used for estimating
  75876. ** the total cost of performing operations with O(logN) or O(NlogN)
  75877. ** complexity. Because N is just a guess, it is no great tragedy if
  75878. ** logN is a little off.
  75879. */
  75880. static double estLog(double N){
  75881. double logN = 1;
  75882. double x = 10;
  75883. while( N>x ){
  75884. logN += 1;
  75885. x *= 10;
  75886. }
  75887. return logN;
  75888. }
  75889. /*
  75890. ** Two routines for printing the content of an sqlite3_index_info
  75891. ** structure. Used for testing and debugging only. If neither
  75892. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  75893. ** are no-ops.
  75894. */
  75895. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
  75896. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  75897. int i;
  75898. if( !sqlite3WhereTrace ) return;
  75899. for(i=0; i<p->nConstraint; i++){
  75900. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  75901. i,
  75902. p->aConstraint[i].iColumn,
  75903. p->aConstraint[i].iTermOffset,
  75904. p->aConstraint[i].op,
  75905. p->aConstraint[i].usable);
  75906. }
  75907. for(i=0; i<p->nOrderBy; i++){
  75908. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  75909. i,
  75910. p->aOrderBy[i].iColumn,
  75911. p->aOrderBy[i].desc);
  75912. }
  75913. }
  75914. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  75915. int i;
  75916. if( !sqlite3WhereTrace ) return;
  75917. for(i=0; i<p->nConstraint; i++){
  75918. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  75919. i,
  75920. p->aConstraintUsage[i].argvIndex,
  75921. p->aConstraintUsage[i].omit);
  75922. }
  75923. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  75924. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  75925. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  75926. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  75927. }
  75928. #else
  75929. #define TRACE_IDX_INPUTS(A)
  75930. #define TRACE_IDX_OUTPUTS(A)
  75931. #endif
  75932. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75933. /*
  75934. ** Compute the best index for a virtual table.
  75935. **
  75936. ** The best index is computed by the xBestIndex method of the virtual
  75937. ** table module. This routine is really just a wrapper that sets up
  75938. ** the sqlite3_index_info structure that is used to communicate with
  75939. ** xBestIndex.
  75940. **
  75941. ** In a join, this routine might be called multiple times for the
  75942. ** same virtual table. The sqlite3_index_info structure is created
  75943. ** and initialized on the first invocation and reused on all subsequent
  75944. ** invocations. The sqlite3_index_info structure is also used when
  75945. ** code is generated to access the virtual table. The whereInfoDelete()
  75946. ** routine takes care of freeing the sqlite3_index_info structure after
  75947. ** everybody has finished with it.
  75948. */
  75949. static double bestVirtualIndex(
  75950. Parse *pParse, /* The parsing context */
  75951. WhereClause *pWC, /* The WHERE clause */
  75952. struct SrcList_item *pSrc, /* The FROM clause term to search */
  75953. Bitmask notReady, /* Mask of cursors that are not available */
  75954. ExprList *pOrderBy, /* The order by clause */
  75955. int orderByUsable, /* True if we can potential sort */
  75956. sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
  75957. ){
  75958. Table *pTab = pSrc->pTab;
  75959. sqlite3_vtab *pVtab = pTab->pVtab;
  75960. sqlite3_index_info *pIdxInfo;
  75961. struct sqlite3_index_constraint *pIdxCons;
  75962. struct sqlite3_index_orderby *pIdxOrderBy;
  75963. struct sqlite3_index_constraint_usage *pUsage;
  75964. WhereTerm *pTerm;
  75965. int i, j;
  75966. int nOrderBy;
  75967. int rc;
  75968. /* If the sqlite3_index_info structure has not been previously
  75969. ** allocated and initialized for this virtual table, then allocate
  75970. ** and initialize it now
  75971. */
  75972. pIdxInfo = *ppIdxInfo;
  75973. if( pIdxInfo==0 ){
  75974. int nTerm;
  75975. WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
  75976. /* Count the number of possible WHERE clause constraints referring
  75977. ** to this virtual table */
  75978. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  75979. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  75980. assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
  75981. testcase( pTerm->eOperator==WO_IN );
  75982. testcase( pTerm->eOperator==WO_ISNULL );
  75983. if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
  75984. nTerm++;
  75985. }
  75986. /* If the ORDER BY clause contains only columns in the current
  75987. ** virtual table then allocate space for the aOrderBy part of
  75988. ** the sqlite3_index_info structure.
  75989. */
  75990. nOrderBy = 0;
  75991. if( pOrderBy ){
  75992. for(i=0; i<pOrderBy->nExpr; i++){
  75993. Expr *pExpr = pOrderBy->a[i].pExpr;
  75994. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  75995. }
  75996. if( i==pOrderBy->nExpr ){
  75997. nOrderBy = pOrderBy->nExpr;
  75998. }
  75999. }
  76000. /* Allocate the sqlite3_index_info structure
  76001. */
  76002. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  76003. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  76004. + sizeof(*pIdxOrderBy)*nOrderBy );
  76005. if( pIdxInfo==0 ){
  76006. sqlite3ErrorMsg(pParse, "out of memory");
  76007. return 0.0;
  76008. }
  76009. *ppIdxInfo = pIdxInfo;
  76010. /* Initialize the structure. The sqlite3_index_info structure contains
  76011. ** many fields that are declared "const" to prevent xBestIndex from
  76012. ** changing them. We have to do some funky casting in order to
  76013. ** initialize those fields.
  76014. */
  76015. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  76016. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  76017. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  76018. *(int*)&pIdxInfo->nConstraint = nTerm;
  76019. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  76020. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  76021. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  76022. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  76023. pUsage;
  76024. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  76025. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  76026. assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
  76027. testcase( pTerm->eOperator==WO_IN );
  76028. testcase( pTerm->eOperator==WO_ISNULL );
  76029. if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
  76030. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  76031. pIdxCons[j].iTermOffset = i;
  76032. pIdxCons[j].op = (u8)pTerm->eOperator;
  76033. /* The direct assignment in the previous line is possible only because
  76034. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  76035. ** following asserts verify this fact. */
  76036. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  76037. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  76038. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  76039. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  76040. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  76041. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  76042. assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  76043. j++;
  76044. }
  76045. for(i=0; i<nOrderBy; i++){
  76046. Expr *pExpr = pOrderBy->a[i].pExpr;
  76047. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  76048. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  76049. }
  76050. }
  76051. /* At this point, the sqlite3_index_info structure that pIdxInfo points
  76052. ** to will have been initialized, either during the current invocation or
  76053. ** during some prior invocation. Now we just have to customize the
  76054. ** details of pIdxInfo for the current invocation and pass it to
  76055. ** xBestIndex.
  76056. */
  76057. /* The module name must be defined. Also, by this point there must
  76058. ** be a pointer to an sqlite3_vtab structure. Otherwise
  76059. ** sqlite3ViewGetColumnNames() would have picked up the error.
  76060. */
  76061. assert( pTab->azModuleArg && pTab->azModuleArg[0] );
  76062. assert( pVtab );
  76063. #if 0
  76064. if( pTab->pVtab==0 ){
  76065. sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
  76066. pTab->azModuleArg[0], pTab->zName);
  76067. return 0.0;
  76068. }
  76069. #endif
  76070. /* Set the aConstraint[].usable fields and initialize all
  76071. ** output variables to zero.
  76072. **
  76073. ** aConstraint[].usable is true for constraints where the right-hand
  76074. ** side contains only references to tables to the left of the current
  76075. ** table. In other words, if the constraint is of the form:
  76076. **
  76077. ** column = expr
  76078. **
  76079. ** and we are evaluating a join, then the constraint on column is
  76080. ** only valid if all tables referenced in expr occur to the left
  76081. ** of the table containing column.
  76082. **
  76083. ** The aConstraints[] array contains entries for all constraints
  76084. ** on the current table. That way we only have to compute it once
  76085. ** even though we might try to pick the best index multiple times.
  76086. ** For each attempt at picking an index, the order of tables in the
  76087. ** join might be different so we have to recompute the usable flag
  76088. ** each time.
  76089. */
  76090. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  76091. pUsage = pIdxInfo->aConstraintUsage;
  76092. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  76093. j = pIdxCons->iTermOffset;
  76094. pTerm = &pWC->a[j];
  76095. pIdxCons->usable = (pTerm->prereqRight & notReady)==0 ?1:0;
  76096. }
  76097. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  76098. if( pIdxInfo->needToFreeIdxStr ){
  76099. sqlite3_free(pIdxInfo->idxStr);
  76100. }
  76101. pIdxInfo->idxStr = 0;
  76102. pIdxInfo->idxNum = 0;
  76103. pIdxInfo->needToFreeIdxStr = 0;
  76104. pIdxInfo->orderByConsumed = 0;
  76105. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
  76106. nOrderBy = pIdxInfo->nOrderBy;
  76107. if( pIdxInfo->nOrderBy && !orderByUsable ){
  76108. *(int*)&pIdxInfo->nOrderBy = 0;
  76109. }
  76110. (void)sqlite3SafetyOff(pParse->db);
  76111. WHERETRACE(("xBestIndex for %s\n", pTab->zName));
  76112. TRACE_IDX_INPUTS(pIdxInfo);
  76113. rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
  76114. TRACE_IDX_OUTPUTS(pIdxInfo);
  76115. (void)sqlite3SafetyOn(pParse->db);
  76116. if( rc!=SQLITE_OK ){
  76117. if( rc==SQLITE_NOMEM ){
  76118. pParse->db->mallocFailed = 1;
  76119. }else if( !pVtab->zErrMsg ){
  76120. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  76121. }else{
  76122. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  76123. }
  76124. }
  76125. sqlite3DbFree(pParse->db, pVtab->zErrMsg);
  76126. pVtab->zErrMsg = 0;
  76127. for(i=0; i<pIdxInfo->nConstraint; i++){
  76128. if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
  76129. sqlite3ErrorMsg(pParse,
  76130. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  76131. return 0.0;
  76132. }
  76133. }
  76134. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  76135. return pIdxInfo->estimatedCost;
  76136. }
  76137. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  76138. /*
  76139. ** Find the query plan for accessing a particular table. Write the
  76140. ** best query plan and its cost into the WhereCost object supplied as the
  76141. ** last parameter.
  76142. **
  76143. ** The lowest cost plan wins. The cost is an estimate of the amount of
  76144. ** CPU and disk I/O need to process the request using the selected plan.
  76145. ** Factors that influence cost include:
  76146. **
  76147. ** * The estimated number of rows that will be retrieved. (The
  76148. ** fewer the better.)
  76149. **
  76150. ** * Whether or not sorting must occur.
  76151. **
  76152. ** * Whether or not there must be separate lookups in the
  76153. ** index and in the main table.
  76154. **
  76155. ** If there was an INDEXED BY clause attached to the table in the SELECT
  76156. ** statement, then this function only considers plans using the
  76157. ** named index. If one cannot be found, then the returned cost is
  76158. ** SQLITE_BIG_DBL. If a plan can be found that uses the named index,
  76159. ** then the cost is calculated in the usual way.
  76160. **
  76161. ** If a NOT INDEXED clause was attached to the table in the SELECT
  76162. ** statement, then no indexes are considered. However, the selected
  76163. ** plan may still take advantage of the tables built-in rowid
  76164. ** index.
  76165. */
  76166. static void bestIndex(
  76167. Parse *pParse, /* The parsing context */
  76168. WhereClause *pWC, /* The WHERE clause */
  76169. struct SrcList_item *pSrc, /* The FROM clause term to search */
  76170. Bitmask notReady, /* Mask of cursors that are not available */
  76171. ExprList *pOrderBy, /* The ORDER BY clause */
  76172. WhereCost *pCost /* Lowest cost query plan */
  76173. ){
  76174. WhereTerm *pTerm; /* A single term of the WHERE clause */
  76175. int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
  76176. Index *pProbe; /* An index we are evaluating */
  76177. int rev; /* True to scan in reverse order */
  76178. int wsFlags; /* Flags associated with pProbe */
  76179. int nEq; /* Number of == or IN constraints */
  76180. int eqTermMask; /* Mask of valid equality operators */
  76181. double cost; /* Cost of using pProbe */
  76182. double nRow; /* Estimated number of rows in result set */
  76183. int i; /* Loop counter */
  76184. Bitmask maskSrc; /* Bitmask for the pSrc table */
  76185. WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName,notReady));
  76186. pProbe = pSrc->pTab->pIndex;
  76187. if( pSrc->notIndexed ){
  76188. pProbe = 0;
  76189. }
  76190. /* If the table has no indices and there are no terms in the where
  76191. ** clause that refer to the ROWID, then we will never be able to do
  76192. ** anything other than a full table scan on this table. We might as
  76193. ** well put it first in the join order. That way, perhaps it can be
  76194. ** referenced by other tables in the join.
  76195. */
  76196. memset(pCost, 0, sizeof(*pCost));
  76197. if( pProbe==0 &&
  76198. findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
  76199. (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
  76200. return;
  76201. }
  76202. pCost->rCost = SQLITE_BIG_DBL;
  76203. /* Check for a rowid=EXPR or rowid IN (...) constraints. If there was
  76204. ** an INDEXED BY clause attached to this table, skip this step.
  76205. */
  76206. if( !pSrc->pIndex ){
  76207. pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
  76208. if( pTerm ){
  76209. Expr *pExpr;
  76210. pCost->plan.wsFlags = WHERE_ROWID_EQ;
  76211. if( pTerm->eOperator & WO_EQ ){
  76212. /* Rowid== is always the best pick. Look no further. Because only
  76213. ** a single row is generated, output is always in sorted order */
  76214. pCost->plan.wsFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
  76215. pCost->plan.nEq = 1;
  76216. WHERETRACE(("... best is rowid\n"));
  76217. pCost->rCost = 0;
  76218. pCost->nRow = 1;
  76219. return;
  76220. }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
  76221. /* Rowid IN (LIST): cost is NlogN where N is the number of list
  76222. ** elements. */
  76223. pCost->rCost = pCost->nRow = pExpr->pList->nExpr;
  76224. pCost->rCost *= estLog(pCost->rCost);
  76225. }else{
  76226. /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
  76227. ** in the result of the inner select. We have no way to estimate
  76228. ** that value so make a wild guess. */
  76229. pCost->nRow = 100;
  76230. pCost->rCost = 200;
  76231. }
  76232. WHERETRACE(("... rowid IN cost: %.9g\n", pCost->rCost));
  76233. }
  76234. /* Estimate the cost of a table scan. If we do not know how many
  76235. ** entries are in the table, use 1 million as a guess.
  76236. */
  76237. cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
  76238. WHERETRACE(("... table scan base cost: %.9g\n", cost));
  76239. wsFlags = WHERE_ROWID_RANGE;
  76240. /* Check for constraints on a range of rowids in a table scan.
  76241. */
  76242. pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
  76243. if( pTerm ){
  76244. if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
  76245. wsFlags |= WHERE_TOP_LIMIT;
  76246. cost /= 3; /* Guess that rowid<EXPR eliminates two-thirds of rows */
  76247. }
  76248. if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
  76249. wsFlags |= WHERE_BTM_LIMIT;
  76250. cost /= 3; /* Guess that rowid>EXPR eliminates two-thirds of rows */
  76251. }
  76252. WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
  76253. }else{
  76254. wsFlags = 0;
  76255. }
  76256. nRow = cost;
  76257. /* If the table scan does not satisfy the ORDER BY clause, increase
  76258. ** the cost by NlogN to cover the expense of sorting. */
  76259. if( pOrderBy ){
  76260. if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
  76261. wsFlags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
  76262. if( rev ){
  76263. wsFlags |= WHERE_REVERSE;
  76264. }
  76265. }else{
  76266. cost += cost*estLog(cost);
  76267. WHERETRACE(("... sorting increases cost to %.9g\n", cost));
  76268. }
  76269. }
  76270. if( cost<pCost->rCost ){
  76271. pCost->rCost = cost;
  76272. pCost->nRow = nRow;
  76273. pCost->plan.wsFlags = wsFlags;
  76274. }
  76275. }
  76276. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  76277. /* Search for an OR-clause that can be used to look up the table.
  76278. */
  76279. maskSrc = getMask(pWC->pMaskSet, iCur);
  76280. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  76281. WhereClause tempWC;
  76282. tempWC = *pWC;
  76283. if( pTerm->eOperator==WO_OR
  76284. && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
  76285. && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 ){
  76286. WhereClause *pOrWC = &pTerm->u.pOrInfo->wc;
  76287. WhereTerm *pOrTerm;
  76288. int j;
  76289. int sortable = 0;
  76290. double rTotal = 0;
  76291. nRow = 0;
  76292. for(j=0, pOrTerm=pOrWC->a; j<pOrWC->nTerm; j++, pOrTerm++){
  76293. WhereCost sTermCost;
  76294. WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", j,i));
  76295. if( pOrTerm->eOperator==WO_AND ){
  76296. WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
  76297. bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
  76298. }else if( pOrTerm->leftCursor==iCur ){
  76299. tempWC.a = pOrTerm;
  76300. tempWC.nTerm = 1;
  76301. bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
  76302. }else{
  76303. continue;
  76304. }
  76305. rTotal += sTermCost.rCost;
  76306. nRow += sTermCost.nRow;
  76307. if( rTotal>=pCost->rCost ) break;
  76308. }
  76309. if( pOrderBy!=0 ){
  76310. if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) && !rev ){
  76311. sortable = 1;
  76312. }else{
  76313. rTotal += nRow*estLog(nRow);
  76314. WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
  76315. }
  76316. }
  76317. WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n",
  76318. rTotal, nRow));
  76319. if( rTotal<pCost->rCost ){
  76320. pCost->rCost = rTotal;
  76321. pCost->nRow = nRow;
  76322. pCost->plan.wsFlags = WHERE_MULTI_OR;
  76323. pCost->plan.u.pTerm = pTerm;
  76324. if( sortable ){
  76325. pCost->plan.wsFlags = WHERE_ORDERBY|WHERE_MULTI_OR;
  76326. }
  76327. }
  76328. }
  76329. }
  76330. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  76331. /* If the pSrc table is the right table of a LEFT JOIN then we may not
  76332. ** use an index to satisfy IS NULL constraints on that table. This is
  76333. ** because columns might end up being NULL if the table does not match -
  76334. ** a circumstance which the index cannot help us discover. Ticket #2177.
  76335. */
  76336. if( (pSrc->jointype & JT_LEFT)!=0 ){
  76337. eqTermMask = WO_EQ|WO_IN;
  76338. }else{
  76339. eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
  76340. }
  76341. /* Look at each index.
  76342. */
  76343. if( pSrc->pIndex ){
  76344. pProbe = pSrc->pIndex;
  76345. }
  76346. for(; pProbe; pProbe=(pSrc->pIndex ? 0 : pProbe->pNext)){
  76347. double inMultiplier = 1;
  76348. WHERETRACE(("... index %s:\n", pProbe->zName));
  76349. /* Count the number of columns in the index that are satisfied
  76350. ** by x=EXPR constraints or x IN (...) constraints.
  76351. */
  76352. wsFlags = 0;
  76353. for(i=0; i<pProbe->nColumn; i++){
  76354. int j = pProbe->aiColumn[i];
  76355. pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
  76356. if( pTerm==0 ) break;
  76357. wsFlags |= WHERE_COLUMN_EQ;
  76358. if( pTerm->eOperator & WO_IN ){
  76359. Expr *pExpr = pTerm->pExpr;
  76360. wsFlags |= WHERE_COLUMN_IN;
  76361. if( pExpr->pSelect!=0 ){
  76362. inMultiplier *= 25;
  76363. }else if( ALWAYS(pExpr->pList) ){
  76364. inMultiplier *= pExpr->pList->nExpr + 1;
  76365. }
  76366. }
  76367. }
  76368. nRow = pProbe->aiRowEst[i] * inMultiplier;
  76369. cost = nRow * estLog(inMultiplier);
  76370. nEq = i;
  76371. if( pProbe->onError!=OE_None && (wsFlags & WHERE_COLUMN_IN)==0
  76372. && nEq==pProbe->nColumn ){
  76373. wsFlags |= WHERE_UNIQUE;
  76374. }
  76375. WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
  76376. /* Look for range constraints
  76377. */
  76378. if( nEq<pProbe->nColumn ){
  76379. int j = pProbe->aiColumn[nEq];
  76380. pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
  76381. if( pTerm ){
  76382. wsFlags |= WHERE_COLUMN_RANGE;
  76383. if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
  76384. wsFlags |= WHERE_TOP_LIMIT;
  76385. cost /= 3;
  76386. nRow /= 3;
  76387. }
  76388. if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
  76389. wsFlags |= WHERE_BTM_LIMIT;
  76390. cost /= 3;
  76391. nRow /= 3;
  76392. }
  76393. WHERETRACE(("...... range reduces cost to %.9g\n", cost));
  76394. }
  76395. }
  76396. /* Add the additional cost of sorting if that is a factor.
  76397. */
  76398. if( pOrderBy ){
  76399. if( (wsFlags & WHERE_COLUMN_IN)==0 &&
  76400. isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
  76401. if( wsFlags==0 ){
  76402. wsFlags = WHERE_COLUMN_RANGE;
  76403. }
  76404. wsFlags |= WHERE_ORDERBY;
  76405. if( rev ){
  76406. wsFlags |= WHERE_REVERSE;
  76407. }
  76408. }else{
  76409. cost += cost*estLog(cost);
  76410. WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
  76411. }
  76412. }
  76413. /* Check to see if we can get away with using just the index without
  76414. ** ever reading the table. If that is the case, then halve the
  76415. ** cost of this index.
  76416. */
  76417. if( wsFlags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
  76418. Bitmask m = pSrc->colUsed;
  76419. int j;
  76420. for(j=0; j<pProbe->nColumn; j++){
  76421. int x = pProbe->aiColumn[j];
  76422. if( x<BMS-1 ){
  76423. m &= ~(((Bitmask)1)<<x);
  76424. }
  76425. }
  76426. if( m==0 ){
  76427. wsFlags |= WHERE_IDX_ONLY;
  76428. cost /= 2;
  76429. WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
  76430. }
  76431. }
  76432. /* If this index has achieved the lowest cost so far, then use it.
  76433. */
  76434. if( wsFlags!=0 && cost < pCost->rCost ){
  76435. pCost->rCost = cost;
  76436. pCost->nRow = nRow;
  76437. pCost->plan.wsFlags = wsFlags;
  76438. pCost->plan.nEq = nEq;
  76439. assert( pCost->plan.wsFlags & WHERE_INDEXED );
  76440. pCost->plan.u.pIdx = pProbe;
  76441. }
  76442. }
  76443. /* Report the best result
  76444. */
  76445. pCost->plan.wsFlags |= eqTermMask;
  76446. WHERETRACE(("best index is %s, cost=%.9g, nrow=%.9g, wsFlags=%x, nEq=%d\n",
  76447. (pCost->plan.wsFlags & WHERE_INDEXED)!=0 ?
  76448. pCost->plan.u.pIdx->zName : "(none)", pCost->nRow,
  76449. pCost->rCost, pCost->plan.wsFlags, pCost->plan.nEq));
  76450. }
  76451. /*
  76452. ** Disable a term in the WHERE clause. Except, do not disable the term
  76453. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  76454. ** or USING clause of that join.
  76455. **
  76456. ** Consider the term t2.z='ok' in the following queries:
  76457. **
  76458. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  76459. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  76460. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  76461. **
  76462. ** The t2.z='ok' is disabled in the in (2) because it originates
  76463. ** in the ON clause. The term is disabled in (3) because it is not part
  76464. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  76465. **
  76466. ** Disabling a term causes that term to not be tested in the inner loop
  76467. ** of the join. Disabling is an optimization. When terms are satisfied
  76468. ** by indices, we disable them to prevent redundant tests in the inner
  76469. ** loop. We would get the correct results if nothing were ever disabled,
  76470. ** but joins might run a little slower. The trick is to disable as much
  76471. ** as we can without disabling too much. If we disabled in (1), we'd get
  76472. ** the wrong answer. See ticket #813.
  76473. */
  76474. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  76475. if( pTerm
  76476. && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
  76477. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  76478. ){
  76479. pTerm->wtFlags |= TERM_CODED;
  76480. if( pTerm->iParent>=0 ){
  76481. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  76482. if( (--pOther->nChild)==0 ){
  76483. disableTerm(pLevel, pOther);
  76484. }
  76485. }
  76486. }
  76487. }
  76488. /*
  76489. ** Apply the affinities associated with the first n columns of index
  76490. ** pIdx to the values in the n registers starting at base.
  76491. */
  76492. static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
  76493. if( n>0 ){
  76494. Vdbe *v = pParse->pVdbe;
  76495. assert( v!=0 );
  76496. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  76497. sqlite3IndexAffinityStr(v, pIdx);
  76498. sqlite3ExprCacheAffinityChange(pParse, base, n);
  76499. }
  76500. }
  76501. /*
  76502. ** Generate code for a single equality term of the WHERE clause. An equality
  76503. ** term can be either X=expr or X IN (...). pTerm is the term to be
  76504. ** coded.
  76505. **
  76506. ** The current value for the constraint is left in register iReg.
  76507. **
  76508. ** For a constraint of the form X=expr, the expression is evaluated and its
  76509. ** result is left on the stack. For constraints of the form X IN (...)
  76510. ** this routine sets up a loop that will iterate over all values of X.
  76511. */
  76512. static int codeEqualityTerm(
  76513. Parse *pParse, /* The parsing context */
  76514. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  76515. WhereLevel *pLevel, /* When level of the FROM clause we are working on */
  76516. int iTarget /* Attempt to leave results in this register */
  76517. ){
  76518. Expr *pX = pTerm->pExpr;
  76519. Vdbe *v = pParse->pVdbe;
  76520. int iReg; /* Register holding results */
  76521. assert( iTarget>0 );
  76522. if( pX->op==TK_EQ ){
  76523. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  76524. }else if( pX->op==TK_ISNULL ){
  76525. iReg = iTarget;
  76526. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  76527. #ifndef SQLITE_OMIT_SUBQUERY
  76528. }else{
  76529. int eType;
  76530. int iTab;
  76531. struct InLoop *pIn;
  76532. assert( pX->op==TK_IN );
  76533. iReg = iTarget;
  76534. eType = sqlite3FindInIndex(pParse, pX, 0);
  76535. iTab = pX->iTable;
  76536. sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  76537. VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
  76538. assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
  76539. if( pLevel->u.in.nIn==0 ){
  76540. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  76541. }
  76542. pLevel->u.in.nIn++;
  76543. pLevel->u.in.aInLoop =
  76544. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  76545. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  76546. pIn = pLevel->u.in.aInLoop;
  76547. if( pIn ){
  76548. pIn += pLevel->u.in.nIn - 1;
  76549. pIn->iCur = iTab;
  76550. if( eType==IN_INDEX_ROWID ){
  76551. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  76552. }else{
  76553. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  76554. }
  76555. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  76556. }else{
  76557. pLevel->u.in.nIn = 0;
  76558. }
  76559. #endif
  76560. }
  76561. disableTerm(pLevel, pTerm);
  76562. return iReg;
  76563. }
  76564. /*
  76565. ** Generate code that will evaluate all == and IN constraints for an
  76566. ** index. The values for all constraints are left on the stack.
  76567. **
  76568. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  76569. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  76570. ** The index has as many as three equality constraints, but in this
  76571. ** example, the third "c" value is an inequality. So only two
  76572. ** constraints are coded. This routine will generate code to evaluate
  76573. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  76574. ** in consecutive registers and the index of the first register is returned.
  76575. **
  76576. ** In the example above nEq==2. But this subroutine works for any value
  76577. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  76578. ** The only thing it does is allocate the pLevel->iMem memory cell.
  76579. **
  76580. ** This routine always allocates at least one memory cell and returns
  76581. ** the index of that memory cell. The code that
  76582. ** calls this routine will use that memory cell to store the termination
  76583. ** key value of the loop. If one or more IN operators appear, then
  76584. ** this routine allocates an additional nEq memory cells for internal
  76585. ** use.
  76586. */
  76587. static int codeAllEqualityTerms(
  76588. Parse *pParse, /* Parsing context */
  76589. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  76590. WhereClause *pWC, /* The WHERE clause */
  76591. Bitmask notReady, /* Which parts of FROM have not yet been coded */
  76592. int nExtraReg /* Number of extra registers to allocate */
  76593. ){
  76594. int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
  76595. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  76596. Index *pIdx; /* The index being used for this loop */
  76597. int iCur = pLevel->iTabCur; /* The cursor of the table */
  76598. WhereTerm *pTerm; /* A single constraint term */
  76599. int j; /* Loop counter */
  76600. int regBase; /* Base register */
  76601. int nReg; /* Number of registers to allocate */
  76602. /* This module is only called on query plans that use an index. */
  76603. assert( pLevel->plan.wsFlags & WHERE_INDEXED );
  76604. pIdx = pLevel->plan.u.pIdx;
  76605. /* Figure out how many memory cells we will need then allocate them.
  76606. */
  76607. regBase = pParse->nMem + 1;
  76608. nReg = pLevel->plan.nEq + nExtraReg;
  76609. pParse->nMem += nReg;
  76610. /* Evaluate the equality constraints
  76611. */
  76612. assert( pIdx->nColumn>=nEq );
  76613. for(j=0; j<nEq; j++){
  76614. int r1;
  76615. int k = pIdx->aiColumn[j];
  76616. pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
  76617. if( NEVER(pTerm==0) ) break;
  76618. assert( (pTerm->wtFlags & TERM_CODED)==0 );
  76619. r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
  76620. if( r1!=regBase+j ){
  76621. if( nReg==1 ){
  76622. sqlite3ReleaseTempReg(pParse, regBase);
  76623. regBase = r1;
  76624. }else{
  76625. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  76626. }
  76627. }
  76628. testcase( pTerm->eOperator & WO_ISNULL );
  76629. testcase( pTerm->eOperator & WO_IN );
  76630. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  76631. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  76632. }
  76633. }
  76634. return regBase;
  76635. }
  76636. /*
  76637. ** Return TRUE if the WhereClause pWC contains no terms that
  76638. ** are not virtual and which have not been coded.
  76639. **
  76640. ** To put it another way, return TRUE if no additional WHERE clauses
  76641. ** tests are required in order to establish that the current row
  76642. ** should go to output and return FALSE if there are some terms of
  76643. ** the WHERE clause that need to be validated before outputing the row.
  76644. */
  76645. static int whereRowReadyForOutput(WhereClause *pWC){
  76646. WhereTerm *pTerm;
  76647. int j;
  76648. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  76649. if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED))==0 ) return 0;
  76650. }
  76651. return 1;
  76652. }
  76653. /*
  76654. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  76655. ** implementation described by pWInfo.
  76656. */
  76657. static Bitmask codeOneLoopStart(
  76658. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  76659. int iLevel, /* Which level of pWInfo->a[] should be coded */
  76660. u8 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  76661. Bitmask notReady /* Which tables are currently available */
  76662. ){
  76663. int j, k; /* Loop counters */
  76664. int iCur; /* The VDBE cursor for the table */
  76665. int addrNxt; /* Where to jump to continue with the next IN case */
  76666. int omitTable; /* True if we use the index only */
  76667. int bRev; /* True if we need to scan in reverse order */
  76668. WhereLevel *pLevel; /* The where level to be coded */
  76669. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  76670. WhereTerm *pTerm; /* A WHERE clause term */
  76671. Parse *pParse; /* Parsing context */
  76672. Vdbe *v; /* The prepared stmt under constructions */
  76673. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  76674. int addrBrk; /* Jump here to break out of the loop */
  76675. int addrCont; /* Jump here to continue with next cycle */
  76676. int regRowSet; /* Write rowids to this RowSet if non-negative */
  76677. int codeRowSetEarly; /* True if index fully constrains the search */
  76678. pParse = pWInfo->pParse;
  76679. v = pParse->pVdbe;
  76680. pWC = pWInfo->pWC;
  76681. pLevel = &pWInfo->a[iLevel];
  76682. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  76683. iCur = pTabItem->iCursor;
  76684. bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
  76685. omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0;
  76686. regRowSet = pWInfo->regRowSet;
  76687. codeRowSetEarly = 0;
  76688. /* Create labels for the "break" and "continue" instructions
  76689. ** for the current loop. Jump to addrBrk to break out of a loop.
  76690. ** Jump to cont to go immediately to the next iteration of the
  76691. ** loop.
  76692. **
  76693. ** When there is an IN operator, we also have a "addrNxt" label that
  76694. ** means to continue with the next IN value combination. When
  76695. ** there are no IN operators in the constraints, the "addrNxt" label
  76696. ** is the same as "addrBrk".
  76697. */
  76698. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  76699. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  76700. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  76701. ** initialize a memory cell that records if this table matches any
  76702. ** row of the left table of the join.
  76703. */
  76704. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  76705. pLevel->iLeftJoin = ++pParse->nMem;
  76706. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  76707. VdbeComment((v, "init LEFT JOIN no-match flag"));
  76708. }
  76709. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76710. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  76711. /* Case 0: The table is a virtual-table. Use the VFilter and VNext
  76712. ** to access the data.
  76713. */
  76714. int iReg; /* P3 Value for OP_VFilter */
  76715. sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
  76716. int nConstraint = pVtabIdx->nConstraint;
  76717. struct sqlite3_index_constraint_usage *aUsage =
  76718. pVtabIdx->aConstraintUsage;
  76719. const struct sqlite3_index_constraint *aConstraint =
  76720. pVtabIdx->aConstraint;
  76721. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  76722. pParse->disableColCache++;
  76723. for(j=1; j<=nConstraint; j++){
  76724. for(k=0; k<nConstraint; k++){
  76725. if( aUsage[k].argvIndex==j ){
  76726. int iTerm = aConstraint[k].iTermOffset;
  76727. assert( pParse->disableColCache );
  76728. sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
  76729. break;
  76730. }
  76731. }
  76732. if( k==nConstraint ) break;
  76733. }
  76734. assert( pParse->disableColCache );
  76735. pParse->disableColCache--;
  76736. sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
  76737. sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
  76738. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
  76739. pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
  76740. pVtabIdx->needToFreeIdxStr = 0;
  76741. for(j=0; j<nConstraint; j++){
  76742. if( aUsage[j].omit ){
  76743. int iTerm = aConstraint[j].iTermOffset;
  76744. disableTerm(pLevel, &pWC->a[iTerm]);
  76745. }
  76746. }
  76747. pLevel->op = OP_VNext;
  76748. pLevel->p1 = iCur;
  76749. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  76750. codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
  76751. if( codeRowSetEarly ){
  76752. sqlite3VdbeAddOp2(v, OP_VRowid, iCur, iReg);
  76753. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, iReg);
  76754. }
  76755. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  76756. }else
  76757. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  76758. if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
  76759. /* Case 1: We can directly reference a single row using an
  76760. ** equality comparison against the ROWID field. Or
  76761. ** we reference multiple rows using a "rowid IN (...)"
  76762. ** construct.
  76763. */
  76764. int r1;
  76765. int rtmp = sqlite3GetTempReg(pParse);
  76766. pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
  76767. assert( pTerm!=0 );
  76768. assert( pTerm->pExpr!=0 );
  76769. assert( pTerm->leftCursor==iCur );
  76770. assert( omitTable==0 );
  76771. r1 = codeEqualityTerm(pParse, pTerm, pLevel, rtmp);
  76772. addrNxt = pLevel->addrNxt;
  76773. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, addrNxt);
  76774. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, r1);
  76775. codeRowSetEarly = (pWC->nTerm==1 && regRowSet>=0) ?1:0;
  76776. if( codeRowSetEarly ){
  76777. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
  76778. }
  76779. sqlite3ReleaseTempReg(pParse, rtmp);
  76780. VdbeComment((v, "pk"));
  76781. pLevel->op = OP_Noop;
  76782. }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
  76783. /* Case 2: We have an inequality comparison against the ROWID field.
  76784. */
  76785. int testOp = OP_Noop;
  76786. int start;
  76787. int memEndValue = 0;
  76788. WhereTerm *pStart, *pEnd;
  76789. assert( omitTable==0 );
  76790. pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
  76791. pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
  76792. if( bRev ){
  76793. pTerm = pStart;
  76794. pStart = pEnd;
  76795. pEnd = pTerm;
  76796. }
  76797. if( pStart ){
  76798. Expr *pX; /* The expression that defines the start bound */
  76799. int r1, rTemp; /* Registers for holding the start boundary */
  76800. /* The following constant maps TK_xx codes into corresponding
  76801. ** seek opcodes. It depends on a particular ordering of TK_xx
  76802. */
  76803. const u8 aMoveOp[] = {
  76804. /* TK_GT */ OP_SeekGt,
  76805. /* TK_LE */ OP_SeekLe,
  76806. /* TK_LT */ OP_SeekLt,
  76807. /* TK_GE */ OP_SeekGe
  76808. };
  76809. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  76810. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  76811. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  76812. pX = pStart->pExpr;
  76813. assert( pX!=0 );
  76814. assert( pStart->leftCursor==iCur );
  76815. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  76816. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  76817. VdbeComment((v, "pk"));
  76818. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  76819. sqlite3ReleaseTempReg(pParse, rTemp);
  76820. disableTerm(pLevel, pStart);
  76821. }else{
  76822. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  76823. }
  76824. if( pEnd ){
  76825. Expr *pX;
  76826. pX = pEnd->pExpr;
  76827. assert( pX!=0 );
  76828. assert( pEnd->leftCursor==iCur );
  76829. memEndValue = ++pParse->nMem;
  76830. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  76831. if( pX->op==TK_LT || pX->op==TK_GT ){
  76832. testOp = bRev ? OP_Le : OP_Ge;
  76833. }else{
  76834. testOp = bRev ? OP_Lt : OP_Gt;
  76835. }
  76836. disableTerm(pLevel, pEnd);
  76837. }
  76838. start = sqlite3VdbeCurrentAddr(v);
  76839. pLevel->op = bRev ? OP_Prev : OP_Next;
  76840. pLevel->p1 = iCur;
  76841. pLevel->p2 = start;
  76842. pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
  76843. codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
  76844. if( codeRowSetEarly || testOp!=OP_Noop ){
  76845. int r1 = sqlite3GetTempReg(pParse);
  76846. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
  76847. if( testOp!=OP_Noop ){
  76848. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, r1);
  76849. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  76850. }
  76851. if( codeRowSetEarly ){
  76852. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
  76853. }
  76854. sqlite3ReleaseTempReg(pParse, r1);
  76855. }
  76856. }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
  76857. /* Case 3: A scan using an index.
  76858. **
  76859. ** The WHERE clause may contain zero or more equality
  76860. ** terms ("==" or "IN" operators) that refer to the N
  76861. ** left-most columns of the index. It may also contain
  76862. ** inequality constraints (>, <, >= or <=) on the indexed
  76863. ** column that immediately follows the N equalities. Only
  76864. ** the right-most column can be an inequality - the rest must
  76865. ** use the "==" and "IN" operators. For example, if the
  76866. ** index is on (x,y,z), then the following clauses are all
  76867. ** optimized:
  76868. **
  76869. ** x=5
  76870. ** x=5 AND y=10
  76871. ** x=5 AND y<10
  76872. ** x=5 AND y>5 AND y<10
  76873. ** x=5 AND y=5 AND z<=10
  76874. **
  76875. ** The z<10 term of the following cannot be used, only
  76876. ** the x=5 term:
  76877. **
  76878. ** x=5 AND z<10
  76879. **
  76880. ** N may be zero if there are inequality constraints.
  76881. ** If there are no inequality constraints, then N is at
  76882. ** least one.
  76883. **
  76884. ** This case is also used when there are no WHERE clause
  76885. ** constraints but an index is selected anyway, in order
  76886. ** to force the output order to conform to an ORDER BY.
  76887. */
  76888. int aStartOp[] = {
  76889. 0,
  76890. 0,
  76891. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  76892. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  76893. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  76894. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  76895. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  76896. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  76897. };
  76898. int aEndOp[] = {
  76899. OP_Noop, /* 0: (!end_constraints) */
  76900. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  76901. OP_IdxLT /* 2: (end_constraints && bRev) */
  76902. };
  76903. int nEq = pLevel->plan.nEq;
  76904. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  76905. int regBase; /* Base register holding constraint values */
  76906. int r1; /* Temp register */
  76907. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  76908. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  76909. int startEq; /* True if range start uses ==, >= or <= */
  76910. int endEq; /* True if range end uses ==, >= or <= */
  76911. int start_constraints; /* Start of range is constrained */
  76912. int nConstraint; /* Number of constraint terms */
  76913. Index *pIdx; /* The index we will be using */
  76914. int iIdxCur; /* The VDBE cursor for the index */
  76915. int nExtraReg = 0; /* Number of extra registers needed */
  76916. int op; /* Instruction opcode */
  76917. pIdx = pLevel->plan.u.pIdx;
  76918. iIdxCur = pLevel->iIdxCur;
  76919. k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
  76920. /* If this loop satisfies a sort order (pOrderBy) request that
  76921. ** was passed to this function to implement a "SELECT min(x) ..."
  76922. ** query, then the caller will only allow the loop to run for
  76923. ** a single iteration. This means that the first row returned
  76924. ** should not have a NULL value stored in 'x'. If column 'x' is
  76925. ** the first one after the nEq equality constraints in the index,
  76926. ** this requires some special handling.
  76927. */
  76928. if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
  76929. && (pLevel->plan.wsFlags&WHERE_ORDERBY)
  76930. && (pIdx->nColumn>nEq)
  76931. ){
  76932. /* assert( pOrderBy->nExpr==1 ); */
  76933. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  76934. isMinQuery = 1;
  76935. nExtraReg = 1;
  76936. }
  76937. /* Find any inequality constraint terms for the start and end
  76938. ** of the range.
  76939. */
  76940. if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
  76941. pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
  76942. nExtraReg = 1;
  76943. }
  76944. if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
  76945. pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
  76946. nExtraReg = 1;
  76947. }
  76948. /* Generate code to evaluate all constraint terms using == or IN
  76949. ** and store the values of those terms in an array of registers
  76950. ** starting at regBase.
  76951. */
  76952. regBase = codeAllEqualityTerms(pParse, pLevel, pWC, notReady, nExtraReg);
  76953. addrNxt = pLevel->addrNxt;
  76954. /* If we are doing a reverse order scan on an ascending index, or
  76955. ** a forward order scan on a descending index, interchange the
  76956. ** start and end terms (pRangeStart and pRangeEnd).
  76957. */
  76958. if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
  76959. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  76960. }
  76961. testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
  76962. testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
  76963. testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
  76964. testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
  76965. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  76966. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  76967. start_constraints = pRangeStart || nEq>0;
  76968. /* Seek the index cursor to the start of the range. */
  76969. nConstraint = nEq;
  76970. if( pRangeStart ){
  76971. int dcc = pParse->disableColCache;
  76972. if( pRangeEnd ){
  76973. pParse->disableColCache++;
  76974. }
  76975. sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
  76976. pParse->disableColCache = dcc;
  76977. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  76978. nConstraint++;
  76979. }else if( isMinQuery ){
  76980. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  76981. nConstraint++;
  76982. startEq = 0;
  76983. start_constraints = 1;
  76984. }
  76985. codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
  76986. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  76987. assert( op!=0 );
  76988. testcase( op==OP_Rewind );
  76989. testcase( op==OP_Last );
  76990. testcase( op==OP_SeekGt );
  76991. testcase( op==OP_SeekGe );
  76992. testcase( op==OP_SeekLe );
  76993. testcase( op==OP_SeekLt );
  76994. sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase,
  76995. SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
  76996. /* Load the value for the inequality constraint at the end of the
  76997. ** range (if any).
  76998. */
  76999. nConstraint = nEq;
  77000. if( pRangeEnd ){
  77001. sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
  77002. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  77003. codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
  77004. nConstraint++;
  77005. }
  77006. /* Top of the loop body */
  77007. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  77008. /* Check if the index cursor is past the end of the range. */
  77009. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  77010. testcase( op==OP_Noop );
  77011. testcase( op==OP_IdxGE );
  77012. testcase( op==OP_IdxLT );
  77013. if( op!=OP_Noop ){
  77014. sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase,
  77015. SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
  77016. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  77017. }
  77018. /* If there are inequality constraints, check that the value
  77019. ** of the table column that the inequality contrains is not NULL.
  77020. ** If it is, jump to the next iteration of the loop.
  77021. */
  77022. r1 = sqlite3GetTempReg(pParse);
  77023. testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
  77024. testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
  77025. if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
  77026. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  77027. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  77028. }
  77029. /* Seek the table cursor, if required */
  77030. disableTerm(pLevel, pRangeStart);
  77031. disableTerm(pLevel, pRangeEnd);
  77032. codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
  77033. if( !omitTable || codeRowSetEarly ){
  77034. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
  77035. if( codeRowSetEarly ){
  77036. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
  77037. }else{
  77038. sqlite3VdbeAddOp2(v, OP_Seek, iCur, r1); /* Deferred seek */
  77039. }
  77040. }
  77041. sqlite3ReleaseTempReg(pParse, r1);
  77042. /* Record the instruction used to terminate the loop. Disable
  77043. ** WHERE clause terms made redundant by the index range scan.
  77044. */
  77045. pLevel->op = bRev ? OP_Prev : OP_Next;
  77046. pLevel->p1 = iIdxCur;
  77047. }else
  77048. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  77049. if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
  77050. /* Case 4: Two or more separately indexed terms connected by OR
  77051. **
  77052. ** Example:
  77053. **
  77054. ** CREATE TABLE t1(a,b,c,d);
  77055. ** CREATE INDEX i1 ON t1(a);
  77056. ** CREATE INDEX i2 ON t1(b);
  77057. ** CREATE INDEX i3 ON t1(c);
  77058. **
  77059. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  77060. **
  77061. ** In the example, there are three indexed terms connected by OR.
  77062. ** The top of the loop is constructed by creating a RowSet object
  77063. ** and populating it. Then looping over elements of the rowset.
  77064. **
  77065. ** Null 1
  77066. ** # fill RowSet 1 with entries where a=5 using i1
  77067. ** # fill Rowset 1 with entries where b=7 using i2
  77068. ** # fill Rowset 1 with entries where c=11 and d=13 i3 and t1
  77069. ** A: RowSetRead 1, B, 2
  77070. ** Seek i, 2
  77071. **
  77072. ** The bottom of the loop looks like this:
  77073. **
  77074. ** Goto 0, A
  77075. ** B:
  77076. */
  77077. int regOrRowset; /* Register holding the RowSet object */
  77078. int regNextRowid; /* Register holding next rowid */
  77079. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  77080. WhereTerm *pOrTerm; /* A single subterm within the OR-clause */
  77081. SrcList oneTab; /* Shortened table list */
  77082. pTerm = pLevel->plan.u.pTerm;
  77083. assert( pTerm!=0 );
  77084. assert( pTerm->eOperator==WO_OR );
  77085. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  77086. pOrWc = &pTerm->u.pOrInfo->wc;
  77087. codeRowSetEarly = (regRowSet>=0 && pWC->nTerm==1) ?1:0;
  77088. if( codeRowSetEarly ){
  77089. regOrRowset = regRowSet;
  77090. }else{
  77091. regOrRowset = sqlite3GetTempReg(pParse);
  77092. sqlite3VdbeAddOp2(v, OP_Null, 0, regOrRowset);
  77093. }
  77094. oneTab.nSrc = 1;
  77095. oneTab.nAlloc = 1;
  77096. oneTab.a[0] = *pTabItem;
  77097. for(j=0, pOrTerm=pOrWc->a; j<pOrWc->nTerm; j++, pOrTerm++){
  77098. WhereInfo *pSubWInfo;
  77099. if( pOrTerm->leftCursor!=iCur && pOrTerm->eOperator!=WO_AND ) continue;
  77100. pSubWInfo = sqlite3WhereBegin(pParse, &oneTab, pOrTerm->pExpr, 0,
  77101. WHERE_FILL_ROWSET | WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE,
  77102. regOrRowset);
  77103. if( pSubWInfo ){
  77104. sqlite3WhereEnd(pSubWInfo);
  77105. }
  77106. }
  77107. sqlite3VdbeResolveLabel(v, addrCont);
  77108. if( !codeRowSetEarly ){
  77109. regNextRowid = sqlite3GetTempReg(pParse);
  77110. addrCont =
  77111. sqlite3VdbeAddOp3(v, OP_RowSetRead, regOrRowset,addrBrk,regNextRowid);
  77112. sqlite3VdbeAddOp2(v, OP_Seek, iCur, regNextRowid);
  77113. sqlite3ReleaseTempReg(pParse, regNextRowid);
  77114. /* sqlite3ReleaseTempReg(pParse, regOrRowset); // Preserve the RowSet */
  77115. pLevel->op = OP_Goto;
  77116. pLevel->p2 = addrCont;
  77117. }else{
  77118. pLevel->op = OP_Noop;
  77119. }
  77120. disableTerm(pLevel, pTerm);
  77121. }else
  77122. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  77123. {
  77124. /* Case 5: There is no usable index. We must do a complete
  77125. ** scan of the entire table.
  77126. */
  77127. assert( omitTable==0 );
  77128. assert( bRev==0 );
  77129. pLevel->op = OP_Next;
  77130. pLevel->p1 = iCur;
  77131. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addrBrk);
  77132. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  77133. codeRowSetEarly = 0;
  77134. }
  77135. notReady &= ~getMask(pWC->pMaskSet, iCur);
  77136. /* Insert code to test every subexpression that can be completely
  77137. ** computed using the current set of tables.
  77138. */
  77139. k = 0;
  77140. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  77141. Expr *pE;
  77142. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  77143. testcase( pTerm->wtFlags & TERM_CODED );
  77144. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  77145. if( (pTerm->prereqAll & notReady)!=0 ) continue;
  77146. pE = pTerm->pExpr;
  77147. assert( pE!=0 );
  77148. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  77149. continue;
  77150. }
  77151. pParse->disableColCache += k;
  77152. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  77153. pParse->disableColCache -= k;
  77154. k = 1;
  77155. pTerm->wtFlags |= TERM_CODED;
  77156. }
  77157. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  77158. ** at least one row of the right table has matched the left table.
  77159. */
  77160. if( pLevel->iLeftJoin ){
  77161. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  77162. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  77163. VdbeComment((v, "record LEFT JOIN hit"));
  77164. sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
  77165. sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
  77166. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  77167. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  77168. testcase( pTerm->wtFlags & TERM_CODED );
  77169. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  77170. if( (pTerm->prereqAll & notReady)!=0 ) continue;
  77171. assert( pTerm->pExpr );
  77172. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  77173. pTerm->wtFlags |= TERM_CODED;
  77174. }
  77175. }
  77176. /*
  77177. ** If it was requested to store the results in a rowset and that has
  77178. ** not already been do, then do so now.
  77179. */
  77180. if( regRowSet>=0 && !codeRowSetEarly ){
  77181. int r1 = sqlite3GetTempReg(pParse);
  77182. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77183. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  77184. sqlite3VdbeAddOp2(v, OP_VRowid, iCur, r1);
  77185. }else
  77186. #endif
  77187. {
  77188. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
  77189. }
  77190. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
  77191. sqlite3ReleaseTempReg(pParse, r1);
  77192. }
  77193. return notReady;
  77194. }
  77195. #if defined(SQLITE_TEST)
  77196. /*
  77197. ** The following variable holds a text description of query plan generated
  77198. ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
  77199. ** overwrites the previous. This information is used for testing and
  77200. ** analysis only.
  77201. */
  77202. SQLITE_API char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
  77203. static int nQPlan = 0; /* Next free slow in _query_plan[] */
  77204. #endif /* SQLITE_TEST */
  77205. /*
  77206. ** Free a WhereInfo structure
  77207. */
  77208. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  77209. if( pWInfo ){
  77210. int i;
  77211. for(i=0; i<pWInfo->nLevel; i++){
  77212. sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
  77213. if( pInfo ){
  77214. assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed );
  77215. if( pInfo->needToFreeIdxStr ){
  77216. sqlite3_free(pInfo->idxStr);
  77217. }
  77218. sqlite3DbFree(db, pInfo);
  77219. }
  77220. }
  77221. whereClauseClear(pWInfo->pWC);
  77222. sqlite3DbFree(db, pWInfo);
  77223. }
  77224. }
  77225. /*
  77226. ** Generate the beginning of the loop used for WHERE clause processing.
  77227. ** The return value is a pointer to an opaque structure that contains
  77228. ** information needed to terminate the loop. Later, the calling routine
  77229. ** should invoke sqlite3WhereEnd() with the return value of this function
  77230. ** in order to complete the WHERE clause processing.
  77231. **
  77232. ** If an error occurs, this routine returns NULL.
  77233. **
  77234. ** The basic idea is to do a nested loop, one loop for each table in
  77235. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  77236. ** same as a SELECT with only a single table in the FROM clause.) For
  77237. ** example, if the SQL is this:
  77238. **
  77239. ** SELECT * FROM t1, t2, t3 WHERE ...;
  77240. **
  77241. ** Then the code generated is conceptually like the following:
  77242. **
  77243. ** foreach row1 in t1 do \ Code generated
  77244. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  77245. ** foreach row3 in t3 do /
  77246. ** ...
  77247. ** end \ Code generated
  77248. ** end |-- by sqlite3WhereEnd()
  77249. ** end /
  77250. **
  77251. ** Note that the loops might not be nested in the order in which they
  77252. ** appear in the FROM clause if a different order is better able to make
  77253. ** use of indices. Note also that when the IN operator appears in
  77254. ** the WHERE clause, it might result in additional nested loops for
  77255. ** scanning through all values on the right-hand side of the IN.
  77256. **
  77257. ** There are Btree cursors associated with each table. t1 uses cursor
  77258. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  77259. ** And so forth. This routine generates code to open those VDBE cursors
  77260. ** and sqlite3WhereEnd() generates the code to close them.
  77261. **
  77262. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  77263. ** in pTabList pointing at their appropriate entries. The [...] code
  77264. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  77265. ** data from the various tables of the loop.
  77266. **
  77267. ** If the WHERE clause is empty, the foreach loops must each scan their
  77268. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  77269. ** the tables have indices and there are terms in the WHERE clause that
  77270. ** refer to those indices, a complete table scan can be avoided and the
  77271. ** code will run much faster. Most of the work of this routine is checking
  77272. ** to see if there are indices that can be used to speed up the loop.
  77273. **
  77274. ** Terms of the WHERE clause are also used to limit which rows actually
  77275. ** make it to the "..." in the middle of the loop. After each "foreach",
  77276. ** terms of the WHERE clause that use only terms in that loop and outer
  77277. ** loops are evaluated and if false a jump is made around all subsequent
  77278. ** inner loops (or around the "..." if the test occurs within the inner-
  77279. ** most loop)
  77280. **
  77281. ** OUTER JOINS
  77282. **
  77283. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  77284. **
  77285. ** foreach row1 in t1 do
  77286. ** flag = 0
  77287. ** foreach row2 in t2 do
  77288. ** start:
  77289. ** ...
  77290. ** flag = 1
  77291. ** end
  77292. ** if flag==0 then
  77293. ** move the row2 cursor to a null row
  77294. ** goto start
  77295. ** fi
  77296. ** end
  77297. **
  77298. ** ORDER BY CLAUSE PROCESSING
  77299. **
  77300. ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
  77301. ** if there is one. If there is no ORDER BY clause or if this routine
  77302. ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
  77303. **
  77304. ** If an index can be used so that the natural output order of the table
  77305. ** scan is correct for the ORDER BY clause, then that index is used and
  77306. ** *ppOrderBy is set to NULL. This is an optimization that prevents an
  77307. ** unnecessary sort of the result set if an index appropriate for the
  77308. ** ORDER BY clause already exists.
  77309. **
  77310. ** If the where clause loops cannot be arranged to provide the correct
  77311. ** output order, then the *ppOrderBy is unchanged.
  77312. */
  77313. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  77314. Parse *pParse, /* The parser context */
  77315. SrcList *pTabList, /* A list of all tables to be scanned */
  77316. Expr *pWhere, /* The WHERE clause */
  77317. ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
  77318. u8 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  77319. int regRowSet /* Register hold RowSet if WHERE_FILL_ROWSET is set */
  77320. ){
  77321. int i; /* Loop counter */
  77322. WhereInfo *pWInfo; /* Will become the return value of this function */
  77323. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  77324. Bitmask notReady; /* Cursors that are not yet positioned */
  77325. WhereMaskSet *pMaskSet; /* The expression mask set */
  77326. WhereClause *pWC; /* Decomposition of the WHERE clause */
  77327. struct SrcList_item *pTabItem; /* A single entry from pTabList */
  77328. WhereLevel *pLevel; /* A single level in the pWInfo list */
  77329. int iFrom; /* First unused FROM clause element */
  77330. int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
  77331. sqlite3 *db; /* Database connection */
  77332. ExprList *pOrderBy = 0;
  77333. /* The number of tables in the FROM clause is limited by the number of
  77334. ** bits in a Bitmask
  77335. */
  77336. if( pTabList->nSrc>BMS ){
  77337. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  77338. return 0;
  77339. }
  77340. if( ppOrderBy ){
  77341. pOrderBy = *ppOrderBy;
  77342. }
  77343. /* Allocate and initialize the WhereInfo structure that will become the
  77344. ** return value.
  77345. */
  77346. db = pParse->db;
  77347. pWInfo = sqlite3DbMallocZero(db,
  77348. sizeof(WhereInfo)
  77349. + (pTabList->nSrc-1)*sizeof(WhereLevel)
  77350. + sizeof(WhereClause)
  77351. + sizeof(WhereMaskSet)
  77352. );
  77353. if( db->mallocFailed ){
  77354. goto whereBeginError;
  77355. }
  77356. pWInfo->nLevel = pTabList->nSrc;
  77357. pWInfo->pParse = pParse;
  77358. pWInfo->pTabList = pTabList;
  77359. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  77360. pWInfo->regRowSet = (wctrlFlags & WHERE_FILL_ROWSET) ? regRowSet : -1;
  77361. pWInfo->pWC = pWC = (WhereClause*)&pWInfo->a[pWInfo->nLevel];
  77362. pWInfo->wctrlFlags = wctrlFlags;
  77363. pMaskSet = (WhereMaskSet*)&pWC[1];
  77364. /* Split the WHERE clause into separate subexpressions where each
  77365. ** subexpression is separated by an AND operator.
  77366. */
  77367. initMaskSet(pMaskSet);
  77368. whereClauseInit(pWC, pParse, pMaskSet);
  77369. sqlite3ExprCodeConstants(pParse, pWhere);
  77370. whereSplit(pWC, pWhere, TK_AND);
  77371. /* Special case: a WHERE clause that is constant. Evaluate the
  77372. ** expression and either jump over all of the code or fall thru.
  77373. */
  77374. if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  77375. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  77376. pWhere = 0;
  77377. }
  77378. /* Assign a bit from the bitmask to every term in the FROM clause.
  77379. **
  77380. ** When assigning bitmask values to FROM clause cursors, it must be
  77381. ** the case that if X is the bitmask for the N-th FROM clause term then
  77382. ** the bitmask for all FROM clause terms to the left of the N-th term
  77383. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  77384. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  77385. ** of the join. Subtracting one from the right table bitmask gives a
  77386. ** bitmask for all tables to the left of the join. Knowing the bitmask
  77387. ** for all tables to the left of a left join is important. Ticket #3015.
  77388. */
  77389. for(i=0; i<pTabList->nSrc; i++){
  77390. createMask(pMaskSet, pTabList->a[i].iCursor);
  77391. }
  77392. #ifndef NDEBUG
  77393. {
  77394. Bitmask toTheLeft = 0;
  77395. for(i=0; i<pTabList->nSrc; i++){
  77396. Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
  77397. assert( (m-1)==toTheLeft );
  77398. toTheLeft |= m;
  77399. }
  77400. }
  77401. #endif
  77402. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  77403. ** add new virtual terms onto the end of the WHERE clause. We do not
  77404. ** want to analyze these virtual terms, so start analyzing at the end
  77405. ** and work forward so that the added virtual terms are never processed.
  77406. */
  77407. exprAnalyzeAll(pTabList, pWC);
  77408. if( db->mallocFailed ){
  77409. goto whereBeginError;
  77410. }
  77411. /* Chose the best index to use for each table in the FROM clause.
  77412. **
  77413. ** This loop fills in the following fields:
  77414. **
  77415. ** pWInfo->a[].pIdx The index to use for this level of the loop.
  77416. ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
  77417. ** pWInfo->a[].nEq The number of == and IN constraints
  77418. ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
  77419. ** pWInfo->a[].iTabCur The VDBE cursor for the database table
  77420. ** pWInfo->a[].iIdxCur The VDBE cursor for the index
  77421. ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
  77422. **
  77423. ** This loop also figures out the nesting order of tables in the FROM
  77424. ** clause.
  77425. */
  77426. notReady = ~(Bitmask)0;
  77427. pTabItem = pTabList->a;
  77428. pLevel = pWInfo->a;
  77429. andFlags = ~0;
  77430. WHERETRACE(("*** Optimizer Start ***\n"));
  77431. for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
  77432. WhereCost bestPlan; /* Most efficient plan seen so far */
  77433. Index *pIdx; /* Index for FROM table at pTabItem */
  77434. int j; /* For looping over FROM tables */
  77435. int bestJ = 0; /* The value of j */
  77436. Bitmask m; /* Bitmask value for j or bestJ */
  77437. int once = 0; /* True when first table is seen */
  77438. memset(&bestPlan, 0, sizeof(bestPlan));
  77439. bestPlan.rCost = SQLITE_BIG_DBL;
  77440. for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
  77441. int doNotReorder; /* True if this table should not be reordered */
  77442. WhereCost sCost; /* Cost information from bestIndex() */
  77443. doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
  77444. if( once && doNotReorder ) break;
  77445. m = getMask(pMaskSet, pTabItem->iCursor);
  77446. if( (m & notReady)==0 ){
  77447. if( j==iFrom ) iFrom++;
  77448. continue;
  77449. }
  77450. assert( pTabItem->pTab );
  77451. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77452. if( IsVirtual(pTabItem->pTab) ){
  77453. sqlite3_index_info *pVtabIdx; /* Current virtual index */
  77454. sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
  77455. sCost.rCost = bestVirtualIndex(pParse, pWC, pTabItem, notReady,
  77456. ppOrderBy ? *ppOrderBy : 0, i==0,
  77457. ppIdxInfo);
  77458. sCost.plan.wsFlags = WHERE_VIRTUALTABLE;
  77459. sCost.plan.u.pVtabIdx = pVtabIdx = *ppIdxInfo;
  77460. if( pVtabIdx && pVtabIdx->orderByConsumed ){
  77461. sCost.plan.wsFlags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
  77462. }
  77463. sCost.plan.nEq = 0;
  77464. if( (SQLITE_BIG_DBL/2.0)<sCost.rCost ){
  77465. /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
  77466. ** inital value of lowestCost in this loop. If it is, then
  77467. ** the (cost<lowestCost) test below will never be true.
  77468. */
  77469. sCost.rCost = (SQLITE_BIG_DBL/2.0);
  77470. }
  77471. }else
  77472. #endif
  77473. {
  77474. bestIndex(pParse, pWC, pTabItem, notReady,
  77475. (i==0 && ppOrderBy) ? *ppOrderBy : 0, &sCost);
  77476. }
  77477. if( once==0 || sCost.rCost<bestPlan.rCost ){
  77478. once = 1;
  77479. bestPlan = sCost;
  77480. bestJ = j;
  77481. }
  77482. if( doNotReorder ) break;
  77483. }
  77484. assert( once );
  77485. assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
  77486. WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
  77487. pLevel-pWInfo->a));
  77488. if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
  77489. *ppOrderBy = 0;
  77490. }
  77491. andFlags &= bestPlan.plan.wsFlags;
  77492. pLevel->plan = bestPlan.plan;
  77493. if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
  77494. pLevel->iIdxCur = pParse->nTab++;
  77495. }else{
  77496. pLevel->iIdxCur = -1;
  77497. }
  77498. notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
  77499. pLevel->iFrom = bestJ;
  77500. /* Check that if the table scanned by this loop iteration had an
  77501. ** INDEXED BY clause attached to it, that the named index is being
  77502. ** used for the scan. If not, then query compilation has failed.
  77503. ** Return an error.
  77504. */
  77505. pIdx = pTabList->a[bestJ].pIndex;
  77506. if( pIdx ){
  77507. if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
  77508. sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
  77509. goto whereBeginError;
  77510. }else{
  77511. /* If an INDEXED BY clause is used, the bestIndex() function is
  77512. ** guaranteed to find the index specified in the INDEXED BY clause
  77513. ** if it find an index at all. */
  77514. assert( bestPlan.plan.u.pIdx==pIdx );
  77515. }
  77516. }
  77517. }
  77518. WHERETRACE(("*** Optimizer Finished ***\n"));
  77519. if( db->mallocFailed ){
  77520. goto whereBeginError;
  77521. }
  77522. /* If the total query only selects a single row, then the ORDER BY
  77523. ** clause is irrelevant.
  77524. */
  77525. if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
  77526. *ppOrderBy = 0;
  77527. }
  77528. /* If the caller is an UPDATE or DELETE statement that is requesting
  77529. ** to use a one-pass algorithm, determine if this is appropriate.
  77530. ** The one-pass algorithm only works if the WHERE clause constraints
  77531. ** the statement to update a single row.
  77532. */
  77533. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  77534. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
  77535. pWInfo->okOnePass = 1;
  77536. pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
  77537. }
  77538. /* Open all tables in the pTabList and any indices selected for
  77539. ** searching those tables.
  77540. */
  77541. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  77542. for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
  77543. Table *pTab; /* Table to open */
  77544. int iDb; /* Index of database containing table/index */
  77545. #ifndef SQLITE_OMIT_EXPLAIN
  77546. if( pParse->explain==2 ){
  77547. char *zMsg;
  77548. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  77549. zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
  77550. if( pItem->zAlias ){
  77551. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  77552. }
  77553. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  77554. zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
  77555. zMsg, pLevel->plan.u.pIdx->zName);
  77556. }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
  77557. zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
  77558. }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  77559. zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
  77560. }
  77561. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77562. else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  77563. sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
  77564. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  77565. pVtabIdx->idxNum, pVtabIdx->idxStr);
  77566. }
  77567. #endif
  77568. if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
  77569. zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
  77570. }
  77571. sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
  77572. }
  77573. #endif /* SQLITE_OMIT_EXPLAIN */
  77574. pTabItem = &pTabList->a[pLevel->iFrom];
  77575. pTab = pTabItem->pTab;
  77576. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  77577. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
  77578. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77579. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  77580. int iCur = pTabItem->iCursor;
  77581. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
  77582. (const char*)pTab->pVtab, P4_VTAB);
  77583. }else
  77584. #endif
  77585. if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  77586. && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
  77587. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  77588. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  77589. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  77590. Bitmask b = pTabItem->colUsed;
  77591. int n = 0;
  77592. for(; b; b=b>>1, n++){}
  77593. sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n);
  77594. assert( n<=pTab->nCol );
  77595. }
  77596. }else{
  77597. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  77598. }
  77599. pLevel->iTabCur = pTabItem->iCursor;
  77600. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  77601. Index *pIx = pLevel->plan.u.pIdx;
  77602. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  77603. int iIdxCur = pLevel->iIdxCur;
  77604. assert( pIx->pSchema==pTab->pSchema );
  77605. assert( iIdxCur>=0 );
  77606. sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1);
  77607. sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
  77608. (char*)pKey, P4_KEYINFO_HANDOFF);
  77609. VdbeComment((v, "%s", pIx->zName));
  77610. }
  77611. sqlite3CodeVerifySchema(pParse, iDb);
  77612. }
  77613. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  77614. /* Generate the code to do the search. Each iteration of the for
  77615. ** loop below generates code for a single nested loop of the VM
  77616. ** program.
  77617. */
  77618. notReady = ~(Bitmask)0;
  77619. for(i=0; i<pTabList->nSrc; i++){
  77620. notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
  77621. pWInfo->iContinue = pWInfo->a[i].addrCont;
  77622. }
  77623. #ifdef SQLITE_TEST /* For testing and debugging use only */
  77624. /* Record in the query plan information about the current table
  77625. ** and the index used to access it (if any). If the table itself
  77626. ** is not used, its name is just '{}'. If no index is used
  77627. ** the index is listed as "{}". If the primary key is used the
  77628. ** index name is '*'.
  77629. */
  77630. for(i=0; i<pTabList->nSrc; i++){
  77631. char *z;
  77632. int n;
  77633. pLevel = &pWInfo->a[i];
  77634. pTabItem = &pTabList->a[pLevel->iFrom];
  77635. z = pTabItem->zAlias;
  77636. if( z==0 ) z = pTabItem->pTab->zName;
  77637. n = sqlite3Strlen30(z);
  77638. if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
  77639. if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
  77640. memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
  77641. nQPlan += 2;
  77642. }else{
  77643. memcpy(&sqlite3_query_plan[nQPlan], z, n);
  77644. nQPlan += n;
  77645. }
  77646. sqlite3_query_plan[nQPlan++] = ' ';
  77647. }
  77648. testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
  77649. testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
  77650. if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  77651. memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
  77652. nQPlan += 2;
  77653. }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  77654. n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
  77655. if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
  77656. memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
  77657. nQPlan += n;
  77658. sqlite3_query_plan[nQPlan++] = ' ';
  77659. }
  77660. }else{
  77661. memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
  77662. nQPlan += 3;
  77663. }
  77664. }
  77665. while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
  77666. sqlite3_query_plan[--nQPlan] = 0;
  77667. }
  77668. sqlite3_query_plan[nQPlan] = 0;
  77669. nQPlan = 0;
  77670. #endif /* SQLITE_TEST // Testing and debugging use only */
  77671. /* Record the continuation address in the WhereInfo structure. Then
  77672. ** clean up and return.
  77673. */
  77674. return pWInfo;
  77675. /* Jump here if malloc fails */
  77676. whereBeginError:
  77677. whereInfoFree(db, pWInfo);
  77678. return 0;
  77679. }
  77680. /*
  77681. ** Generate the end of the WHERE loop. See comments on
  77682. ** sqlite3WhereBegin() for additional information.
  77683. */
  77684. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  77685. Parse *pParse = pWInfo->pParse;
  77686. Vdbe *v = pParse->pVdbe;
  77687. int i;
  77688. WhereLevel *pLevel;
  77689. SrcList *pTabList = pWInfo->pTabList;
  77690. sqlite3 *db = pParse->db;
  77691. /* Generate loop termination code.
  77692. */
  77693. sqlite3ExprClearColumnCache(pParse, -1);
  77694. for(i=pTabList->nSrc-1; i>=0; i--){
  77695. pLevel = &pWInfo->a[i];
  77696. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  77697. if( pLevel->op!=OP_Noop ){
  77698. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  77699. sqlite3VdbeChangeP5(v, pLevel->p5);
  77700. }
  77701. if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  77702. struct InLoop *pIn;
  77703. int j;
  77704. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  77705. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  77706. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  77707. sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
  77708. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  77709. }
  77710. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  77711. }
  77712. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  77713. if( pLevel->iLeftJoin ){
  77714. int addr;
  77715. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  77716. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  77717. if( pLevel->iIdxCur>=0 ){
  77718. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  77719. }
  77720. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  77721. sqlite3VdbeJumpHere(v, addr);
  77722. }
  77723. }
  77724. /* The "break" point is here, just past the end of the outer loop.
  77725. ** Set it.
  77726. */
  77727. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  77728. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  77729. */
  77730. for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
  77731. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  77732. Table *pTab = pTabItem->pTab;
  77733. assert( pTab!=0 );
  77734. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
  77735. if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
  77736. if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
  77737. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  77738. }
  77739. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  77740. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  77741. }
  77742. }
  77743. /* If this scan uses an index, make code substitutions to read data
  77744. ** from the index in preference to the table. Sometimes, this means
  77745. ** the table need never be read from. This is a performance boost,
  77746. ** as the vdbe level waits until the table is read before actually
  77747. ** seeking the table cursor to the record corresponding to the current
  77748. ** position in the index.
  77749. **
  77750. ** Calls to the code generator in between sqlite3WhereBegin and
  77751. ** sqlite3WhereEnd will have created code that references the table
  77752. ** directly. This loop scans all that code looking for opcodes
  77753. ** that reference the table and converts them into opcodes that
  77754. ** reference the index.
  77755. */
  77756. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  77757. int k, j, last;
  77758. VdbeOp *pOp;
  77759. Index *pIdx = pLevel->plan.u.pIdx;
  77760. int useIndexOnly = pLevel->plan.wsFlags & WHERE_IDX_ONLY;
  77761. assert( pIdx!=0 );
  77762. pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
  77763. last = sqlite3VdbeCurrentAddr(v);
  77764. for(k=pWInfo->iTop; k<last; k++, pOp++){
  77765. if( pOp->p1!=pLevel->iTabCur ) continue;
  77766. if( pOp->opcode==OP_Column ){
  77767. for(j=0; j<pIdx->nColumn; j++){
  77768. if( pOp->p2==pIdx->aiColumn[j] ){
  77769. pOp->p2 = j;
  77770. pOp->p1 = pLevel->iIdxCur;
  77771. break;
  77772. }
  77773. }
  77774. assert(!useIndexOnly || j<pIdx->nColumn);
  77775. }else if( pOp->opcode==OP_Rowid ){
  77776. pOp->p1 = pLevel->iIdxCur;
  77777. pOp->opcode = OP_IdxRowid;
  77778. }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
  77779. pOp->opcode = OP_Noop;
  77780. }
  77781. }
  77782. }
  77783. }
  77784. /* Final cleanup
  77785. */
  77786. whereInfoFree(db, pWInfo);
  77787. return;
  77788. }
  77789. /************** End of where.c ***********************************************/
  77790. /************** Begin file parse.c *******************************************/
  77791. /* Driver template for the LEMON parser generator.
  77792. ** The author disclaims copyright to this source code.
  77793. */
  77794. /* First off, code is included that follows the "include" declaration
  77795. ** in the input grammar file. */
  77796. /*
  77797. ** An instance of this structure holds information about the
  77798. ** LIMIT clause of a SELECT statement.
  77799. */
  77800. struct LimitVal {
  77801. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  77802. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  77803. };
  77804. /*
  77805. ** An instance of this structure is used to store the LIKE,
  77806. ** GLOB, NOT LIKE, and NOT GLOB operators.
  77807. */
  77808. struct LikeOp {
  77809. Token eOperator; /* "like" or "glob" or "regexp" */
  77810. int not; /* True if the NOT keyword is present */
  77811. };
  77812. /*
  77813. ** An instance of the following structure describes the event of a
  77814. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  77815. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  77816. **
  77817. ** UPDATE ON (a,b,c)
  77818. **
  77819. ** Then the "b" IdList records the list "a,b,c".
  77820. */
  77821. struct TrigEvent { int a; IdList * b; };
  77822. /*
  77823. ** An instance of this structure holds the ATTACH key and the key type.
  77824. */
  77825. struct AttachKey { int type; Token key; };
  77826. /* Next is all token values, in a form suitable for use by makeheaders.
  77827. ** This section will be null unless lemon is run with the -m switch.
  77828. */
  77829. /*
  77830. ** These constants (all generated automatically by the parser generator)
  77831. ** specify the various kinds of tokens (terminals) that the parser
  77832. ** understands.
  77833. **
  77834. ** Each symbol here is a terminal symbol in the grammar.
  77835. */
  77836. /* Make sure the INTERFACE macro is defined.
  77837. */
  77838. #ifndef INTERFACE
  77839. # define INTERFACE 1
  77840. #endif
  77841. /* The next thing included is series of defines which control
  77842. ** various aspects of the generated parser.
  77843. ** YYCODETYPE is the data type used for storing terminal
  77844. ** and nonterminal numbers. "unsigned char" is
  77845. ** used if there are fewer than 250 terminals
  77846. ** and nonterminals. "int" is used otherwise.
  77847. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  77848. ** to no legal terminal or nonterminal number. This
  77849. ** number is used to fill in empty slots of the hash
  77850. ** table.
  77851. ** YYFALLBACK If defined, this indicates that one or more tokens
  77852. ** have fall-back values which should be used if the
  77853. ** original value of the token will not parse.
  77854. ** YYACTIONTYPE is the data type used for storing terminal
  77855. ** and nonterminal numbers. "unsigned char" is
  77856. ** used if there are fewer than 250 rules and
  77857. ** states combined. "int" is used otherwise.
  77858. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  77859. ** directly to the parser from the tokenizer.
  77860. ** YYMINORTYPE is the data type used for all minor tokens.
  77861. ** This is typically a union of many types, one of
  77862. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  77863. ** for base tokens is called "yy0".
  77864. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  77865. ** zero the stack is dynamically sized using realloc()
  77866. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  77867. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  77868. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  77869. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  77870. ** YYNSTATE the combined number of states.
  77871. ** YYNRULE the number of rules in the grammar
  77872. ** YYERRORSYMBOL is the code number of the error symbol. If not
  77873. ** defined, then do no error processing.
  77874. */
  77875. #define YYCODETYPE unsigned char
  77876. #define YYNOCODE 251
  77877. #define YYACTIONTYPE unsigned short int
  77878. #define YYWILDCARD 62
  77879. #define sqlite3ParserTOKENTYPE Token
  77880. typedef union {
  77881. int yyinit;
  77882. sqlite3ParserTOKENTYPE yy0;
  77883. struct LimitVal yy64;
  77884. Expr* yy122;
  77885. Select* yy159;
  77886. IdList* yy180;
  77887. struct {int value; int mask;} yy207;
  77888. struct LikeOp yy318;
  77889. TriggerStep* yy327;
  77890. SrcList* yy347;
  77891. int yy392;
  77892. struct TrigEvent yy410;
  77893. ExprList* yy442;
  77894. } YYMINORTYPE;
  77895. #ifndef YYSTACKDEPTH
  77896. #define YYSTACKDEPTH 100
  77897. #endif
  77898. #define sqlite3ParserARG_SDECL Parse *pParse;
  77899. #define sqlite3ParserARG_PDECL ,Parse *pParse
  77900. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  77901. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  77902. #define YYNSTATE 610
  77903. #define YYNRULE 319
  77904. #define YYFALLBACK 1
  77905. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  77906. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  77907. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  77908. /* The yyzerominor constant is used to initialize instances of
  77909. ** YYMINORTYPE objects to zero. */
  77910. static const YYMINORTYPE yyzerominor = { 0 };
  77911. /* Next are the tables used to determine what action to take based on the
  77912. ** current state and lookahead token. These tables are used to implement
  77913. ** functions that take a state number and lookahead value and return an
  77914. ** action integer.
  77915. **
  77916. ** Suppose the action integer is N. Then the action is determined as
  77917. ** follows
  77918. **
  77919. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  77920. ** token onto the stack and goto state N.
  77921. **
  77922. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  77923. **
  77924. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  77925. **
  77926. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  77927. **
  77928. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  77929. ** slots in the yy_action[] table.
  77930. **
  77931. ** The action table is constructed as a single large table named yy_action[].
  77932. ** Given state S and lookahead X, the action is computed as
  77933. **
  77934. ** yy_action[ yy_shift_ofst[S] + X ]
  77935. **
  77936. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  77937. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  77938. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  77939. ** and that yy_default[S] should be used instead.
  77940. **
  77941. ** The formula above is for computing the action when the lookahead is
  77942. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  77943. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  77944. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  77945. ** YY_SHIFT_USE_DFLT.
  77946. **
  77947. ** The following are the tables generated in this section:
  77948. **
  77949. ** yy_action[] A single table containing all actions.
  77950. ** yy_lookahead[] A table containing the lookahead for each entry in
  77951. ** yy_action. Used to detect hash collisions.
  77952. ** yy_shift_ofst[] For each state, the offset into yy_action for
  77953. ** shifting terminals.
  77954. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  77955. ** shifting non-terminals after a reduce.
  77956. ** yy_default[] Default action for each state.
  77957. */
  77958. static const YYACTIONTYPE yy_action[] = {
  77959. /* 0 */ 304, 930, 120, 609, 1, 178, 214, 436, 62, 62,
  77960. /* 10 */ 62, 62, 216, 64, 64, 64, 64, 65, 65, 66,
  77961. /* 20 */ 66, 66, 67, 216, 406, 403, 443, 449, 69, 64,
  77962. /* 30 */ 64, 64, 64, 65, 65, 66, 66, 66, 67, 216,
  77963. /* 40 */ 469, 467, 336, 174, 61, 60, 309, 453, 454, 450,
  77964. /* 50 */ 450, 63, 63, 62, 62, 62, 62, 200, 64, 64,
  77965. /* 60 */ 64, 64, 65, 65, 66, 66, 66, 67, 216, 304,
  77966. /* 70 */ 510, 312, 436, 509, 438, 83, 64, 64, 64, 64,
  77967. /* 80 */ 65, 65, 66, 66, 66, 67, 216, 65, 65, 66,
  77968. /* 90 */ 66, 66, 67, 216, 511, 443, 449, 325, 408, 59,
  77969. /* 100 */ 465, 218, 57, 213, 411, 496, 428, 440, 440, 440,
  77970. /* 110 */ 206, 67, 216, 61, 60, 309, 453, 454, 450, 450,
  77971. /* 120 */ 63, 63, 62, 62, 62, 62, 552, 64, 64, 64,
  77972. /* 130 */ 64, 65, 65, 66, 66, 66, 67, 216, 304, 228,
  77973. /* 140 */ 186, 469, 544, 312, 433, 170, 114, 256, 357, 261,
  77974. /* 150 */ 358, 181, 425, 20, 426, 542, 153, 85, 265, 465,
  77975. /* 160 */ 218, 150, 151, 539, 443, 449, 95, 311, 394, 412,
  77976. /* 170 */ 413, 510, 276, 427, 436, 438, 152, 553, 545, 589,
  77977. /* 180 */ 590, 539, 61, 60, 309, 453, 454, 450, 450, 63,
  77978. /* 190 */ 63, 62, 62, 62, 62, 402, 64, 64, 64, 64,
  77979. /* 200 */ 65, 65, 66, 66, 66, 67, 216, 304, 440, 440,
  77980. /* 210 */ 440, 228, 109, 411, 399, 523, 593, 330, 114, 256,
  77981. /* 220 */ 357, 261, 358, 181, 187, 330, 485, 359, 362, 363,
  77982. /* 230 */ 265, 593, 241, 443, 449, 592, 591, 248, 364, 436,
  77983. /* 240 */ 432, 35, 492, 66, 66, 66, 67, 216, 432, 42,
  77984. /* 250 */ 592, 61, 60, 309, 453, 454, 450, 450, 63, 63,
  77985. /* 260 */ 62, 62, 62, 62, 401, 64, 64, 64, 64, 65,
  77986. /* 270 */ 65, 66, 66, 66, 67, 216, 304, 570, 412, 413,
  77987. /* 280 */ 187, 501, 344, 359, 362, 363, 215, 354, 346, 221,
  77988. /* 290 */ 330, 341, 330, 56, 364, 569, 588, 217, 68, 156,
  77989. /* 300 */ 70, 155, 443, 449, 68, 187, 70, 155, 359, 362,
  77990. /* 310 */ 363, 397, 217, 432, 35, 432, 36, 148, 569, 364,
  77991. /* 320 */ 61, 60, 309, 453, 454, 450, 450, 63, 63, 62,
  77992. /* 330 */ 62, 62, 62, 433, 64, 64, 64, 64, 65, 65,
  77993. /* 340 */ 66, 66, 66, 67, 216, 387, 282, 281, 330, 304,
  77994. /* 350 */ 474, 68, 480, 70, 155, 344, 214, 154, 299, 330,
  77995. /* 360 */ 343, 467, 543, 174, 384, 475, 257, 247, 387, 282,
  77996. /* 370 */ 281, 432, 28, 411, 160, 443, 449, 258, 476, 214,
  77997. /* 380 */ 516, 496, 432, 42, 198, 492, 68, 162, 70, 155,
  77998. /* 390 */ 517, 433, 78, 61, 60, 309, 453, 454, 450, 450,
  77999. /* 400 */ 63, 63, 62, 62, 62, 62, 595, 64, 64, 64,
  78000. /* 410 */ 64, 65, 65, 66, 66, 66, 67, 216, 433, 367,
  78001. /* 420 */ 349, 433, 304, 220, 222, 544, 505, 330, 465, 330,
  78002. /* 430 */ 230, 330, 240, 163, 161, 554, 20, 431, 412, 413,
  78003. /* 440 */ 2, 430, 385, 375, 411, 198, 182, 249, 443, 449,
  78004. /* 450 */ 432, 35, 432, 50, 432, 50, 310, 460, 461, 17,
  78005. /* 460 */ 207, 335, 460, 461, 388, 81, 61, 60, 309, 453,
  78006. /* 470 */ 454, 450, 450, 63, 63, 62, 62, 62, 62, 433,
  78007. /* 480 */ 64, 64, 64, 64, 65, 65, 66, 66, 66, 67,
  78008. /* 490 */ 216, 304, 348, 504, 433, 508, 531, 486, 320, 353,
  78009. /* 500 */ 321, 306, 457, 385, 23, 331, 265, 470, 411, 412,
  78010. /* 510 */ 413, 444, 445, 551, 526, 307, 532, 443, 449, 217,
  78011. /* 520 */ 550, 496, 432, 3, 217, 381, 607, 921, 333, 921,
  78012. /* 530 */ 456, 456, 447, 448, 276, 61, 60, 309, 453, 454,
  78013. /* 540 */ 450, 450, 63, 63, 62, 62, 62, 62, 410, 64,
  78014. /* 550 */ 64, 64, 64, 65, 65, 66, 66, 66, 67, 216,
  78015. /* 560 */ 304, 446, 607, 920, 525, 920, 604, 264, 314, 474,
  78016. /* 570 */ 411, 123, 411, 412, 413, 124, 277, 487, 234, 333,
  78017. /* 580 */ 411, 456, 456, 319, 475, 411, 443, 449, 333, 377,
  78018. /* 590 */ 456, 456, 286, 333, 380, 456, 456, 476, 178, 340,
  78019. /* 600 */ 436, 420, 604, 315, 61, 60, 309, 453, 454, 450,
  78020. /* 610 */ 450, 63, 63, 62, 62, 62, 62, 330, 64, 64,
  78021. /* 620 */ 64, 64, 65, 65, 66, 66, 66, 67, 216, 304,
  78022. /* 630 */ 289, 5, 287, 268, 466, 412, 413, 412, 413, 396,
  78023. /* 640 */ 432, 29, 503, 330, 159, 412, 413, 610, 406, 403,
  78024. /* 650 */ 412, 413, 414, 415, 416, 443, 449, 333, 214, 456,
  78025. /* 660 */ 456, 488, 276, 489, 21, 436, 432, 24, 436, 487,
  78026. /* 670 */ 514, 515, 395, 61, 60, 309, 453, 454, 450, 450,
  78027. /* 680 */ 63, 63, 62, 62, 62, 62, 330, 64, 64, 64,
  78028. /* 690 */ 64, 65, 65, 66, 66, 66, 67, 216, 304, 560,
  78029. /* 700 */ 374, 560, 352, 94, 578, 330, 567, 515, 330, 432,
  78030. /* 710 */ 33, 330, 288, 330, 562, 330, 544, 330, 561, 183,
  78031. /* 720 */ 184, 185, 603, 303, 443, 449, 600, 20, 432, 54,
  78032. /* 730 */ 376, 432, 53, 436, 432, 99, 432, 97, 432, 102,
  78033. /* 740 */ 432, 103, 61, 60, 309, 453, 454, 450, 450, 63,
  78034. /* 750 */ 63, 62, 62, 62, 62, 330, 64, 64, 64, 64,
  78035. /* 760 */ 65, 65, 66, 66, 66, 67, 216, 304, 330, 405,
  78036. /* 770 */ 1, 202, 330, 512, 330, 214, 330, 171, 432, 108,
  78037. /* 780 */ 330, 421, 429, 330, 487, 342, 330, 384, 19, 386,
  78038. /* 790 */ 145, 432, 110, 443, 449, 432, 16, 432, 100, 432,
  78039. /* 800 */ 34, 351, 270, 432, 98, 433, 432, 25, 276, 432,
  78040. /* 810 */ 55, 61, 60, 309, 453, 454, 450, 450, 63, 63,
  78041. /* 820 */ 62, 62, 62, 62, 330, 64, 64, 64, 64, 65,
  78042. /* 830 */ 65, 66, 66, 66, 67, 216, 304, 330, 323, 119,
  78043. /* 840 */ 274, 330, 272, 330, 355, 330, 422, 432, 111, 330,
  78044. /* 850 */ 580, 159, 115, 233, 330, 177, 161, 439, 463, 463,
  78045. /* 860 */ 432, 112, 443, 449, 432, 113, 432, 26, 432, 37,
  78046. /* 870 */ 649, 431, 432, 38, 492, 430, 487, 432, 27, 264,
  78047. /* 880 */ 61, 71, 309, 453, 454, 450, 450, 63, 63, 62,
  78048. /* 890 */ 62, 62, 62, 330, 64, 64, 64, 64, 65, 65,
  78049. /* 900 */ 66, 66, 66, 67, 216, 304, 330, 264, 264, 528,
  78050. /* 910 */ 330, 157, 330, 252, 330, 229, 432, 39, 330, 482,
  78051. /* 920 */ 332, 478, 77, 330, 79, 330, 483, 520, 521, 432,
  78052. /* 930 */ 40, 443, 449, 432, 41, 432, 43, 432, 44, 492,
  78053. /* 940 */ 491, 432, 45, 316, 317, 433, 432, 30, 432, 31,
  78054. /* 950 */ 60, 309, 453, 454, 450, 450, 63, 63, 62, 62,
  78055. /* 960 */ 62, 62, 330, 64, 64, 64, 64, 65, 65, 66,
  78056. /* 970 */ 66, 66, 67, 216, 304, 330, 264, 564, 254, 330,
  78057. /* 980 */ 458, 330, 22, 330, 495, 432, 46, 330, 494, 535,
  78058. /* 990 */ 179, 186, 330, 267, 330, 186, 451, 497, 432, 47,
  78059. /* 1000 */ 443, 449, 432, 48, 432, 49, 432, 32, 182, 262,
  78060. /* 1010 */ 432, 10, 318, 276, 389, 432, 51, 432, 52, 276,
  78061. /* 1020 */ 309, 453, 454, 450, 450, 63, 63, 62, 62, 62,
  78062. /* 1030 */ 62, 276, 64, 64, 64, 64, 65, 65, 66, 66,
  78063. /* 1040 */ 66, 67, 216, 165, 276, 276, 189, 192, 235, 236,
  78064. /* 1050 */ 237, 168, 239, 566, 105, 581, 18, 530, 529, 73,
  78065. /* 1060 */ 337, 582, 4, 306, 605, 527, 308, 211, 366, 294,
  78066. /* 1070 */ 186, 263, 533, 231, 334, 565, 295, 186, 534, 546,
  78067. /* 1080 */ 433, 433, 573, 574, 179, 92, 232, 292, 209, 269,
  78068. /* 1090 */ 569, 339, 271, 853, 208, 273, 275, 210, 585, 195,
  78069. /* 1100 */ 92, 469, 371, 606, 602, 8, 302, 423, 280, 379,
  78070. /* 1110 */ 382, 383, 147, 242, 283, 437, 462, 284, 285, 577,
  78071. /* 1120 */ 338, 76, 75, 587, 293, 296, 297, 599, 481, 464,
  78072. /* 1130 */ 74, 328, 329, 250, 526, 438, 572, 166, 290, 393,
  78073. /* 1140 */ 392, 291, 281, 409, 537, 584, 305, 484, 259, 540,
  78074. /* 1150 */ 417, 214, 418, 214, 536, 326, 538, 419, 361, 167,
  78075. /* 1160 */ 73, 337, 169, 4, 7, 327, 347, 308, 440, 440,
  78076. /* 1170 */ 440, 441, 442, 11, 85, 334, 398, 84, 434, 345,
  78077. /* 1180 */ 243, 58, 244, 73, 337, 80, 4, 245, 435, 246,
  78078. /* 1190 */ 308, 176, 339, 479, 86, 121, 356, 350, 334, 493,
  78079. /* 1200 */ 251, 253, 469, 499, 255, 513, 500, 518, 313, 519,
  78080. /* 1210 */ 260, 523, 125, 522, 226, 339, 219, 524, 368, 190,
  78081. /* 1220 */ 191, 300, 76, 75, 502, 469, 225, 227, 547, 541,
  78082. /* 1230 */ 548, 74, 328, 329, 301, 555, 438, 549, 370, 193,
  78083. /* 1240 */ 372, 194, 557, 89, 196, 76, 75, 278, 378, 117,
  78084. /* 1250 */ 558, 568, 133, 390, 74, 328, 329, 199, 391, 438,
  78085. /* 1260 */ 322, 134, 135, 136, 575, 143, 583, 596, 139, 440,
  78086. /* 1270 */ 440, 440, 441, 442, 11, 597, 598, 601, 137, 142,
  78087. /* 1280 */ 101, 224, 104, 407, 238, 424, 650, 651, 93, 172,
  78088. /* 1290 */ 96, 173, 440, 440, 440, 441, 442, 11, 452, 455,
  78089. /* 1300 */ 72, 471, 459, 468, 472, 144, 158, 6, 473, 490,
  78090. /* 1310 */ 107, 175, 477, 82, 13, 122, 12, 180, 506, 118,
  78091. /* 1320 */ 498, 164, 507, 324, 223, 87, 126, 116, 266, 127,
  78092. /* 1330 */ 88, 128, 188, 258, 360, 369, 146, 556, 129, 373,
  78093. /* 1340 */ 179, 365, 279, 197, 131, 130, 563, 9, 571, 132,
  78094. /* 1350 */ 559, 201, 14, 576, 203, 204, 205, 579, 140, 138,
  78095. /* 1360 */ 141, 15, 586, 594, 212, 106, 400, 298, 149, 404,
  78096. /* 1370 */ 931, 608, 90, 91,
  78097. };
  78098. static const YYCODETYPE yy_lookahead[] = {
  78099. /* 0 */ 19, 142, 143, 144, 145, 24, 113, 26, 72, 73,
  78100. /* 10 */ 74, 75, 87, 77, 78, 79, 80, 81, 82, 83,
  78101. /* 20 */ 84, 85, 86, 87, 1, 2, 45, 46, 76, 77,
  78102. /* 30 */ 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
  78103. /* 40 */ 61, 165, 166, 167, 63, 64, 65, 66, 67, 68,
  78104. /* 50 */ 69, 70, 71, 72, 73, 74, 75, 25, 77, 78,
  78105. /* 60 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 19,
  78106. /* 70 */ 91, 19, 91, 173, 95, 25, 77, 78, 79, 80,
  78107. /* 80 */ 81, 82, 83, 84, 85, 86, 87, 81, 82, 83,
  78108. /* 90 */ 84, 85, 86, 87, 173, 45, 46, 146, 147, 49,
  78109. /* 100 */ 81, 82, 22, 152, 26, 150, 26, 128, 129, 130,
  78110. /* 110 */ 159, 86, 87, 63, 64, 65, 66, 67, 68, 69,
  78111. /* 120 */ 70, 71, 72, 73, 74, 75, 185, 77, 78, 79,
  78112. /* 130 */ 80, 81, 82, 83, 84, 85, 86, 87, 19, 87,
  78113. /* 140 */ 25, 61, 150, 19, 193, 93, 94, 95, 96, 97,
  78114. /* 150 */ 98, 99, 160, 161, 171, 172, 25, 125, 106, 81,
  78115. /* 160 */ 82, 81, 82, 180, 45, 46, 47, 212, 217, 91,
  78116. /* 170 */ 92, 91, 150, 172, 26, 95, 184, 185, 185, 101,
  78117. /* 180 */ 102, 180, 63, 64, 65, 66, 67, 68, 69, 70,
  78118. /* 190 */ 71, 72, 73, 74, 75, 244, 77, 78, 79, 80,
  78119. /* 200 */ 81, 82, 83, 84, 85, 86, 87, 19, 128, 129,
  78120. /* 210 */ 130, 87, 24, 26, 192, 100, 150, 150, 94, 95,
  78121. /* 220 */ 96, 97, 98, 99, 93, 150, 25, 96, 97, 98,
  78122. /* 230 */ 106, 150, 194, 45, 46, 169, 170, 150, 107, 91,
  78123. /* 240 */ 173, 174, 165, 83, 84, 85, 86, 87, 173, 174,
  78124. /* 250 */ 169, 63, 64, 65, 66, 67, 68, 69, 70, 71,
  78125. /* 260 */ 72, 73, 74, 75, 242, 77, 78, 79, 80, 81,
  78126. /* 270 */ 82, 83, 84, 85, 86, 87, 19, 11, 91, 92,
  78127. /* 280 */ 93, 204, 215, 96, 97, 98, 196, 220, 213, 214,
  78128. /* 290 */ 150, 190, 150, 203, 107, 52, 230, 231, 221, 159,
  78129. /* 300 */ 223, 224, 45, 46, 221, 93, 223, 224, 96, 97,
  78130. /* 310 */ 98, 230, 231, 173, 174, 173, 174, 116, 52, 107,
  78131. /* 320 */ 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
  78132. /* 330 */ 73, 74, 75, 193, 77, 78, 79, 80, 81, 82,
  78133. /* 340 */ 83, 84, 85, 86, 87, 102, 103, 104, 150, 19,
  78134. /* 350 */ 12, 221, 222, 223, 224, 215, 113, 159, 162, 150,
  78135. /* 360 */ 220, 165, 166, 167, 150, 27, 95, 225, 102, 103,
  78136. /* 370 */ 104, 173, 174, 26, 150, 45, 46, 106, 40, 113,
  78137. /* 380 */ 42, 150, 173, 174, 159, 165, 221, 159, 223, 224,
  78138. /* 390 */ 52, 193, 135, 63, 64, 65, 66, 67, 68, 69,
  78139. /* 400 */ 70, 71, 72, 73, 74, 75, 241, 77, 78, 79,
  78140. /* 410 */ 80, 81, 82, 83, 84, 85, 86, 87, 193, 19,
  78141. /* 420 */ 150, 193, 19, 214, 204, 150, 23, 150, 81, 150,
  78142. /* 430 */ 216, 150, 157, 205, 206, 160, 161, 110, 91, 92,
  78143. /* 440 */ 22, 114, 217, 212, 26, 159, 46, 150, 45, 46,
  78144. /* 450 */ 173, 174, 173, 174, 173, 174, 168, 169, 170, 234,
  78145. /* 460 */ 159, 168, 169, 170, 239, 135, 63, 64, 65, 66,
  78146. /* 470 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 193,
  78147. /* 480 */ 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
  78148. /* 490 */ 87, 19, 215, 23, 193, 23, 33, 207, 219, 150,
  78149. /* 500 */ 219, 101, 23, 217, 22, 150, 106, 23, 26, 91,
  78150. /* 510 */ 92, 45, 46, 180, 181, 154, 53, 45, 46, 231,
  78151. /* 520 */ 187, 150, 173, 174, 231, 239, 22, 23, 109, 25,
  78152. /* 530 */ 111, 112, 66, 67, 150, 63, 64, 65, 66, 67,
  78153. /* 540 */ 68, 69, 70, 71, 72, 73, 74, 75, 150, 77,
  78154. /* 550 */ 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
  78155. /* 560 */ 19, 95, 22, 23, 23, 25, 62, 150, 105, 12,
  78156. /* 570 */ 26, 23, 26, 91, 92, 23, 192, 25, 148, 109,
  78157. /* 580 */ 26, 111, 112, 212, 27, 26, 45, 46, 109, 228,
  78158. /* 590 */ 111, 112, 17, 109, 233, 111, 112, 40, 24, 42,
  78159. /* 600 */ 26, 150, 62, 186, 63, 64, 65, 66, 67, 68,
  78160. /* 610 */ 69, 70, 71, 72, 73, 74, 75, 150, 77, 78,
  78161. /* 620 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 19,
  78162. /* 630 */ 55, 195, 57, 23, 165, 91, 92, 91, 92, 94,
  78163. /* 640 */ 173, 174, 83, 150, 92, 91, 92, 0, 1, 2,
  78164. /* 650 */ 91, 92, 7, 8, 9, 45, 46, 109, 113, 111,
  78165. /* 660 */ 112, 117, 150, 117, 22, 91, 173, 174, 26, 117,
  78166. /* 670 */ 189, 190, 127, 63, 64, 65, 66, 67, 68, 69,
  78167. /* 680 */ 70, 71, 72, 73, 74, 75, 150, 77, 78, 79,
  78168. /* 690 */ 80, 81, 82, 83, 84, 85, 86, 87, 19, 102,
  78169. /* 700 */ 103, 104, 19, 24, 192, 150, 189, 190, 150, 173,
  78170. /* 710 */ 174, 150, 137, 150, 28, 150, 150, 150, 32, 102,
  78171. /* 720 */ 103, 104, 247, 248, 45, 46, 160, 161, 173, 174,
  78172. /* 730 */ 44, 173, 174, 91, 173, 174, 173, 174, 173, 174,
  78173. /* 740 */ 173, 174, 63, 64, 65, 66, 67, 68, 69, 70,
  78174. /* 750 */ 71, 72, 73, 74, 75, 150, 77, 78, 79, 80,
  78175. /* 760 */ 81, 82, 83, 84, 85, 86, 87, 19, 150, 144,
  78176. /* 770 */ 145, 159, 150, 164, 150, 113, 150, 22, 173, 174,
  78177. /* 780 */ 150, 150, 173, 150, 25, 150, 150, 150, 22, 127,
  78178. /* 790 */ 24, 173, 174, 45, 46, 173, 174, 173, 174, 173,
  78179. /* 800 */ 174, 118, 17, 173, 174, 193, 173, 174, 150, 173,
  78180. /* 810 */ 174, 63, 64, 65, 66, 67, 68, 69, 70, 71,
  78181. /* 820 */ 72, 73, 74, 75, 150, 77, 78, 79, 80, 81,
  78182. /* 830 */ 82, 83, 84, 85, 86, 87, 19, 150, 245, 246,
  78183. /* 840 */ 55, 150, 57, 150, 83, 150, 150, 173, 174, 150,
  78184. /* 850 */ 192, 92, 150, 216, 150, 205, 206, 150, 128, 129,
  78185. /* 860 */ 173, 174, 45, 46, 173, 174, 173, 174, 173, 174,
  78186. /* 870 */ 115, 110, 173, 174, 165, 114, 117, 173, 174, 150,
  78187. /* 880 */ 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
  78188. /* 890 */ 73, 74, 75, 150, 77, 78, 79, 80, 81, 82,
  78189. /* 900 */ 83, 84, 85, 86, 87, 19, 150, 150, 150, 182,
  78190. /* 910 */ 150, 159, 150, 204, 150, 186, 173, 174, 150, 30,
  78191. /* 920 */ 19, 150, 134, 150, 136, 150, 37, 7, 8, 173,
  78192. /* 930 */ 174, 45, 46, 173, 174, 173, 174, 173, 174, 165,
  78193. /* 940 */ 150, 173, 174, 186, 186, 193, 173, 174, 173, 174,
  78194. /* 950 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
  78195. /* 960 */ 74, 75, 150, 77, 78, 79, 80, 81, 82, 83,
  78196. /* 970 */ 84, 85, 86, 87, 19, 150, 150, 21, 204, 150,
  78197. /* 980 */ 23, 150, 25, 150, 150, 173, 174, 150, 23, 23,
  78198. /* 990 */ 25, 25, 150, 23, 150, 25, 95, 150, 173, 174,
  78199. /* 1000 */ 45, 46, 173, 174, 173, 174, 173, 174, 46, 150,
  78200. /* 1010 */ 173, 174, 186, 150, 58, 173, 174, 173, 174, 150,
  78201. /* 1020 */ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
  78202. /* 1030 */ 75, 150, 77, 78, 79, 80, 81, 82, 83, 84,
  78203. /* 1040 */ 85, 86, 87, 5, 150, 150, 159, 159, 10, 11,
  78204. /* 1050 */ 12, 13, 14, 97, 16, 192, 22, 94, 95, 19,
  78205. /* 1060 */ 20, 192, 22, 101, 23, 150, 26, 29, 23, 31,
  78206. /* 1070 */ 25, 150, 182, 192, 34, 23, 38, 25, 182, 150,
  78207. /* 1080 */ 193, 193, 23, 23, 25, 25, 192, 192, 50, 150,
  78208. /* 1090 */ 52, 51, 150, 137, 56, 150, 150, 59, 23, 235,
  78209. /* 1100 */ 25, 61, 236, 62, 23, 71, 25, 153, 150, 150,
  78210. /* 1110 */ 150, 150, 195, 197, 150, 165, 232, 150, 150, 150,
  78211. /* 1120 */ 227, 81, 82, 150, 150, 150, 150, 150, 176, 232,
  78212. /* 1130 */ 90, 91, 92, 208, 181, 95, 198, 6, 208, 208,
  78213. /* 1140 */ 102, 103, 104, 149, 165, 198, 108, 176, 176, 165,
  78214. /* 1150 */ 149, 113, 149, 113, 176, 149, 176, 13, 177, 151,
  78215. /* 1160 */ 19, 20, 151, 22, 25, 158, 122, 26, 128, 129,
  78216. /* 1170 */ 130, 131, 132, 133, 125, 34, 138, 123, 193, 121,
  78217. /* 1180 */ 198, 124, 199, 19, 20, 134, 22, 200, 202, 201,
  78218. /* 1190 */ 26, 115, 51, 156, 101, 156, 101, 120, 34, 210,
  78219. /* 1200 */ 209, 209, 61, 210, 209, 175, 210, 175, 43, 183,
  78220. /* 1210 */ 175, 100, 22, 177, 87, 51, 226, 175, 18, 155,
  78221. /* 1220 */ 155, 178, 81, 82, 83, 61, 229, 229, 175, 183,
  78222. /* 1230 */ 175, 90, 91, 92, 178, 156, 95, 175, 156, 155,
  78223. /* 1240 */ 41, 156, 156, 134, 155, 81, 82, 237, 156, 63,
  78224. /* 1250 */ 238, 188, 22, 156, 90, 91, 92, 188, 18, 95,
  78225. /* 1260 */ 156, 191, 191, 191, 198, 218, 198, 36, 188, 128,
  78226. /* 1270 */ 129, 130, 131, 132, 133, 156, 156, 140, 191, 218,
  78227. /* 1280 */ 163, 179, 179, 1, 15, 23, 115, 115, 240, 115,
  78228. /* 1290 */ 240, 115, 128, 129, 130, 131, 132, 133, 95, 110,
  78229. /* 1300 */ 22, 11, 23, 23, 23, 22, 22, 119, 23, 117,
  78230. /* 1310 */ 243, 25, 23, 25, 119, 22, 25, 119, 23, 246,
  78231. /* 1320 */ 118, 115, 23, 249, 47, 22, 22, 35, 23, 22,
  78232. /* 1330 */ 22, 22, 99, 106, 47, 19, 24, 20, 101, 39,
  78233. /* 1340 */ 25, 47, 137, 101, 22, 48, 48, 5, 1, 105,
  78234. /* 1350 */ 54, 126, 22, 1, 116, 17, 120, 20, 105, 116,
  78235. /* 1360 */ 126, 22, 127, 23, 15, 17, 60, 139, 22, 3,
  78236. /* 1370 */ 250, 4, 71, 71,
  78237. };
  78238. #define YY_SHIFT_USE_DFLT (-108)
  78239. #define YY_SHIFT_MAX 404
  78240. static const short yy_shift_ofst[] = {
  78241. /* 0 */ 23, 1038, 1040, -19, 1040, 1164, 1164, 187, 78, 243,
  78242. /* 10 */ 119, 1164, 1164, 1164, 1164, 1164, -48, 266, 347, 554,
  78243. /* 20 */ 148, 19, 19, -107, 50, 188, 257, 330, 403, 472,
  78244. /* 30 */ 541, 610, 679, 748, 817, 748, 748, 748, 748, 748,
  78245. /* 40 */ 748, 748, 748, 748, 748, 748, 748, 748, 748, 748,
  78246. /* 50 */ 748, 748, 748, 886, 955, 955, 1141, 1164, 1164, 1164,
  78247. /* 60 */ 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164,
  78248. /* 70 */ 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164,
  78249. /* 80 */ 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164,
  78250. /* 90 */ 1164, 1164, 1164, 1164, 1164, 1164, 1164, -64, -64, -1,
  78251. /* 100 */ -1, 52, 6, 160, 400, 956, 554, 554, 25, 148,
  78252. /* 110 */ -75, -108, -108, -108, 80, 124, 338, 338, 504, 540,
  78253. /* 120 */ 647, 574, 554, 574, 574, 554, 554, 554, 554, 554,
  78254. /* 130 */ 554, 554, 554, 554, 554, 554, 554, 554, 554, 554,
  78255. /* 140 */ 554, 554, 545, 662, -107, -107, -107, -108, -108, -108,
  78256. /* 150 */ -21, -21, 131, 212, 470, 418, 479, 484, 557, 544,
  78257. /* 160 */ 546, 482, 548, 552, 559, 645, 554, 554, 554, 554,
  78258. /* 170 */ 554, 761, 554, 554, 642, 554, 554, 759, 554, 554,
  78259. /* 180 */ 554, 554, 554, 463, 463, 463, 554, 554, 554, 419,
  78260. /* 190 */ 554, 554, 419, 554, 686, 597, 554, 554, 419, 554,
  78261. /* 200 */ 554, 554, 419, 554, 554, 554, 419, 419, 554, 554,
  78262. /* 210 */ 554, 554, 554, 766, 327, 201, 148, 730, 730, 788,
  78263. /* 220 */ 889, 889, 683, 889, 962, 889, 148, 889, 148, 115,
  78264. /* 230 */ 32, 683, 683, 32, 1131, 1131, 1131, 1131, 1144, 1144,
  78265. /* 240 */ 1139, -107, 1049, 1044, 1054, 1058, 1057, 1051, 1076, 1076,
  78266. /* 250 */ 1093, 1077, 1093, 1077, 1093, 1077, 1095, 1095, 1165, 1095,
  78267. /* 260 */ 1111, 1095, 1190, 1127, 1127, 1165, 1095, 1095, 1095, 1190,
  78268. /* 270 */ 1200, 1076, 1200, 1076, 1200, 1076, 1076, 1199, 1109, 1200,
  78269. /* 280 */ 1076, 1186, 1186, 1230, 1049, 1076, 1240, 1240, 1240, 1240,
  78270. /* 290 */ 1049, 1186, 1230, 1076, 1231, 1231, 1076, 1076, 1137, -108,
  78271. /* 300 */ -108, -108, -108, -108, 466, 575, 617, 785, 755, 901,
  78272. /* 310 */ 957, 965, 271, 920, 963, 966, 970, 1045, 1052, 1059,
  78273. /* 320 */ 1060, 1075, 1034, 1081, 1041, 1282, 1269, 1262, 1171, 1172,
  78274. /* 330 */ 1174, 1176, 1203, 1189, 1278, 1279, 1280, 1283, 1290, 1284,
  78275. /* 340 */ 1281, 1286, 1285, 1289, 1288, 1188, 1291, 1195, 1288, 1192,
  78276. /* 350 */ 1293, 1198, 1202, 1206, 1295, 1299, 1292, 1277, 1303, 1287,
  78277. /* 360 */ 1304, 1305, 1307, 1308, 1294, 1309, 1233, 1227, 1316, 1317,
  78278. /* 370 */ 1312, 1237, 1300, 1296, 1297, 1315, 1298, 1205, 1242, 1322,
  78279. /* 380 */ 1342, 1347, 1244, 1301, 1302, 1225, 1330, 1238, 1352, 1338,
  78280. /* 390 */ 1236, 1337, 1243, 1253, 1234, 1339, 1235, 1340, 1348, 1306,
  78281. /* 400 */ 1349, 1228, 1346, 1366, 1367,
  78282. };
  78283. #define YY_REDUCE_USE_DFLT (-142)
  78284. #define YY_REDUCE_MAX 303
  78285. static const short yy_reduce_ofst[] = {
  78286. /* 0 */ -141, -49, 140, 77, 198, 67, 75, -8, 66, 225,
  78287. /* 10 */ 165, 142, 209, 277, 279, 281, 130, 286, 81, 275,
  78288. /* 20 */ 196, 288, 293, 228, 83, 83, 83, 83, 83, 83,
  78289. /* 30 */ 83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
  78290. /* 40 */ 83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
  78291. /* 50 */ 83, 83, 83, 83, 83, 83, 349, 467, 493, 536,
  78292. /* 60 */ 555, 558, 561, 563, 565, 567, 605, 618, 622, 624,
  78293. /* 70 */ 626, 630, 633, 636, 674, 687, 691, 693, 695, 699,
  78294. /* 80 */ 704, 743, 756, 760, 762, 764, 768, 773, 775, 812,
  78295. /* 90 */ 825, 829, 831, 833, 837, 842, 844, 83, 83, 83,
  78296. /* 100 */ 83, -17, 83, 83, 333, 361, 22, 566, 83, -124,
  78297. /* 110 */ 83, 83, 83, 83, 609, 1, 481, 517, 475, 475,
  78298. /* 120 */ 625, 220, -45, 709, 774, 417, 729, 757, 758, 384,
  78299. /* 130 */ 231, 826, 214, 371, 512, 658, 863, 869, 881, 894,
  78300. /* 140 */ 637, 895, 301, 612, 752, 887, 888, 90, 650, 593,
  78301. /* 150 */ -100, -79, -59, -7, 38, 87, 38, 38, 101, 224,
  78302. /* 160 */ 270, 297, 38, 290, 355, 430, 398, 451, 631, 696,
  78303. /* 170 */ 702, 436, 355, 707, 469, 635, 771, 290, 790, 834,
  78304. /* 180 */ 847, 859, 915, 727, 890, 896, 921, 929, 939, 38,
  78305. /* 190 */ 942, 945, 38, 946, 864, 866, 958, 959, 38, 960,
  78306. /* 200 */ 961, 964, 38, 967, 968, 969, 38, 38, 973, 974,
  78307. /* 210 */ 975, 976, 977, 954, 917, 916, 950, 884, 897, 893,
  78308. /* 220 */ 952, 971, 925, 972, 953, 978, 979, 980, 984, 981,
  78309. /* 230 */ 938, 930, 931, 947, 994, 1001, 1003, 1006, 1008, 1011,
  78310. /* 240 */ 1007, 985, 982, 983, 987, 988, 986, 990, 1037, 1039,
  78311. /* 250 */ 991, 989, 992, 993, 995, 996, 1030, 1032, 1026, 1035,
  78312. /* 260 */ 1036, 1042, 1043, 997, 998, 1046, 1053, 1055, 1062, 1056,
  78313. /* 270 */ 1064, 1079, 1065, 1082, 1084, 1085, 1086, 1010, 1012, 1089,
  78314. /* 280 */ 1092, 1063, 1069, 1047, 1066, 1097, 1070, 1071, 1072, 1087,
  78315. /* 290 */ 1068, 1080, 1061, 1104, 1048, 1050, 1119, 1120, 1067, 1117,
  78316. /* 300 */ 1102, 1103, 1073, 1074,
  78317. };
  78318. static const YYACTIONTYPE yy_default[] = {
  78319. /* 0 */ 615, 929, 848, 736, 929, 848, 929, 929, 875, 929,
  78320. /* 10 */ 904, 846, 929, 929, 929, 929, 820, 929, 875, 929,
  78321. /* 20 */ 652, 875, 875, 740, 771, 929, 929, 929, 929, 929,
  78322. /* 30 */ 929, 929, 929, 772, 929, 850, 845, 841, 843, 842,
  78323. /* 40 */ 849, 773, 762, 769, 776, 751, 888, 778, 779, 785,
  78324. /* 50 */ 786, 905, 903, 808, 807, 826, 929, 929, 929, 929,
  78325. /* 60 */ 929, 929, 929, 929, 929, 929, 929, 929, 929, 929,
  78326. /* 70 */ 929, 929, 929, 929, 929, 929, 929, 929, 929, 929,
  78327. /* 80 */ 929, 929, 929, 929, 929, 929, 929, 929, 929, 929,
  78328. /* 90 */ 929, 929, 929, 929, 929, 929, 929, 810, 832, 809,
  78329. /* 100 */ 819, 645, 811, 812, 705, 640, 929, 929, 813, 929,
  78330. /* 110 */ 814, 827, 828, 829, 929, 929, 929, 929, 929, 929,
  78331. /* 120 */ 615, 736, 929, 736, 736, 929, 929, 929, 929, 929,
  78332. /* 130 */ 929, 929, 929, 929, 929, 929, 929, 929, 929, 929,
  78333. /* 140 */ 929, 929, 929, 929, 929, 929, 929, 730, 740, 922,
  78334. /* 150 */ 929, 929, 696, 929, 929, 929, 929, 929, 929, 929,
  78335. /* 160 */ 929, 929, 929, 929, 929, 623, 621, 929, 929, 929,
  78336. /* 170 */ 929, 728, 929, 929, 654, 929, 929, 738, 929, 929,
  78337. /* 180 */ 929, 929, 929, 929, 929, 929, 929, 929, 929, 642,
  78338. /* 190 */ 929, 929, 717, 929, 881, 929, 929, 929, 895, 929,
  78339. /* 200 */ 929, 929, 893, 929, 929, 929, 719, 781, 861, 929,
  78340. /* 210 */ 908, 910, 929, 929, 728, 737, 929, 929, 929, 844,
  78341. /* 220 */ 765, 765, 753, 765, 675, 765, 929, 765, 929, 678,
  78342. /* 230 */ 775, 753, 753, 775, 620, 620, 620, 620, 631, 631,
  78343. /* 240 */ 695, 929, 775, 766, 768, 758, 770, 929, 744, 744,
  78344. /* 250 */ 752, 757, 752, 757, 752, 757, 707, 707, 692, 707,
  78345. /* 260 */ 678, 707, 854, 858, 858, 692, 707, 707, 707, 854,
  78346. /* 270 */ 637, 744, 637, 744, 637, 744, 744, 885, 887, 637,
  78347. /* 280 */ 744, 709, 709, 787, 775, 744, 716, 716, 716, 716,
  78348. /* 290 */ 775, 709, 787, 744, 907, 907, 744, 744, 915, 662,
  78349. /* 300 */ 680, 680, 922, 927, 929, 929, 929, 929, 794, 929,
  78350. /* 310 */ 929, 929, 929, 929, 929, 929, 929, 929, 929, 929,
  78351. /* 320 */ 929, 929, 868, 929, 929, 929, 629, 929, 799, 795,
  78352. /* 330 */ 929, 796, 929, 722, 929, 929, 929, 929, 929, 929,
  78353. /* 340 */ 929, 929, 929, 929, 847, 929, 759, 929, 767, 929,
  78354. /* 350 */ 929, 929, 929, 929, 929, 929, 929, 929, 929, 929,
  78355. /* 360 */ 929, 929, 929, 929, 929, 929, 929, 929, 929, 929,
  78356. /* 370 */ 929, 929, 929, 929, 883, 884, 929, 929, 929, 929,
  78357. /* 380 */ 929, 929, 929, 929, 929, 929, 929, 929, 929, 929,
  78358. /* 390 */ 929, 929, 929, 929, 929, 929, 929, 929, 929, 914,
  78359. /* 400 */ 929, 929, 917, 616, 929, 611, 613, 614, 618, 619,
  78360. /* 410 */ 622, 649, 650, 651, 624, 625, 626, 627, 628, 630,
  78361. /* 420 */ 634, 632, 633, 635, 641, 643, 661, 663, 647, 665,
  78362. /* 430 */ 726, 727, 791, 720, 721, 725, 648, 802, 793, 797,
  78363. /* 440 */ 798, 800, 801, 815, 816, 818, 824, 831, 834, 817,
  78364. /* 450 */ 822, 823, 825, 830, 833, 723, 724, 837, 655, 656,
  78365. /* 460 */ 659, 660, 871, 873, 872, 874, 658, 657, 803, 806,
  78366. /* 470 */ 839, 840, 896, 897, 898, 899, 900, 835, 745, 838,
  78367. /* 480 */ 821, 760, 763, 764, 761, 729, 739, 747, 748, 749,
  78368. /* 490 */ 750, 734, 735, 741, 756, 789, 790, 754, 755, 742,
  78369. /* 500 */ 743, 731, 732, 733, 836, 792, 804, 805, 666, 667,
  78370. /* 510 */ 799, 668, 669, 670, 708, 711, 712, 713, 671, 690,
  78371. /* 520 */ 693, 694, 672, 679, 673, 674, 681, 682, 683, 686,
  78372. /* 530 */ 687, 688, 689, 684, 685, 855, 856, 859, 857, 676,
  78373. /* 540 */ 677, 691, 664, 653, 646, 697, 700, 701, 702, 703,
  78374. /* 550 */ 704, 706, 698, 699, 644, 636, 638, 746, 877, 886,
  78375. /* 560 */ 882, 878, 879, 880, 639, 851, 852, 710, 783, 784,
  78376. /* 570 */ 876, 889, 891, 788, 892, 894, 890, 919, 714, 715,
  78377. /* 580 */ 718, 860, 901, 774, 777, 780, 782, 862, 863, 864,
  78378. /* 590 */ 865, 866, 869, 870, 867, 902, 906, 909, 911, 912,
  78379. /* 600 */ 913, 916, 918, 923, 924, 925, 928, 926, 617, 612,
  78380. };
  78381. #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
  78382. /* The next table maps tokens into fallback tokens. If a construct
  78383. ** like the following:
  78384. **
  78385. ** %fallback ID X Y Z.
  78386. **
  78387. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  78388. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  78389. ** but it does not parse, the type of the token is changed to ID and
  78390. ** the parse is retried before an error is thrown.
  78391. */
  78392. #ifdef YYFALLBACK
  78393. static const YYCODETYPE yyFallback[] = {
  78394. 0, /* $ => nothing */
  78395. 0, /* SEMI => nothing */
  78396. 26, /* EXPLAIN => ID */
  78397. 26, /* QUERY => ID */
  78398. 26, /* PLAN => ID */
  78399. 26, /* BEGIN => ID */
  78400. 0, /* TRANSACTION => nothing */
  78401. 26, /* DEFERRED => ID */
  78402. 26, /* IMMEDIATE => ID */
  78403. 26, /* EXCLUSIVE => ID */
  78404. 0, /* COMMIT => nothing */
  78405. 26, /* END => ID */
  78406. 0, /* ROLLBACK => nothing */
  78407. 0, /* SAVEPOINT => nothing */
  78408. 0, /* RELEASE => nothing */
  78409. 0, /* TO => nothing */
  78410. 0, /* CREATE => nothing */
  78411. 0, /* TABLE => nothing */
  78412. 26, /* IF => ID */
  78413. 0, /* NOT => nothing */
  78414. 0, /* EXISTS => nothing */
  78415. 26, /* TEMP => ID */
  78416. 0, /* LP => nothing */
  78417. 0, /* RP => nothing */
  78418. 0, /* AS => nothing */
  78419. 0, /* COMMA => nothing */
  78420. 0, /* ID => nothing */
  78421. 26, /* ABORT => ID */
  78422. 26, /* AFTER => ID */
  78423. 26, /* ANALYZE => ID */
  78424. 26, /* ASC => ID */
  78425. 26, /* ATTACH => ID */
  78426. 26, /* BEFORE => ID */
  78427. 26, /* CASCADE => ID */
  78428. 26, /* CAST => ID */
  78429. 26, /* CONFLICT => ID */
  78430. 26, /* DATABASE => ID */
  78431. 26, /* DESC => ID */
  78432. 26, /* DETACH => ID */
  78433. 26, /* EACH => ID */
  78434. 26, /* FAIL => ID */
  78435. 26, /* FOR => ID */
  78436. 26, /* IGNORE => ID */
  78437. 26, /* INITIALLY => ID */
  78438. 26, /* INSTEAD => ID */
  78439. 26, /* LIKE_KW => ID */
  78440. 26, /* MATCH => ID */
  78441. 26, /* KEY => ID */
  78442. 26, /* OF => ID */
  78443. 26, /* OFFSET => ID */
  78444. 26, /* PRAGMA => ID */
  78445. 26, /* RAISE => ID */
  78446. 26, /* REPLACE => ID */
  78447. 26, /* RESTRICT => ID */
  78448. 26, /* ROW => ID */
  78449. 26, /* TRIGGER => ID */
  78450. 26, /* VACUUM => ID */
  78451. 26, /* VIEW => ID */
  78452. 26, /* VIRTUAL => ID */
  78453. 26, /* REINDEX => ID */
  78454. 26, /* RENAME => ID */
  78455. 26, /* CTIME_KW => ID */
  78456. 0, /* ANY => nothing */
  78457. 0, /* OR => nothing */
  78458. 0, /* AND => nothing */
  78459. 0, /* IS => nothing */
  78460. 0, /* BETWEEN => nothing */
  78461. 0, /* IN => nothing */
  78462. 0, /* ISNULL => nothing */
  78463. 0, /* NOTNULL => nothing */
  78464. 0, /* NE => nothing */
  78465. 0, /* EQ => nothing */
  78466. 0, /* GT => nothing */
  78467. 0, /* LE => nothing */
  78468. 0, /* LT => nothing */
  78469. 0, /* GE => nothing */
  78470. 0, /* ESCAPE => nothing */
  78471. 0, /* BITAND => nothing */
  78472. 0, /* BITOR => nothing */
  78473. 0, /* LSHIFT => nothing */
  78474. 0, /* RSHIFT => nothing */
  78475. 0, /* PLUS => nothing */
  78476. 0, /* MINUS => nothing */
  78477. 0, /* STAR => nothing */
  78478. 0, /* SLASH => nothing */
  78479. 0, /* REM => nothing */
  78480. 0, /* CONCAT => nothing */
  78481. 0, /* COLLATE => nothing */
  78482. 0, /* UMINUS => nothing */
  78483. 0, /* UPLUS => nothing */
  78484. 0, /* BITNOT => nothing */
  78485. 0, /* STRING => nothing */
  78486. 0, /* JOIN_KW => nothing */
  78487. 0, /* CONSTRAINT => nothing */
  78488. 0, /* DEFAULT => nothing */
  78489. 0, /* NULL => nothing */
  78490. 0, /* PRIMARY => nothing */
  78491. 0, /* UNIQUE => nothing */
  78492. 0, /* CHECK => nothing */
  78493. 0, /* REFERENCES => nothing */
  78494. 0, /* AUTOINCR => nothing */
  78495. 0, /* ON => nothing */
  78496. 0, /* DELETE => nothing */
  78497. 0, /* UPDATE => nothing */
  78498. 0, /* INSERT => nothing */
  78499. 0, /* SET => nothing */
  78500. 0, /* DEFERRABLE => nothing */
  78501. 0, /* FOREIGN => nothing */
  78502. 0, /* DROP => nothing */
  78503. 0, /* UNION => nothing */
  78504. 0, /* ALL => nothing */
  78505. 0, /* EXCEPT => nothing */
  78506. 0, /* INTERSECT => nothing */
  78507. 0, /* SELECT => nothing */
  78508. 0, /* DISTINCT => nothing */
  78509. 0, /* DOT => nothing */
  78510. 0, /* FROM => nothing */
  78511. 0, /* JOIN => nothing */
  78512. 0, /* INDEXED => nothing */
  78513. 0, /* BY => nothing */
  78514. 0, /* USING => nothing */
  78515. 0, /* ORDER => nothing */
  78516. 0, /* GROUP => nothing */
  78517. 0, /* HAVING => nothing */
  78518. 0, /* LIMIT => nothing */
  78519. 0, /* WHERE => nothing */
  78520. 0, /* INTO => nothing */
  78521. 0, /* VALUES => nothing */
  78522. 0, /* INTEGER => nothing */
  78523. 0, /* FLOAT => nothing */
  78524. 0, /* BLOB => nothing */
  78525. 0, /* REGISTER => nothing */
  78526. 0, /* VARIABLE => nothing */
  78527. 0, /* CASE => nothing */
  78528. 0, /* WHEN => nothing */
  78529. 0, /* THEN => nothing */
  78530. 0, /* ELSE => nothing */
  78531. 0, /* INDEX => nothing */
  78532. 0, /* ALTER => nothing */
  78533. 0, /* ADD => nothing */
  78534. 0, /* COLUMNKW => nothing */
  78535. };
  78536. #endif /* YYFALLBACK */
  78537. /* The following structure represents a single element of the
  78538. ** parser's stack. Information stored includes:
  78539. **
  78540. ** + The state number for the parser at this level of the stack.
  78541. **
  78542. ** + The value of the token stored at this level of the stack.
  78543. ** (In other words, the "major" token.)
  78544. **
  78545. ** + The semantic value stored at this level of the stack. This is
  78546. ** the information used by the action routines in the grammar.
  78547. ** It is sometimes called the "minor" token.
  78548. */
  78549. struct yyStackEntry {
  78550. YYACTIONTYPE stateno; /* The state-number */
  78551. YYCODETYPE major; /* The major token value. This is the code
  78552. ** number for the token at this stack level */
  78553. YYMINORTYPE minor; /* The user-supplied minor token value. This
  78554. ** is the value of the token */
  78555. };
  78556. typedef struct yyStackEntry yyStackEntry;
  78557. /* The state of the parser is completely contained in an instance of
  78558. ** the following structure */
  78559. struct yyParser {
  78560. int yyidx; /* Index of top element in stack */
  78561. #ifdef YYTRACKMAXSTACKDEPTH
  78562. int yyidxMax; /* Maximum value of yyidx */
  78563. #endif
  78564. int yyerrcnt; /* Shifts left before out of the error */
  78565. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  78566. #if YYSTACKDEPTH<=0
  78567. int yystksz; /* Current side of the stack */
  78568. yyStackEntry *yystack; /* The parser's stack */
  78569. #else
  78570. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  78571. #endif
  78572. };
  78573. typedef struct yyParser yyParser;
  78574. #ifndef NDEBUG
  78575. static FILE *yyTraceFILE = 0;
  78576. static char *yyTracePrompt = 0;
  78577. #endif /* NDEBUG */
  78578. #ifndef NDEBUG
  78579. /*
  78580. ** Turn parser tracing on by giving a stream to which to write the trace
  78581. ** and a prompt to preface each trace message. Tracing is turned off
  78582. ** by making either argument NULL
  78583. **
  78584. ** Inputs:
  78585. ** <ul>
  78586. ** <li> A FILE* to which trace output should be written.
  78587. ** If NULL, then tracing is turned off.
  78588. ** <li> A prefix string written at the beginning of every
  78589. ** line of trace output. If NULL, then tracing is
  78590. ** turned off.
  78591. ** </ul>
  78592. **
  78593. ** Outputs:
  78594. ** None.
  78595. */
  78596. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  78597. yyTraceFILE = TraceFILE;
  78598. yyTracePrompt = zTracePrompt;
  78599. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  78600. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  78601. }
  78602. #endif /* NDEBUG */
  78603. #ifndef NDEBUG
  78604. /* For tracing shifts, the names of all terminals and nonterminals
  78605. ** are required. The following table supplies these names */
  78606. static const char *const yyTokenName[] = {
  78607. "$", "SEMI", "EXPLAIN", "QUERY",
  78608. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  78609. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  78610. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  78611. "CREATE", "TABLE", "IF", "NOT",
  78612. "EXISTS", "TEMP", "LP", "RP",
  78613. "AS", "COMMA", "ID", "ABORT",
  78614. "AFTER", "ANALYZE", "ASC", "ATTACH",
  78615. "BEFORE", "CASCADE", "CAST", "CONFLICT",
  78616. "DATABASE", "DESC", "DETACH", "EACH",
  78617. "FAIL", "FOR", "IGNORE", "INITIALLY",
  78618. "INSTEAD", "LIKE_KW", "MATCH", "KEY",
  78619. "OF", "OFFSET", "PRAGMA", "RAISE",
  78620. "REPLACE", "RESTRICT", "ROW", "TRIGGER",
  78621. "VACUUM", "VIEW", "VIRTUAL", "REINDEX",
  78622. "RENAME", "CTIME_KW", "ANY", "OR",
  78623. "AND", "IS", "BETWEEN", "IN",
  78624. "ISNULL", "NOTNULL", "NE", "EQ",
  78625. "GT", "LE", "LT", "GE",
  78626. "ESCAPE", "BITAND", "BITOR", "LSHIFT",
  78627. "RSHIFT", "PLUS", "MINUS", "STAR",
  78628. "SLASH", "REM", "CONCAT", "COLLATE",
  78629. "UMINUS", "UPLUS", "BITNOT", "STRING",
  78630. "JOIN_KW", "CONSTRAINT", "DEFAULT", "NULL",
  78631. "PRIMARY", "UNIQUE", "CHECK", "REFERENCES",
  78632. "AUTOINCR", "ON", "DELETE", "UPDATE",
  78633. "INSERT", "SET", "DEFERRABLE", "FOREIGN",
  78634. "DROP", "UNION", "ALL", "EXCEPT",
  78635. "INTERSECT", "SELECT", "DISTINCT", "DOT",
  78636. "FROM", "JOIN", "INDEXED", "BY",
  78637. "USING", "ORDER", "GROUP", "HAVING",
  78638. "LIMIT", "WHERE", "INTO", "VALUES",
  78639. "INTEGER", "FLOAT", "BLOB", "REGISTER",
  78640. "VARIABLE", "CASE", "WHEN", "THEN",
  78641. "ELSE", "INDEX", "ALTER", "ADD",
  78642. "COLUMNKW", "error", "input", "cmdlist",
  78643. "ecmd", "explain", "cmdx", "cmd",
  78644. "transtype", "trans_opt", "nm", "savepoint_opt",
  78645. "create_table", "create_table_args", "temp", "ifnotexists",
  78646. "dbnm", "columnlist", "conslist_opt", "select",
  78647. "column", "columnid", "type", "carglist",
  78648. "id", "ids", "typetoken", "typename",
  78649. "signed", "plus_num", "minus_num", "carg",
  78650. "ccons", "term", "expr", "onconf",
  78651. "sortorder", "autoinc", "idxlist_opt", "refargs",
  78652. "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
  78653. "conslist", "tcons", "idxlist", "defer_subclause_opt",
  78654. "orconf", "resolvetype", "raisetype", "ifexists",
  78655. "fullname", "oneselect", "multiselect_op", "distinct",
  78656. "selcollist", "from", "where_opt", "groupby_opt",
  78657. "having_opt", "orderby_opt", "limit_opt", "sclp",
  78658. "as", "seltablist", "stl_prefix", "joinop",
  78659. "indexed_opt", "on_opt", "using_opt", "joinop2",
  78660. "inscollist", "sortlist", "sortitem", "nexprlist",
  78661. "setlist", "insert_cmd", "inscollist_opt", "itemlist",
  78662. "exprlist", "likeop", "escape", "between_op",
  78663. "in_op", "case_operand", "case_exprlist", "case_else",
  78664. "uniqueflag", "collate", "nmnum", "plus_opt",
  78665. "number", "trigger_decl", "trigger_cmd_list", "trigger_time",
  78666. "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
  78667. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  78668. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  78669. "lp", "anylist",
  78670. };
  78671. #endif /* NDEBUG */
  78672. #ifndef NDEBUG
  78673. /* For tracing reduce actions, the names of all rules are required.
  78674. */
  78675. static const char *const yyRuleName[] = {
  78676. /* 0 */ "input ::= cmdlist",
  78677. /* 1 */ "cmdlist ::= cmdlist ecmd",
  78678. /* 2 */ "cmdlist ::= ecmd",
  78679. /* 3 */ "ecmd ::= SEMI",
  78680. /* 4 */ "ecmd ::= explain cmdx SEMI",
  78681. /* 5 */ "explain ::=",
  78682. /* 6 */ "explain ::= EXPLAIN",
  78683. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  78684. /* 8 */ "cmdx ::= cmd",
  78685. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  78686. /* 10 */ "trans_opt ::=",
  78687. /* 11 */ "trans_opt ::= TRANSACTION",
  78688. /* 12 */ "trans_opt ::= TRANSACTION nm",
  78689. /* 13 */ "transtype ::=",
  78690. /* 14 */ "transtype ::= DEFERRED",
  78691. /* 15 */ "transtype ::= IMMEDIATE",
  78692. /* 16 */ "transtype ::= EXCLUSIVE",
  78693. /* 17 */ "cmd ::= COMMIT trans_opt",
  78694. /* 18 */ "cmd ::= END trans_opt",
  78695. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  78696. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  78697. /* 21 */ "savepoint_opt ::=",
  78698. /* 22 */ "cmd ::= SAVEPOINT nm",
  78699. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  78700. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  78701. /* 25 */ "cmd ::= create_table create_table_args",
  78702. /* 26 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
  78703. /* 27 */ "ifnotexists ::=",
  78704. /* 28 */ "ifnotexists ::= IF NOT EXISTS",
  78705. /* 29 */ "temp ::= TEMP",
  78706. /* 30 */ "temp ::=",
  78707. /* 31 */ "create_table_args ::= LP columnlist conslist_opt RP",
  78708. /* 32 */ "create_table_args ::= AS select",
  78709. /* 33 */ "columnlist ::= columnlist COMMA column",
  78710. /* 34 */ "columnlist ::= column",
  78711. /* 35 */ "column ::= columnid type carglist",
  78712. /* 36 */ "columnid ::= nm",
  78713. /* 37 */ "id ::= ID",
  78714. /* 38 */ "ids ::= ID|STRING",
  78715. /* 39 */ "nm ::= ID",
  78716. /* 40 */ "nm ::= STRING",
  78717. /* 41 */ "nm ::= JOIN_KW",
  78718. /* 42 */ "type ::=",
  78719. /* 43 */ "type ::= typetoken",
  78720. /* 44 */ "typetoken ::= typename",
  78721. /* 45 */ "typetoken ::= typename LP signed RP",
  78722. /* 46 */ "typetoken ::= typename LP signed COMMA signed RP",
  78723. /* 47 */ "typename ::= ids",
  78724. /* 48 */ "typename ::= typename ids",
  78725. /* 49 */ "signed ::= plus_num",
  78726. /* 50 */ "signed ::= minus_num",
  78727. /* 51 */ "carglist ::= carglist carg",
  78728. /* 52 */ "carglist ::=",
  78729. /* 53 */ "carg ::= CONSTRAINT nm ccons",
  78730. /* 54 */ "carg ::= ccons",
  78731. /* 55 */ "ccons ::= DEFAULT term",
  78732. /* 56 */ "ccons ::= DEFAULT LP expr RP",
  78733. /* 57 */ "ccons ::= DEFAULT PLUS term",
  78734. /* 58 */ "ccons ::= DEFAULT MINUS term",
  78735. /* 59 */ "ccons ::= DEFAULT id",
  78736. /* 60 */ "ccons ::= NULL onconf",
  78737. /* 61 */ "ccons ::= NOT NULL onconf",
  78738. /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  78739. /* 63 */ "ccons ::= UNIQUE onconf",
  78740. /* 64 */ "ccons ::= CHECK LP expr RP",
  78741. /* 65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  78742. /* 66 */ "ccons ::= defer_subclause",
  78743. /* 67 */ "ccons ::= COLLATE ids",
  78744. /* 68 */ "autoinc ::=",
  78745. /* 69 */ "autoinc ::= AUTOINCR",
  78746. /* 70 */ "refargs ::=",
  78747. /* 71 */ "refargs ::= refargs refarg",
  78748. /* 72 */ "refarg ::= MATCH nm",
  78749. /* 73 */ "refarg ::= ON DELETE refact",
  78750. /* 74 */ "refarg ::= ON UPDATE refact",
  78751. /* 75 */ "refarg ::= ON INSERT refact",
  78752. /* 76 */ "refact ::= SET NULL",
  78753. /* 77 */ "refact ::= SET DEFAULT",
  78754. /* 78 */ "refact ::= CASCADE",
  78755. /* 79 */ "refact ::= RESTRICT",
  78756. /* 80 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  78757. /* 81 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  78758. /* 82 */ "init_deferred_pred_opt ::=",
  78759. /* 83 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  78760. /* 84 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  78761. /* 85 */ "conslist_opt ::=",
  78762. /* 86 */ "conslist_opt ::= COMMA conslist",
  78763. /* 87 */ "conslist ::= conslist COMMA tcons",
  78764. /* 88 */ "conslist ::= conslist tcons",
  78765. /* 89 */ "conslist ::= tcons",
  78766. /* 90 */ "tcons ::= CONSTRAINT nm",
  78767. /* 91 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  78768. /* 92 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  78769. /* 93 */ "tcons ::= CHECK LP expr RP onconf",
  78770. /* 94 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  78771. /* 95 */ "defer_subclause_opt ::=",
  78772. /* 96 */ "defer_subclause_opt ::= defer_subclause",
  78773. /* 97 */ "onconf ::=",
  78774. /* 98 */ "onconf ::= ON CONFLICT resolvetype",
  78775. /* 99 */ "orconf ::=",
  78776. /* 100 */ "orconf ::= OR resolvetype",
  78777. /* 101 */ "resolvetype ::= raisetype",
  78778. /* 102 */ "resolvetype ::= IGNORE",
  78779. /* 103 */ "resolvetype ::= REPLACE",
  78780. /* 104 */ "cmd ::= DROP TABLE ifexists fullname",
  78781. /* 105 */ "ifexists ::= IF EXISTS",
  78782. /* 106 */ "ifexists ::=",
  78783. /* 107 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
  78784. /* 108 */ "cmd ::= DROP VIEW ifexists fullname",
  78785. /* 109 */ "cmd ::= select",
  78786. /* 110 */ "select ::= oneselect",
  78787. /* 111 */ "select ::= select multiselect_op oneselect",
  78788. /* 112 */ "multiselect_op ::= UNION",
  78789. /* 113 */ "multiselect_op ::= UNION ALL",
  78790. /* 114 */ "multiselect_op ::= EXCEPT|INTERSECT",
  78791. /* 115 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  78792. /* 116 */ "distinct ::= DISTINCT",
  78793. /* 117 */ "distinct ::= ALL",
  78794. /* 118 */ "distinct ::=",
  78795. /* 119 */ "sclp ::= selcollist COMMA",
  78796. /* 120 */ "sclp ::=",
  78797. /* 121 */ "selcollist ::= sclp expr as",
  78798. /* 122 */ "selcollist ::= sclp STAR",
  78799. /* 123 */ "selcollist ::= sclp nm DOT STAR",
  78800. /* 124 */ "as ::= AS nm",
  78801. /* 125 */ "as ::= ids",
  78802. /* 126 */ "as ::=",
  78803. /* 127 */ "from ::=",
  78804. /* 128 */ "from ::= FROM seltablist",
  78805. /* 129 */ "stl_prefix ::= seltablist joinop",
  78806. /* 130 */ "stl_prefix ::=",
  78807. /* 131 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  78808. /* 132 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  78809. /* 133 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  78810. /* 134 */ "dbnm ::=",
  78811. /* 135 */ "dbnm ::= DOT nm",
  78812. /* 136 */ "fullname ::= nm dbnm",
  78813. /* 137 */ "joinop ::= COMMA|JOIN",
  78814. /* 138 */ "joinop ::= JOIN_KW JOIN",
  78815. /* 139 */ "joinop ::= JOIN_KW nm JOIN",
  78816. /* 140 */ "joinop ::= JOIN_KW nm nm JOIN",
  78817. /* 141 */ "on_opt ::= ON expr",
  78818. /* 142 */ "on_opt ::=",
  78819. /* 143 */ "indexed_opt ::=",
  78820. /* 144 */ "indexed_opt ::= INDEXED BY nm",
  78821. /* 145 */ "indexed_opt ::= NOT INDEXED",
  78822. /* 146 */ "using_opt ::= USING LP inscollist RP",
  78823. /* 147 */ "using_opt ::=",
  78824. /* 148 */ "orderby_opt ::=",
  78825. /* 149 */ "orderby_opt ::= ORDER BY sortlist",
  78826. /* 150 */ "sortlist ::= sortlist COMMA sortitem sortorder",
  78827. /* 151 */ "sortlist ::= sortitem sortorder",
  78828. /* 152 */ "sortitem ::= expr",
  78829. /* 153 */ "sortorder ::= ASC",
  78830. /* 154 */ "sortorder ::= DESC",
  78831. /* 155 */ "sortorder ::=",
  78832. /* 156 */ "groupby_opt ::=",
  78833. /* 157 */ "groupby_opt ::= GROUP BY nexprlist",
  78834. /* 158 */ "having_opt ::=",
  78835. /* 159 */ "having_opt ::= HAVING expr",
  78836. /* 160 */ "limit_opt ::=",
  78837. /* 161 */ "limit_opt ::= LIMIT expr",
  78838. /* 162 */ "limit_opt ::= LIMIT expr OFFSET expr",
  78839. /* 163 */ "limit_opt ::= LIMIT expr COMMA expr",
  78840. /* 164 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
  78841. /* 165 */ "where_opt ::=",
  78842. /* 166 */ "where_opt ::= WHERE expr",
  78843. /* 167 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
  78844. /* 168 */ "setlist ::= setlist COMMA nm EQ expr",
  78845. /* 169 */ "setlist ::= nm EQ expr",
  78846. /* 170 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
  78847. /* 171 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
  78848. /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  78849. /* 173 */ "insert_cmd ::= INSERT orconf",
  78850. /* 174 */ "insert_cmd ::= REPLACE",
  78851. /* 175 */ "itemlist ::= itemlist COMMA expr",
  78852. /* 176 */ "itemlist ::= expr",
  78853. /* 177 */ "inscollist_opt ::=",
  78854. /* 178 */ "inscollist_opt ::= LP inscollist RP",
  78855. /* 179 */ "inscollist ::= inscollist COMMA nm",
  78856. /* 180 */ "inscollist ::= nm",
  78857. /* 181 */ "expr ::= term",
  78858. /* 182 */ "expr ::= LP expr RP",
  78859. /* 183 */ "term ::= NULL",
  78860. /* 184 */ "expr ::= ID",
  78861. /* 185 */ "expr ::= JOIN_KW",
  78862. /* 186 */ "expr ::= nm DOT nm",
  78863. /* 187 */ "expr ::= nm DOT nm DOT nm",
  78864. /* 188 */ "term ::= INTEGER|FLOAT|BLOB",
  78865. /* 189 */ "term ::= STRING",
  78866. /* 190 */ "expr ::= REGISTER",
  78867. /* 191 */ "expr ::= VARIABLE",
  78868. /* 192 */ "expr ::= expr COLLATE ids",
  78869. /* 193 */ "expr ::= CAST LP expr AS typetoken RP",
  78870. /* 194 */ "expr ::= ID LP distinct exprlist RP",
  78871. /* 195 */ "expr ::= ID LP STAR RP",
  78872. /* 196 */ "term ::= CTIME_KW",
  78873. /* 197 */ "expr ::= expr AND expr",
  78874. /* 198 */ "expr ::= expr OR expr",
  78875. /* 199 */ "expr ::= expr LT|GT|GE|LE expr",
  78876. /* 200 */ "expr ::= expr EQ|NE expr",
  78877. /* 201 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  78878. /* 202 */ "expr ::= expr PLUS|MINUS expr",
  78879. /* 203 */ "expr ::= expr STAR|SLASH|REM expr",
  78880. /* 204 */ "expr ::= expr CONCAT expr",
  78881. /* 205 */ "likeop ::= LIKE_KW",
  78882. /* 206 */ "likeop ::= NOT LIKE_KW",
  78883. /* 207 */ "likeop ::= MATCH",
  78884. /* 208 */ "likeop ::= NOT MATCH",
  78885. /* 209 */ "escape ::= ESCAPE expr",
  78886. /* 210 */ "escape ::=",
  78887. /* 211 */ "expr ::= expr likeop expr escape",
  78888. /* 212 */ "expr ::= expr ISNULL|NOTNULL",
  78889. /* 213 */ "expr ::= expr IS NULL",
  78890. /* 214 */ "expr ::= expr NOT NULL",
  78891. /* 215 */ "expr ::= expr IS NOT NULL",
  78892. /* 216 */ "expr ::= NOT expr",
  78893. /* 217 */ "expr ::= BITNOT expr",
  78894. /* 218 */ "expr ::= MINUS expr",
  78895. /* 219 */ "expr ::= PLUS expr",
  78896. /* 220 */ "between_op ::= BETWEEN",
  78897. /* 221 */ "between_op ::= NOT BETWEEN",
  78898. /* 222 */ "expr ::= expr between_op expr AND expr",
  78899. /* 223 */ "in_op ::= IN",
  78900. /* 224 */ "in_op ::= NOT IN",
  78901. /* 225 */ "expr ::= expr in_op LP exprlist RP",
  78902. /* 226 */ "expr ::= LP select RP",
  78903. /* 227 */ "expr ::= expr in_op LP select RP",
  78904. /* 228 */ "expr ::= expr in_op nm dbnm",
  78905. /* 229 */ "expr ::= EXISTS LP select RP",
  78906. /* 230 */ "expr ::= CASE case_operand case_exprlist case_else END",
  78907. /* 231 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  78908. /* 232 */ "case_exprlist ::= WHEN expr THEN expr",
  78909. /* 233 */ "case_else ::= ELSE expr",
  78910. /* 234 */ "case_else ::=",
  78911. /* 235 */ "case_operand ::= expr",
  78912. /* 236 */ "case_operand ::=",
  78913. /* 237 */ "exprlist ::= nexprlist",
  78914. /* 238 */ "exprlist ::=",
  78915. /* 239 */ "nexprlist ::= nexprlist COMMA expr",
  78916. /* 240 */ "nexprlist ::= expr",
  78917. /* 241 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
  78918. /* 242 */ "uniqueflag ::= UNIQUE",
  78919. /* 243 */ "uniqueflag ::=",
  78920. /* 244 */ "idxlist_opt ::=",
  78921. /* 245 */ "idxlist_opt ::= LP idxlist RP",
  78922. /* 246 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  78923. /* 247 */ "idxlist ::= nm collate sortorder",
  78924. /* 248 */ "collate ::=",
  78925. /* 249 */ "collate ::= COLLATE ids",
  78926. /* 250 */ "cmd ::= DROP INDEX ifexists fullname",
  78927. /* 251 */ "cmd ::= VACUUM",
  78928. /* 252 */ "cmd ::= VACUUM nm",
  78929. /* 253 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  78930. /* 254 */ "cmd ::= PRAGMA nm dbnm EQ ON",
  78931. /* 255 */ "cmd ::= PRAGMA nm dbnm EQ DELETE",
  78932. /* 256 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  78933. /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  78934. /* 258 */ "cmd ::= PRAGMA nm dbnm",
  78935. /* 259 */ "nmnum ::= plus_num",
  78936. /* 260 */ "nmnum ::= nm",
  78937. /* 261 */ "plus_num ::= plus_opt number",
  78938. /* 262 */ "minus_num ::= MINUS number",
  78939. /* 263 */ "number ::= INTEGER|FLOAT",
  78940. /* 264 */ "plus_opt ::= PLUS",
  78941. /* 265 */ "plus_opt ::=",
  78942. /* 266 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
  78943. /* 267 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  78944. /* 268 */ "trigger_time ::= BEFORE",
  78945. /* 269 */ "trigger_time ::= AFTER",
  78946. /* 270 */ "trigger_time ::= INSTEAD OF",
  78947. /* 271 */ "trigger_time ::=",
  78948. /* 272 */ "trigger_event ::= DELETE|INSERT",
  78949. /* 273 */ "trigger_event ::= UPDATE",
  78950. /* 274 */ "trigger_event ::= UPDATE OF inscollist",
  78951. /* 275 */ "foreach_clause ::=",
  78952. /* 276 */ "foreach_clause ::= FOR EACH ROW",
  78953. /* 277 */ "when_clause ::=",
  78954. /* 278 */ "when_clause ::= WHEN expr",
  78955. /* 279 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  78956. /* 280 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  78957. /* 281 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
  78958. /* 282 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
  78959. /* 283 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
  78960. /* 284 */ "trigger_cmd ::= DELETE FROM nm where_opt",
  78961. /* 285 */ "trigger_cmd ::= select",
  78962. /* 286 */ "expr ::= RAISE LP IGNORE RP",
  78963. /* 287 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  78964. /* 288 */ "raisetype ::= ROLLBACK",
  78965. /* 289 */ "raisetype ::= ABORT",
  78966. /* 290 */ "raisetype ::= FAIL",
  78967. /* 291 */ "cmd ::= DROP TRIGGER ifexists fullname",
  78968. /* 292 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  78969. /* 293 */ "cmd ::= DETACH database_kw_opt expr",
  78970. /* 294 */ "key_opt ::=",
  78971. /* 295 */ "key_opt ::= KEY expr",
  78972. /* 296 */ "database_kw_opt ::= DATABASE",
  78973. /* 297 */ "database_kw_opt ::=",
  78974. /* 298 */ "cmd ::= REINDEX",
  78975. /* 299 */ "cmd ::= REINDEX nm dbnm",
  78976. /* 300 */ "cmd ::= ANALYZE",
  78977. /* 301 */ "cmd ::= ANALYZE nm dbnm",
  78978. /* 302 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  78979. /* 303 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  78980. /* 304 */ "add_column_fullname ::= fullname",
  78981. /* 305 */ "kwcolumn_opt ::=",
  78982. /* 306 */ "kwcolumn_opt ::= COLUMNKW",
  78983. /* 307 */ "cmd ::= create_vtab",
  78984. /* 308 */ "cmd ::= create_vtab LP vtabarglist RP",
  78985. /* 309 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
  78986. /* 310 */ "vtabarglist ::= vtabarg",
  78987. /* 311 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  78988. /* 312 */ "vtabarg ::=",
  78989. /* 313 */ "vtabarg ::= vtabarg vtabargtoken",
  78990. /* 314 */ "vtabargtoken ::= ANY",
  78991. /* 315 */ "vtabargtoken ::= lp anylist RP",
  78992. /* 316 */ "lp ::= LP",
  78993. /* 317 */ "anylist ::=",
  78994. /* 318 */ "anylist ::= anylist ANY",
  78995. };
  78996. #endif /* NDEBUG */
  78997. #if YYSTACKDEPTH<=0
  78998. /*
  78999. ** Try to increase the size of the parser stack.
  79000. */
  79001. static void yyGrowStack(yyParser *p){
  79002. int newSize;
  79003. yyStackEntry *pNew;
  79004. newSize = p->yystksz*2 + 100;
  79005. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  79006. if( pNew ){
  79007. p->yystack = pNew;
  79008. p->yystksz = newSize;
  79009. #ifndef NDEBUG
  79010. if( yyTraceFILE ){
  79011. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  79012. yyTracePrompt, p->yystksz);
  79013. }
  79014. #endif
  79015. }
  79016. }
  79017. #endif
  79018. /*
  79019. ** This function allocates a new parser.
  79020. ** The only argument is a pointer to a function which works like
  79021. ** malloc.
  79022. **
  79023. ** Inputs:
  79024. ** A pointer to the function used to allocate memory.
  79025. **
  79026. ** Outputs:
  79027. ** A pointer to a parser. This pointer is used in subsequent calls
  79028. ** to sqlite3Parser and sqlite3ParserFree.
  79029. */
  79030. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  79031. yyParser *pParser;
  79032. pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  79033. if( pParser ){
  79034. pParser->yyidx = -1;
  79035. #ifdef YYTRACKMAXSTACKDEPTH
  79036. pParser->yyidxMax = 0;
  79037. #endif
  79038. #if YYSTACKDEPTH<=0
  79039. pParser->yystack = NULL;
  79040. pParser->yystksz = 0;
  79041. yyGrowStack(pParser);
  79042. #endif
  79043. }
  79044. return pParser;
  79045. }
  79046. /* The following function deletes the value associated with a
  79047. ** symbol. The symbol can be either a terminal or nonterminal.
  79048. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  79049. ** the value.
  79050. */
  79051. static void yy_destructor(
  79052. yyParser *yypParser, /* The parser */
  79053. YYCODETYPE yymajor, /* Type code for object to destroy */
  79054. YYMINORTYPE *yypminor /* The object to be destroyed */
  79055. ){
  79056. sqlite3ParserARG_FETCH;
  79057. switch( yymajor ){
  79058. /* Here is inserted the actions which take place when a
  79059. ** terminal or non-terminal is destroyed. This can happen
  79060. ** when the symbol is popped from the stack during a
  79061. ** reduce or during error processing or when a parser is
  79062. ** being destroyed before it is finished parsing.
  79063. **
  79064. ** Note: during a reduce, the only symbols destroyed are those
  79065. ** which appear on the RHS of the rule, but which are not used
  79066. ** inside the C code.
  79067. */
  79068. case 159: /* select */
  79069. case 193: /* oneselect */
  79070. {
  79071. sqlite3SelectDelete(pParse->db, (yypminor->yy159));
  79072. }
  79073. break;
  79074. case 173: /* term */
  79075. case 174: /* expr */
  79076. case 198: /* where_opt */
  79077. case 200: /* having_opt */
  79078. case 209: /* on_opt */
  79079. case 214: /* sortitem */
  79080. case 222: /* escape */
  79081. case 225: /* case_operand */
  79082. case 227: /* case_else */
  79083. case 238: /* when_clause */
  79084. case 241: /* key_opt */
  79085. {
  79086. sqlite3ExprDelete(pParse->db, (yypminor->yy122));
  79087. }
  79088. break;
  79089. case 178: /* idxlist_opt */
  79090. case 186: /* idxlist */
  79091. case 196: /* selcollist */
  79092. case 199: /* groupby_opt */
  79093. case 201: /* orderby_opt */
  79094. case 203: /* sclp */
  79095. case 213: /* sortlist */
  79096. case 215: /* nexprlist */
  79097. case 216: /* setlist */
  79098. case 219: /* itemlist */
  79099. case 220: /* exprlist */
  79100. case 226: /* case_exprlist */
  79101. {
  79102. sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
  79103. }
  79104. break;
  79105. case 192: /* fullname */
  79106. case 197: /* from */
  79107. case 205: /* seltablist */
  79108. case 206: /* stl_prefix */
  79109. {
  79110. sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
  79111. }
  79112. break;
  79113. case 210: /* using_opt */
  79114. case 212: /* inscollist */
  79115. case 218: /* inscollist_opt */
  79116. {
  79117. sqlite3IdListDelete(pParse->db, (yypminor->yy180));
  79118. }
  79119. break;
  79120. case 234: /* trigger_cmd_list */
  79121. case 239: /* trigger_cmd */
  79122. {
  79123. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
  79124. }
  79125. break;
  79126. case 236: /* trigger_event */
  79127. {
  79128. sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
  79129. }
  79130. break;
  79131. default: break; /* If no destructor action specified: do nothing */
  79132. }
  79133. }
  79134. /*
  79135. ** Pop the parser's stack once.
  79136. **
  79137. ** If there is a destructor routine associated with the token which
  79138. ** is popped from the stack, then call it.
  79139. **
  79140. ** Return the major token number for the symbol popped.
  79141. */
  79142. static int yy_pop_parser_stack(yyParser *pParser){
  79143. YYCODETYPE yymajor;
  79144. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  79145. if( pParser->yyidx<0 ) return 0;
  79146. #ifndef NDEBUG
  79147. if( yyTraceFILE && pParser->yyidx>=0 ){
  79148. fprintf(yyTraceFILE,"%sPopping %s\n",
  79149. yyTracePrompt,
  79150. yyTokenName[yytos->major]);
  79151. }
  79152. #endif
  79153. yymajor = yytos->major;
  79154. yy_destructor(pParser, yymajor, &yytos->minor);
  79155. pParser->yyidx--;
  79156. return yymajor;
  79157. }
  79158. /*
  79159. ** Deallocate and destroy a parser. Destructors are all called for
  79160. ** all stack elements before shutting the parser down.
  79161. **
  79162. ** Inputs:
  79163. ** <ul>
  79164. ** <li> A pointer to the parser. This should be a pointer
  79165. ** obtained from sqlite3ParserAlloc.
  79166. ** <li> A pointer to a function used to reclaim memory obtained
  79167. ** from malloc.
  79168. ** </ul>
  79169. */
  79170. SQLITE_PRIVATE void sqlite3ParserFree(
  79171. void *p, /* The parser to be deleted */
  79172. void (*freeProc)(void*) /* Function used to reclaim memory */
  79173. ){
  79174. yyParser *pParser = (yyParser*)p;
  79175. if( pParser==0 ) return;
  79176. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  79177. #if YYSTACKDEPTH<=0
  79178. free(pParser->yystack);
  79179. #endif
  79180. (*freeProc)((void*)pParser);
  79181. }
  79182. /*
  79183. ** Return the peak depth of the stack for a parser.
  79184. */
  79185. #ifdef YYTRACKMAXSTACKDEPTH
  79186. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  79187. yyParser *pParser = (yyParser*)p;
  79188. return pParser->yyidxMax;
  79189. }
  79190. #endif
  79191. /*
  79192. ** Find the appropriate action for a parser given the terminal
  79193. ** look-ahead token iLookAhead.
  79194. **
  79195. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  79196. ** independent of the look-ahead. If it is, return the action, otherwise
  79197. ** return YY_NO_ACTION.
  79198. */
  79199. static int yy_find_shift_action(
  79200. yyParser *pParser, /* The parser */
  79201. YYCODETYPE iLookAhead /* The look-ahead token */
  79202. ){
  79203. int i;
  79204. int stateno = pParser->yystack[pParser->yyidx].stateno;
  79205. if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  79206. return yy_default[stateno];
  79207. }
  79208. assert( iLookAhead!=YYNOCODE );
  79209. i += iLookAhead;
  79210. if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
  79211. if( iLookAhead>0 ){
  79212. #ifdef YYFALLBACK
  79213. YYCODETYPE iFallback; /* Fallback token */
  79214. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  79215. && (iFallback = yyFallback[iLookAhead])!=0 ){
  79216. #ifndef NDEBUG
  79217. if( yyTraceFILE ){
  79218. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  79219. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  79220. }
  79221. #endif
  79222. return yy_find_shift_action(pParser, iFallback);
  79223. }
  79224. #endif
  79225. #ifdef YYWILDCARD
  79226. {
  79227. int j = i - iLookAhead + YYWILDCARD;
  79228. if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
  79229. #ifndef NDEBUG
  79230. if( yyTraceFILE ){
  79231. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  79232. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  79233. }
  79234. #endif /* NDEBUG */
  79235. return yy_action[j];
  79236. }
  79237. }
  79238. #endif /* YYWILDCARD */
  79239. }
  79240. return yy_default[stateno];
  79241. }else{
  79242. return yy_action[i];
  79243. }
  79244. }
  79245. /*
  79246. ** Find the appropriate action for a parser given the non-terminal
  79247. ** look-ahead token iLookAhead.
  79248. **
  79249. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  79250. ** independent of the look-ahead. If it is, return the action, otherwise
  79251. ** return YY_NO_ACTION.
  79252. */
  79253. static int yy_find_reduce_action(
  79254. int stateno, /* Current state number */
  79255. YYCODETYPE iLookAhead /* The look-ahead token */
  79256. ){
  79257. int i;
  79258. #ifdef YYERRORSYMBOL
  79259. if( stateno>YY_REDUCE_MAX ){
  79260. return yy_default[stateno];
  79261. }
  79262. #else
  79263. assert( stateno<=YY_REDUCE_MAX );
  79264. #endif
  79265. i = yy_reduce_ofst[stateno];
  79266. assert( i!=YY_REDUCE_USE_DFLT );
  79267. assert( iLookAhead!=YYNOCODE );
  79268. i += iLookAhead;
  79269. #ifdef YYERRORSYMBOL
  79270. if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
  79271. return yy_default[stateno];
  79272. }
  79273. #else
  79274. assert( i>=0 && i<YY_SZ_ACTTAB );
  79275. assert( yy_lookahead[i]==iLookAhead );
  79276. #endif
  79277. return yy_action[i];
  79278. }
  79279. /*
  79280. ** The following routine is called if the stack overflows.
  79281. */
  79282. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  79283. sqlite3ParserARG_FETCH;
  79284. yypParser->yyidx--;
  79285. #ifndef NDEBUG
  79286. if( yyTraceFILE ){
  79287. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  79288. }
  79289. #endif
  79290. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  79291. /* Here code is inserted which will execute if the parser
  79292. ** stack every overflows */
  79293. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  79294. sqlite3ErrorMsg(pParse, "parser stack overflow");
  79295. pParse->parseError = 1;
  79296. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  79297. }
  79298. /*
  79299. ** Perform a shift action.
  79300. */
  79301. static void yy_shift(
  79302. yyParser *yypParser, /* The parser to be shifted */
  79303. int yyNewState, /* The new state to shift in */
  79304. int yyMajor, /* The major token to shift in */
  79305. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  79306. ){
  79307. yyStackEntry *yytos;
  79308. yypParser->yyidx++;
  79309. #ifdef YYTRACKMAXSTACKDEPTH
  79310. if( yypParser->yyidx>yypParser->yyidxMax ){
  79311. yypParser->yyidxMax = yypParser->yyidx;
  79312. }
  79313. #endif
  79314. #if YYSTACKDEPTH>0
  79315. if( yypParser->yyidx>=YYSTACKDEPTH ){
  79316. yyStackOverflow(yypParser, yypMinor);
  79317. return;
  79318. }
  79319. #else
  79320. if( yypParser->yyidx>=yypParser->yystksz ){
  79321. yyGrowStack(yypParser);
  79322. if( yypParser->yyidx>=yypParser->yystksz ){
  79323. yyStackOverflow(yypParser, yypMinor);
  79324. return;
  79325. }
  79326. }
  79327. #endif
  79328. yytos = &yypParser->yystack[yypParser->yyidx];
  79329. yytos->stateno = (YYACTIONTYPE)yyNewState;
  79330. yytos->major = (YYCODETYPE)yyMajor;
  79331. yytos->minor = *yypMinor;
  79332. #ifndef NDEBUG
  79333. if( yyTraceFILE && yypParser->yyidx>0 ){
  79334. int i;
  79335. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  79336. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  79337. for(i=1; i<=yypParser->yyidx; i++)
  79338. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  79339. fprintf(yyTraceFILE,"\n");
  79340. }
  79341. #endif
  79342. }
  79343. /* The following table contains information about every rule that
  79344. ** is used during the reduce.
  79345. */
  79346. static const struct {
  79347. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  79348. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  79349. } yyRuleInfo[] = {
  79350. { 142, 1 },
  79351. { 143, 2 },
  79352. { 143, 1 },
  79353. { 144, 1 },
  79354. { 144, 3 },
  79355. { 145, 0 },
  79356. { 145, 1 },
  79357. { 145, 3 },
  79358. { 146, 1 },
  79359. { 147, 3 },
  79360. { 149, 0 },
  79361. { 149, 1 },
  79362. { 149, 2 },
  79363. { 148, 0 },
  79364. { 148, 1 },
  79365. { 148, 1 },
  79366. { 148, 1 },
  79367. { 147, 2 },
  79368. { 147, 2 },
  79369. { 147, 2 },
  79370. { 151, 1 },
  79371. { 151, 0 },
  79372. { 147, 2 },
  79373. { 147, 3 },
  79374. { 147, 5 },
  79375. { 147, 2 },
  79376. { 152, 6 },
  79377. { 155, 0 },
  79378. { 155, 3 },
  79379. { 154, 1 },
  79380. { 154, 0 },
  79381. { 153, 4 },
  79382. { 153, 2 },
  79383. { 157, 3 },
  79384. { 157, 1 },
  79385. { 160, 3 },
  79386. { 161, 1 },
  79387. { 164, 1 },
  79388. { 165, 1 },
  79389. { 150, 1 },
  79390. { 150, 1 },
  79391. { 150, 1 },
  79392. { 162, 0 },
  79393. { 162, 1 },
  79394. { 166, 1 },
  79395. { 166, 4 },
  79396. { 166, 6 },
  79397. { 167, 1 },
  79398. { 167, 2 },
  79399. { 168, 1 },
  79400. { 168, 1 },
  79401. { 163, 2 },
  79402. { 163, 0 },
  79403. { 171, 3 },
  79404. { 171, 1 },
  79405. { 172, 2 },
  79406. { 172, 4 },
  79407. { 172, 3 },
  79408. { 172, 3 },
  79409. { 172, 2 },
  79410. { 172, 2 },
  79411. { 172, 3 },
  79412. { 172, 5 },
  79413. { 172, 2 },
  79414. { 172, 4 },
  79415. { 172, 4 },
  79416. { 172, 1 },
  79417. { 172, 2 },
  79418. { 177, 0 },
  79419. { 177, 1 },
  79420. { 179, 0 },
  79421. { 179, 2 },
  79422. { 181, 2 },
  79423. { 181, 3 },
  79424. { 181, 3 },
  79425. { 181, 3 },
  79426. { 182, 2 },
  79427. { 182, 2 },
  79428. { 182, 1 },
  79429. { 182, 1 },
  79430. { 180, 3 },
  79431. { 180, 2 },
  79432. { 183, 0 },
  79433. { 183, 2 },
  79434. { 183, 2 },
  79435. { 158, 0 },
  79436. { 158, 2 },
  79437. { 184, 3 },
  79438. { 184, 2 },
  79439. { 184, 1 },
  79440. { 185, 2 },
  79441. { 185, 7 },
  79442. { 185, 5 },
  79443. { 185, 5 },
  79444. { 185, 10 },
  79445. { 187, 0 },
  79446. { 187, 1 },
  79447. { 175, 0 },
  79448. { 175, 3 },
  79449. { 188, 0 },
  79450. { 188, 2 },
  79451. { 189, 1 },
  79452. { 189, 1 },
  79453. { 189, 1 },
  79454. { 147, 4 },
  79455. { 191, 2 },
  79456. { 191, 0 },
  79457. { 147, 8 },
  79458. { 147, 4 },
  79459. { 147, 1 },
  79460. { 159, 1 },
  79461. { 159, 3 },
  79462. { 194, 1 },
  79463. { 194, 2 },
  79464. { 194, 1 },
  79465. { 193, 9 },
  79466. { 195, 1 },
  79467. { 195, 1 },
  79468. { 195, 0 },
  79469. { 203, 2 },
  79470. { 203, 0 },
  79471. { 196, 3 },
  79472. { 196, 2 },
  79473. { 196, 4 },
  79474. { 204, 2 },
  79475. { 204, 1 },
  79476. { 204, 0 },
  79477. { 197, 0 },
  79478. { 197, 2 },
  79479. { 206, 2 },
  79480. { 206, 0 },
  79481. { 205, 7 },
  79482. { 205, 7 },
  79483. { 205, 7 },
  79484. { 156, 0 },
  79485. { 156, 2 },
  79486. { 192, 2 },
  79487. { 207, 1 },
  79488. { 207, 2 },
  79489. { 207, 3 },
  79490. { 207, 4 },
  79491. { 209, 2 },
  79492. { 209, 0 },
  79493. { 208, 0 },
  79494. { 208, 3 },
  79495. { 208, 2 },
  79496. { 210, 4 },
  79497. { 210, 0 },
  79498. { 201, 0 },
  79499. { 201, 3 },
  79500. { 213, 4 },
  79501. { 213, 2 },
  79502. { 214, 1 },
  79503. { 176, 1 },
  79504. { 176, 1 },
  79505. { 176, 0 },
  79506. { 199, 0 },
  79507. { 199, 3 },
  79508. { 200, 0 },
  79509. { 200, 2 },
  79510. { 202, 0 },
  79511. { 202, 2 },
  79512. { 202, 4 },
  79513. { 202, 4 },
  79514. { 147, 5 },
  79515. { 198, 0 },
  79516. { 198, 2 },
  79517. { 147, 7 },
  79518. { 216, 5 },
  79519. { 216, 3 },
  79520. { 147, 8 },
  79521. { 147, 5 },
  79522. { 147, 6 },
  79523. { 217, 2 },
  79524. { 217, 1 },
  79525. { 219, 3 },
  79526. { 219, 1 },
  79527. { 218, 0 },
  79528. { 218, 3 },
  79529. { 212, 3 },
  79530. { 212, 1 },
  79531. { 174, 1 },
  79532. { 174, 3 },
  79533. { 173, 1 },
  79534. { 174, 1 },
  79535. { 174, 1 },
  79536. { 174, 3 },
  79537. { 174, 5 },
  79538. { 173, 1 },
  79539. { 173, 1 },
  79540. { 174, 1 },
  79541. { 174, 1 },
  79542. { 174, 3 },
  79543. { 174, 6 },
  79544. { 174, 5 },
  79545. { 174, 4 },
  79546. { 173, 1 },
  79547. { 174, 3 },
  79548. { 174, 3 },
  79549. { 174, 3 },
  79550. { 174, 3 },
  79551. { 174, 3 },
  79552. { 174, 3 },
  79553. { 174, 3 },
  79554. { 174, 3 },
  79555. { 221, 1 },
  79556. { 221, 2 },
  79557. { 221, 1 },
  79558. { 221, 2 },
  79559. { 222, 2 },
  79560. { 222, 0 },
  79561. { 174, 4 },
  79562. { 174, 2 },
  79563. { 174, 3 },
  79564. { 174, 3 },
  79565. { 174, 4 },
  79566. { 174, 2 },
  79567. { 174, 2 },
  79568. { 174, 2 },
  79569. { 174, 2 },
  79570. { 223, 1 },
  79571. { 223, 2 },
  79572. { 174, 5 },
  79573. { 224, 1 },
  79574. { 224, 2 },
  79575. { 174, 5 },
  79576. { 174, 3 },
  79577. { 174, 5 },
  79578. { 174, 4 },
  79579. { 174, 4 },
  79580. { 174, 5 },
  79581. { 226, 5 },
  79582. { 226, 4 },
  79583. { 227, 2 },
  79584. { 227, 0 },
  79585. { 225, 1 },
  79586. { 225, 0 },
  79587. { 220, 1 },
  79588. { 220, 0 },
  79589. { 215, 3 },
  79590. { 215, 1 },
  79591. { 147, 11 },
  79592. { 228, 1 },
  79593. { 228, 0 },
  79594. { 178, 0 },
  79595. { 178, 3 },
  79596. { 186, 5 },
  79597. { 186, 3 },
  79598. { 229, 0 },
  79599. { 229, 2 },
  79600. { 147, 4 },
  79601. { 147, 1 },
  79602. { 147, 2 },
  79603. { 147, 5 },
  79604. { 147, 5 },
  79605. { 147, 5 },
  79606. { 147, 5 },
  79607. { 147, 6 },
  79608. { 147, 3 },
  79609. { 230, 1 },
  79610. { 230, 1 },
  79611. { 169, 2 },
  79612. { 170, 2 },
  79613. { 232, 1 },
  79614. { 231, 1 },
  79615. { 231, 0 },
  79616. { 147, 5 },
  79617. { 233, 11 },
  79618. { 235, 1 },
  79619. { 235, 1 },
  79620. { 235, 2 },
  79621. { 235, 0 },
  79622. { 236, 1 },
  79623. { 236, 1 },
  79624. { 236, 3 },
  79625. { 237, 0 },
  79626. { 237, 3 },
  79627. { 238, 0 },
  79628. { 238, 2 },
  79629. { 234, 3 },
  79630. { 234, 2 },
  79631. { 239, 6 },
  79632. { 239, 8 },
  79633. { 239, 5 },
  79634. { 239, 4 },
  79635. { 239, 1 },
  79636. { 174, 4 },
  79637. { 174, 6 },
  79638. { 190, 1 },
  79639. { 190, 1 },
  79640. { 190, 1 },
  79641. { 147, 4 },
  79642. { 147, 6 },
  79643. { 147, 3 },
  79644. { 241, 0 },
  79645. { 241, 2 },
  79646. { 240, 1 },
  79647. { 240, 0 },
  79648. { 147, 1 },
  79649. { 147, 3 },
  79650. { 147, 1 },
  79651. { 147, 3 },
  79652. { 147, 6 },
  79653. { 147, 6 },
  79654. { 242, 1 },
  79655. { 243, 0 },
  79656. { 243, 1 },
  79657. { 147, 1 },
  79658. { 147, 4 },
  79659. { 244, 7 },
  79660. { 245, 1 },
  79661. { 245, 3 },
  79662. { 246, 0 },
  79663. { 246, 2 },
  79664. { 247, 1 },
  79665. { 247, 3 },
  79666. { 248, 1 },
  79667. { 249, 0 },
  79668. { 249, 2 },
  79669. };
  79670. static void yy_accept(yyParser*); /* Forward Declaration */
  79671. /*
  79672. ** Perform a reduce action and the shift that must immediately
  79673. ** follow the reduce.
  79674. */
  79675. static void yy_reduce(
  79676. yyParser *yypParser, /* The parser */
  79677. int yyruleno /* Number of the rule by which to reduce */
  79678. ){
  79679. int yygoto; /* The next state */
  79680. int yyact; /* The next action */
  79681. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  79682. yyStackEntry *yymsp; /* The top of the parser's stack */
  79683. int yysize; /* Amount to pop the stack */
  79684. sqlite3ParserARG_FETCH;
  79685. yymsp = &yypParser->yystack[yypParser->yyidx];
  79686. #ifndef NDEBUG
  79687. if( yyTraceFILE && yyruleno>=0
  79688. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  79689. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  79690. yyRuleName[yyruleno]);
  79691. }
  79692. #endif /* NDEBUG */
  79693. /* Silence complaints from purify about yygotominor being uninitialized
  79694. ** in some cases when it is copied into the stack after the following
  79695. ** switch. yygotominor is uninitialized when a rule reduces that does
  79696. ** not set the value of its left-hand side nonterminal. Leaving the
  79697. ** value of the nonterminal uninitialized is utterly harmless as long
  79698. ** as the value is never used. So really the only thing this code
  79699. ** accomplishes is to quieten purify.
  79700. **
  79701. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  79702. ** without this code, their parser segfaults. I'm not sure what there
  79703. ** parser is doing to make this happen. This is the second bug report
  79704. ** from wireshark this week. Clearly they are stressing Lemon in ways
  79705. ** that it has not been previously stressed... (SQLite ticket #2172)
  79706. */
  79707. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  79708. yygotominor = yyzerominor;
  79709. switch( yyruleno ){
  79710. /* Beginning here are the reduction cases. A typical example
  79711. ** follows:
  79712. ** case 0:
  79713. ** #line <lineno> <grammarfile>
  79714. ** { ... } // User supplied code
  79715. ** #line <lineno> <thisfile>
  79716. ** break;
  79717. */
  79718. case 0: /* input ::= cmdlist */
  79719. case 1: /* cmdlist ::= cmdlist ecmd */
  79720. case 2: /* cmdlist ::= ecmd */
  79721. case 3: /* ecmd ::= SEMI */
  79722. case 4: /* ecmd ::= explain cmdx SEMI */
  79723. case 10: /* trans_opt ::= */
  79724. case 11: /* trans_opt ::= TRANSACTION */
  79725. case 12: /* trans_opt ::= TRANSACTION nm */
  79726. case 20: /* savepoint_opt ::= SAVEPOINT */
  79727. case 21: /* savepoint_opt ::= */
  79728. case 25: /* cmd ::= create_table create_table_args */
  79729. case 33: /* columnlist ::= columnlist COMMA column */
  79730. case 34: /* columnlist ::= column */
  79731. case 42: /* type ::= */
  79732. case 49: /* signed ::= plus_num */
  79733. case 50: /* signed ::= minus_num */
  79734. case 51: /* carglist ::= carglist carg */
  79735. case 52: /* carglist ::= */
  79736. case 53: /* carg ::= CONSTRAINT nm ccons */
  79737. case 54: /* carg ::= ccons */
  79738. case 60: /* ccons ::= NULL onconf */
  79739. case 87: /* conslist ::= conslist COMMA tcons */
  79740. case 88: /* conslist ::= conslist tcons */
  79741. case 89: /* conslist ::= tcons */
  79742. case 90: /* tcons ::= CONSTRAINT nm */
  79743. case 264: /* plus_opt ::= PLUS */
  79744. case 265: /* plus_opt ::= */
  79745. case 275: /* foreach_clause ::= */
  79746. case 276: /* foreach_clause ::= FOR EACH ROW */
  79747. case 296: /* database_kw_opt ::= DATABASE */
  79748. case 297: /* database_kw_opt ::= */
  79749. case 305: /* kwcolumn_opt ::= */
  79750. case 306: /* kwcolumn_opt ::= COLUMNKW */
  79751. case 310: /* vtabarglist ::= vtabarg */
  79752. case 311: /* vtabarglist ::= vtabarglist COMMA vtabarg */
  79753. case 313: /* vtabarg ::= vtabarg vtabargtoken */
  79754. case 317: /* anylist ::= */
  79755. {
  79756. }
  79757. break;
  79758. case 5: /* explain ::= */
  79759. { sqlite3BeginParse(pParse, 0); }
  79760. break;
  79761. case 6: /* explain ::= EXPLAIN */
  79762. { sqlite3BeginParse(pParse, 1); }
  79763. break;
  79764. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  79765. { sqlite3BeginParse(pParse, 2); }
  79766. break;
  79767. case 8: /* cmdx ::= cmd */
  79768. { sqlite3FinishCoding(pParse); }
  79769. break;
  79770. case 9: /* cmd ::= BEGIN transtype trans_opt */
  79771. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
  79772. break;
  79773. case 13: /* transtype ::= */
  79774. {yygotominor.yy392 = TK_DEFERRED;}
  79775. break;
  79776. case 14: /* transtype ::= DEFERRED */
  79777. case 15: /* transtype ::= IMMEDIATE */
  79778. case 16: /* transtype ::= EXCLUSIVE */
  79779. case 112: /* multiselect_op ::= UNION */
  79780. case 114: /* multiselect_op ::= EXCEPT|INTERSECT */
  79781. {yygotominor.yy392 = yymsp[0].major;}
  79782. break;
  79783. case 17: /* cmd ::= COMMIT trans_opt */
  79784. case 18: /* cmd ::= END trans_opt */
  79785. {sqlite3CommitTransaction(pParse);}
  79786. break;
  79787. case 19: /* cmd ::= ROLLBACK trans_opt */
  79788. {sqlite3RollbackTransaction(pParse);}
  79789. break;
  79790. case 22: /* cmd ::= SAVEPOINT nm */
  79791. {
  79792. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  79793. }
  79794. break;
  79795. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  79796. {
  79797. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  79798. }
  79799. break;
  79800. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  79801. {
  79802. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  79803. }
  79804. break;
  79805. case 26: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */
  79806. {
  79807. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
  79808. }
  79809. break;
  79810. case 27: /* ifnotexists ::= */
  79811. case 30: /* temp ::= */
  79812. case 68: /* autoinc ::= */
  79813. case 82: /* init_deferred_pred_opt ::= */
  79814. case 84: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  79815. case 95: /* defer_subclause_opt ::= */
  79816. case 106: /* ifexists ::= */
  79817. case 117: /* distinct ::= ALL */
  79818. case 118: /* distinct ::= */
  79819. case 220: /* between_op ::= BETWEEN */
  79820. case 223: /* in_op ::= IN */
  79821. {yygotominor.yy392 = 0;}
  79822. break;
  79823. case 28: /* ifnotexists ::= IF NOT EXISTS */
  79824. case 29: /* temp ::= TEMP */
  79825. case 69: /* autoinc ::= AUTOINCR */
  79826. case 83: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  79827. case 105: /* ifexists ::= IF EXISTS */
  79828. case 116: /* distinct ::= DISTINCT */
  79829. case 221: /* between_op ::= NOT BETWEEN */
  79830. case 224: /* in_op ::= NOT IN */
  79831. {yygotominor.yy392 = 1;}
  79832. break;
  79833. case 31: /* create_table_args ::= LP columnlist conslist_opt RP */
  79834. {
  79835. sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
  79836. }
  79837. break;
  79838. case 32: /* create_table_args ::= AS select */
  79839. {
  79840. sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
  79841. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  79842. }
  79843. break;
  79844. case 35: /* column ::= columnid type carglist */
  79845. {
  79846. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  79847. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  79848. }
  79849. break;
  79850. case 36: /* columnid ::= nm */
  79851. {
  79852. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  79853. yygotominor.yy0 = yymsp[0].minor.yy0;
  79854. }
  79855. break;
  79856. case 37: /* id ::= ID */
  79857. case 38: /* ids ::= ID|STRING */
  79858. case 39: /* nm ::= ID */
  79859. case 40: /* nm ::= STRING */
  79860. case 41: /* nm ::= JOIN_KW */
  79861. case 44: /* typetoken ::= typename */
  79862. case 47: /* typename ::= ids */
  79863. case 124: /* as ::= AS nm */
  79864. case 125: /* as ::= ids */
  79865. case 135: /* dbnm ::= DOT nm */
  79866. case 144: /* indexed_opt ::= INDEXED BY nm */
  79867. case 249: /* collate ::= COLLATE ids */
  79868. case 259: /* nmnum ::= plus_num */
  79869. case 260: /* nmnum ::= nm */
  79870. case 261: /* plus_num ::= plus_opt number */
  79871. case 262: /* minus_num ::= MINUS number */
  79872. case 263: /* number ::= INTEGER|FLOAT */
  79873. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  79874. break;
  79875. case 43: /* type ::= typetoken */
  79876. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  79877. break;
  79878. case 45: /* typetoken ::= typename LP signed RP */
  79879. {
  79880. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  79881. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  79882. }
  79883. break;
  79884. case 46: /* typetoken ::= typename LP signed COMMA signed RP */
  79885. {
  79886. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  79887. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  79888. }
  79889. break;
  79890. case 48: /* typename ::= typename ids */
  79891. {yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  79892. break;
  79893. case 55: /* ccons ::= DEFAULT term */
  79894. case 57: /* ccons ::= DEFAULT PLUS term */
  79895. {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy122);}
  79896. break;
  79897. case 56: /* ccons ::= DEFAULT LP expr RP */
  79898. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy122);}
  79899. break;
  79900. case 58: /* ccons ::= DEFAULT MINUS term */
  79901. {
  79902. Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy122, 0, 0);
  79903. sqlite3ExprSpan(p,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy122->span);
  79904. sqlite3AddDefaultValue(pParse,p);
  79905. }
  79906. break;
  79907. case 59: /* ccons ::= DEFAULT id */
  79908. {
  79909. Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy0);
  79910. sqlite3AddDefaultValue(pParse,p);
  79911. }
  79912. break;
  79913. case 61: /* ccons ::= NOT NULL onconf */
  79914. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
  79915. break;
  79916. case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  79917. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
  79918. break;
  79919. case 63: /* ccons ::= UNIQUE onconf */
  79920. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
  79921. break;
  79922. case 64: /* ccons ::= CHECK LP expr RP */
  79923. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy122);}
  79924. break;
  79925. case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  79926. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
  79927. break;
  79928. case 66: /* ccons ::= defer_subclause */
  79929. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
  79930. break;
  79931. case 67: /* ccons ::= COLLATE ids */
  79932. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  79933. break;
  79934. case 70: /* refargs ::= */
  79935. { yygotominor.yy392 = OE_Restrict * 0x010101; }
  79936. break;
  79937. case 71: /* refargs ::= refargs refarg */
  79938. { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
  79939. break;
  79940. case 72: /* refarg ::= MATCH nm */
  79941. { yygotominor.yy207.value = 0; yygotominor.yy207.mask = 0x000000; }
  79942. break;
  79943. case 73: /* refarg ::= ON DELETE refact */
  79944. { yygotominor.yy207.value = yymsp[0].minor.yy392; yygotominor.yy207.mask = 0x0000ff; }
  79945. break;
  79946. case 74: /* refarg ::= ON UPDATE refact */
  79947. { yygotominor.yy207.value = yymsp[0].minor.yy392<<8; yygotominor.yy207.mask = 0x00ff00; }
  79948. break;
  79949. case 75: /* refarg ::= ON INSERT refact */
  79950. { yygotominor.yy207.value = yymsp[0].minor.yy392<<16; yygotominor.yy207.mask = 0xff0000; }
  79951. break;
  79952. case 76: /* refact ::= SET NULL */
  79953. { yygotominor.yy392 = OE_SetNull; }
  79954. break;
  79955. case 77: /* refact ::= SET DEFAULT */
  79956. { yygotominor.yy392 = OE_SetDflt; }
  79957. break;
  79958. case 78: /* refact ::= CASCADE */
  79959. { yygotominor.yy392 = OE_Cascade; }
  79960. break;
  79961. case 79: /* refact ::= RESTRICT */
  79962. { yygotominor.yy392 = OE_Restrict; }
  79963. break;
  79964. case 80: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  79965. case 81: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  79966. case 96: /* defer_subclause_opt ::= defer_subclause */
  79967. case 98: /* onconf ::= ON CONFLICT resolvetype */
  79968. case 100: /* orconf ::= OR resolvetype */
  79969. case 101: /* resolvetype ::= raisetype */
  79970. case 173: /* insert_cmd ::= INSERT orconf */
  79971. {yygotominor.yy392 = yymsp[0].minor.yy392;}
  79972. break;
  79973. case 85: /* conslist_opt ::= */
  79974. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  79975. break;
  79976. case 86: /* conslist_opt ::= COMMA conslist */
  79977. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  79978. break;
  79979. case 91: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  79980. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
  79981. break;
  79982. case 92: /* tcons ::= UNIQUE LP idxlist RP onconf */
  79983. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
  79984. break;
  79985. case 93: /* tcons ::= CHECK LP expr RP onconf */
  79986. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy122);}
  79987. break;
  79988. case 94: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  79989. {
  79990. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
  79991. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
  79992. }
  79993. break;
  79994. case 97: /* onconf ::= */
  79995. case 99: /* orconf ::= */
  79996. {yygotominor.yy392 = OE_Default;}
  79997. break;
  79998. case 102: /* resolvetype ::= IGNORE */
  79999. {yygotominor.yy392 = OE_Ignore;}
  80000. break;
  80001. case 103: /* resolvetype ::= REPLACE */
  80002. case 174: /* insert_cmd ::= REPLACE */
  80003. {yygotominor.yy392 = OE_Replace;}
  80004. break;
  80005. case 104: /* cmd ::= DROP TABLE ifexists fullname */
  80006. {
  80007. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
  80008. }
  80009. break;
  80010. case 107: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */
  80011. {
  80012. sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
  80013. }
  80014. break;
  80015. case 108: /* cmd ::= DROP VIEW ifexists fullname */
  80016. {
  80017. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
  80018. }
  80019. break;
  80020. case 109: /* cmd ::= select */
  80021. {
  80022. SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  80023. sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
  80024. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  80025. }
  80026. break;
  80027. case 110: /* select ::= oneselect */
  80028. {yygotominor.yy159 = yymsp[0].minor.yy159;}
  80029. break;
  80030. case 111: /* select ::= select multiselect_op oneselect */
  80031. {
  80032. if( yymsp[0].minor.yy159 ){
  80033. yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
  80034. yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
  80035. }else{
  80036. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
  80037. }
  80038. yygotominor.yy159 = yymsp[0].minor.yy159;
  80039. }
  80040. break;
  80041. case 113: /* multiselect_op ::= UNION ALL */
  80042. {yygotominor.yy392 = TK_ALL;}
  80043. break;
  80044. case 115: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  80045. {
  80046. yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
  80047. }
  80048. break;
  80049. case 119: /* sclp ::= selcollist COMMA */
  80050. case 245: /* idxlist_opt ::= LP idxlist RP */
  80051. {yygotominor.yy442 = yymsp[-1].minor.yy442;}
  80052. break;
  80053. case 120: /* sclp ::= */
  80054. case 148: /* orderby_opt ::= */
  80055. case 156: /* groupby_opt ::= */
  80056. case 238: /* exprlist ::= */
  80057. case 244: /* idxlist_opt ::= */
  80058. {yygotominor.yy442 = 0;}
  80059. break;
  80060. case 121: /* selcollist ::= sclp expr as */
  80061. {
  80062. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
  80063. }
  80064. break;
  80065. case 122: /* selcollist ::= sclp STAR */
  80066. {
  80067. Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
  80068. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p, 0);
  80069. }
  80070. break;
  80071. case 123: /* selcollist ::= sclp nm DOT STAR */
  80072. {
  80073. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  80074. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  80075. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  80076. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot, 0);
  80077. }
  80078. break;
  80079. case 126: /* as ::= */
  80080. {yygotominor.yy0.n = 0;}
  80081. break;
  80082. case 127: /* from ::= */
  80083. {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
  80084. break;
  80085. case 128: /* from ::= FROM seltablist */
  80086. {
  80087. yygotominor.yy347 = yymsp[0].minor.yy347;
  80088. sqlite3SrcListShiftJoinType(yygotominor.yy347);
  80089. }
  80090. break;
  80091. case 129: /* stl_prefix ::= seltablist joinop */
  80092. {
  80093. yygotominor.yy347 = yymsp[-1].minor.yy347;
  80094. if( yygotominor.yy347 && yygotominor.yy347->nSrc>0 ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
  80095. }
  80096. break;
  80097. case 130: /* stl_prefix ::= */
  80098. {yygotominor.yy347 = 0;}
  80099. break;
  80100. case 131: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  80101. {
  80102. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  80103. sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
  80104. }
  80105. break;
  80106. case 132: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  80107. {
  80108. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  80109. }
  80110. break;
  80111. case 133: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  80112. {
  80113. if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
  80114. yygotominor.yy347 = yymsp[-4].minor.yy347;
  80115. }else{
  80116. Select *pSubquery;
  80117. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
  80118. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
  80119. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  80120. }
  80121. }
  80122. break;
  80123. case 134: /* dbnm ::= */
  80124. case 143: /* indexed_opt ::= */
  80125. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  80126. break;
  80127. case 136: /* fullname ::= nm dbnm */
  80128. {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  80129. break;
  80130. case 137: /* joinop ::= COMMA|JOIN */
  80131. { yygotominor.yy392 = JT_INNER; }
  80132. break;
  80133. case 138: /* joinop ::= JOIN_KW JOIN */
  80134. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  80135. break;
  80136. case 139: /* joinop ::= JOIN_KW nm JOIN */
  80137. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  80138. break;
  80139. case 140: /* joinop ::= JOIN_KW nm nm JOIN */
  80140. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  80141. break;
  80142. case 141: /* on_opt ::= ON expr */
  80143. case 152: /* sortitem ::= expr */
  80144. case 159: /* having_opt ::= HAVING expr */
  80145. case 166: /* where_opt ::= WHERE expr */
  80146. case 181: /* expr ::= term */
  80147. case 209: /* escape ::= ESCAPE expr */
  80148. case 233: /* case_else ::= ELSE expr */
  80149. case 235: /* case_operand ::= expr */
  80150. {yygotominor.yy122 = yymsp[0].minor.yy122;}
  80151. break;
  80152. case 142: /* on_opt ::= */
  80153. case 158: /* having_opt ::= */
  80154. case 165: /* where_opt ::= */
  80155. case 210: /* escape ::= */
  80156. case 234: /* case_else ::= */
  80157. case 236: /* case_operand ::= */
  80158. {yygotominor.yy122 = 0;}
  80159. break;
  80160. case 145: /* indexed_opt ::= NOT INDEXED */
  80161. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  80162. break;
  80163. case 146: /* using_opt ::= USING LP inscollist RP */
  80164. case 178: /* inscollist_opt ::= LP inscollist RP */
  80165. {yygotominor.yy180 = yymsp[-1].minor.yy180;}
  80166. break;
  80167. case 147: /* using_opt ::= */
  80168. case 177: /* inscollist_opt ::= */
  80169. {yygotominor.yy180 = 0;}
  80170. break;
  80171. case 149: /* orderby_opt ::= ORDER BY sortlist */
  80172. case 157: /* groupby_opt ::= GROUP BY nexprlist */
  80173. case 237: /* exprlist ::= nexprlist */
  80174. {yygotominor.yy442 = yymsp[0].minor.yy442;}
  80175. break;
  80176. case 150: /* sortlist ::= sortlist COMMA sortitem sortorder */
  80177. {
  80178. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy122,0);
  80179. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  80180. }
  80181. break;
  80182. case 151: /* sortlist ::= sortitem sortorder */
  80183. {
  80184. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy122,0);
  80185. if( yygotominor.yy442 && yygotominor.yy442->a ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
  80186. }
  80187. break;
  80188. case 153: /* sortorder ::= ASC */
  80189. case 155: /* sortorder ::= */
  80190. {yygotominor.yy392 = SQLITE_SO_ASC;}
  80191. break;
  80192. case 154: /* sortorder ::= DESC */
  80193. {yygotominor.yy392 = SQLITE_SO_DESC;}
  80194. break;
  80195. case 160: /* limit_opt ::= */
  80196. {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
  80197. break;
  80198. case 161: /* limit_opt ::= LIMIT expr */
  80199. {yygotominor.yy64.pLimit = yymsp[0].minor.yy122; yygotominor.yy64.pOffset = 0;}
  80200. break;
  80201. case 162: /* limit_opt ::= LIMIT expr OFFSET expr */
  80202. {yygotominor.yy64.pLimit = yymsp[-2].minor.yy122; yygotominor.yy64.pOffset = yymsp[0].minor.yy122;}
  80203. break;
  80204. case 163: /* limit_opt ::= LIMIT expr COMMA expr */
  80205. {yygotominor.yy64.pOffset = yymsp[-2].minor.yy122; yygotominor.yy64.pLimit = yymsp[0].minor.yy122;}
  80206. break;
  80207. case 164: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
  80208. {
  80209. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
  80210. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
  80211. }
  80212. break;
  80213. case 167: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
  80214. {
  80215. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
  80216. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
  80217. sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy392);
  80218. }
  80219. break;
  80220. case 168: /* setlist ::= setlist COMMA nm EQ expr */
  80221. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442,yymsp[0].minor.yy122,&yymsp[-2].minor.yy0);}
  80222. break;
  80223. case 169: /* setlist ::= nm EQ expr */
  80224. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy122,&yymsp[-2].minor.yy0);}
  80225. break;
  80226. case 170: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
  80227. {sqlite3Insert(pParse, yymsp[-5].minor.yy347, yymsp[-1].minor.yy442, 0, yymsp[-4].minor.yy180, yymsp[-7].minor.yy392);}
  80228. break;
  80229. case 171: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
  80230. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy392);}
  80231. break;
  80232. case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  80233. {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy392);}
  80234. break;
  80235. case 175: /* itemlist ::= itemlist COMMA expr */
  80236. case 239: /* nexprlist ::= nexprlist COMMA expr */
  80237. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy122,0);}
  80238. break;
  80239. case 176: /* itemlist ::= expr */
  80240. case 240: /* nexprlist ::= expr */
  80241. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy122,0);}
  80242. break;
  80243. case 179: /* inscollist ::= inscollist COMMA nm */
  80244. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
  80245. break;
  80246. case 180: /* inscollist ::= nm */
  80247. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  80248. break;
  80249. case 182: /* expr ::= LP expr RP */
  80250. {yygotominor.yy122 = yymsp[-1].minor.yy122; sqlite3ExprSpan(yygotominor.yy122,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
  80251. break;
  80252. case 183: /* term ::= NULL */
  80253. case 188: /* term ::= INTEGER|FLOAT|BLOB */
  80254. case 189: /* term ::= STRING */
  80255. {yygotominor.yy122 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
  80256. break;
  80257. case 184: /* expr ::= ID */
  80258. case 185: /* expr ::= JOIN_KW */
  80259. {yygotominor.yy122 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
  80260. break;
  80261. case 186: /* expr ::= nm DOT nm */
  80262. {
  80263. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  80264. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  80265. yygotominor.yy122 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  80266. }
  80267. break;
  80268. case 187: /* expr ::= nm DOT nm DOT nm */
  80269. {
  80270. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  80271. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  80272. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  80273. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  80274. yygotominor.yy122 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  80275. }
  80276. break;
  80277. case 190: /* expr ::= REGISTER */
  80278. {yygotominor.yy122 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
  80279. break;
  80280. case 191: /* expr ::= VARIABLE */
  80281. {
  80282. Token *pToken = &yymsp[0].minor.yy0;
  80283. Expr *pExpr = yygotominor.yy122 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
  80284. sqlite3ExprAssignVarNumber(pParse, pExpr);
  80285. }
  80286. break;
  80287. case 192: /* expr ::= expr COLLATE ids */
  80288. {
  80289. yygotominor.yy122 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy122, &yymsp[0].minor.yy0);
  80290. }
  80291. break;
  80292. case 193: /* expr ::= CAST LP expr AS typetoken RP */
  80293. {
  80294. yygotominor.yy122 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy122, 0, &yymsp[-1].minor.yy0);
  80295. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  80296. }
  80297. break;
  80298. case 194: /* expr ::= ID LP distinct exprlist RP */
  80299. {
  80300. if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>SQLITE_MAX_FUNCTION_ARG ){
  80301. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  80302. }
  80303. yygotominor.yy122 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
  80304. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  80305. if( yymsp[-2].minor.yy392 && yygotominor.yy122 ){
  80306. yygotominor.yy122->flags |= EP_Distinct;
  80307. }
  80308. }
  80309. break;
  80310. case 195: /* expr ::= ID LP STAR RP */
  80311. {
  80312. yygotominor.yy122 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  80313. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  80314. }
  80315. break;
  80316. case 196: /* term ::= CTIME_KW */
  80317. {
  80318. /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  80319. ** treated as functions that return constants */
  80320. yygotominor.yy122 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  80321. if( yygotominor.yy122 ){
  80322. yygotominor.yy122->op = TK_CONST_FUNC;
  80323. yygotominor.yy122->span = yymsp[0].minor.yy0;
  80324. }
  80325. }
  80326. break;
  80327. case 197: /* expr ::= expr AND expr */
  80328. case 198: /* expr ::= expr OR expr */
  80329. case 199: /* expr ::= expr LT|GT|GE|LE expr */
  80330. case 200: /* expr ::= expr EQ|NE expr */
  80331. case 201: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  80332. case 202: /* expr ::= expr PLUS|MINUS expr */
  80333. case 203: /* expr ::= expr STAR|SLASH|REM expr */
  80334. case 204: /* expr ::= expr CONCAT expr */
  80335. {yygotominor.yy122 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy122,yymsp[0].minor.yy122,0);}
  80336. break;
  80337. case 205: /* likeop ::= LIKE_KW */
  80338. case 207: /* likeop ::= MATCH */
  80339. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 0;}
  80340. break;
  80341. case 206: /* likeop ::= NOT LIKE_KW */
  80342. case 208: /* likeop ::= NOT MATCH */
  80343. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 1;}
  80344. break;
  80345. case 211: /* expr ::= expr likeop expr escape */
  80346. {
  80347. ExprList *pList;
  80348. pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy122, 0);
  80349. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy122, 0);
  80350. if( yymsp[0].minor.yy122 ){
  80351. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy122, 0);
  80352. }
  80353. yygotominor.yy122 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy318.eOperator);
  80354. if( yymsp[-2].minor.yy318.not ) yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy122, 0, 0);
  80355. sqlite3ExprSpan(yygotominor.yy122, &yymsp[-3].minor.yy122->span, &yymsp[-1].minor.yy122->span);
  80356. if( yygotominor.yy122 ) yygotominor.yy122->flags |= EP_InfixFunc;
  80357. }
  80358. break;
  80359. case 212: /* expr ::= expr ISNULL|NOTNULL */
  80360. {
  80361. yygotominor.yy122 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy122, 0, 0);
  80362. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-1].minor.yy122->span,&yymsp[0].minor.yy0);
  80363. }
  80364. break;
  80365. case 213: /* expr ::= expr IS NULL */
  80366. {
  80367. yygotominor.yy122 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy122, 0, 0);
  80368. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-2].minor.yy122->span,&yymsp[0].minor.yy0);
  80369. }
  80370. break;
  80371. case 214: /* expr ::= expr NOT NULL */
  80372. {
  80373. yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy122, 0, 0);
  80374. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-2].minor.yy122->span,&yymsp[0].minor.yy0);
  80375. }
  80376. break;
  80377. case 215: /* expr ::= expr IS NOT NULL */
  80378. {
  80379. yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy122, 0, 0);
  80380. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-3].minor.yy122->span,&yymsp[0].minor.yy0);
  80381. }
  80382. break;
  80383. case 216: /* expr ::= NOT expr */
  80384. case 217: /* expr ::= BITNOT expr */
  80385. {
  80386. yygotominor.yy122 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy122, 0, 0);
  80387. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy122->span);
  80388. }
  80389. break;
  80390. case 218: /* expr ::= MINUS expr */
  80391. {
  80392. yygotominor.yy122 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy122, 0, 0);
  80393. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy122->span);
  80394. }
  80395. break;
  80396. case 219: /* expr ::= PLUS expr */
  80397. {
  80398. yygotominor.yy122 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy122, 0, 0);
  80399. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy122->span);
  80400. }
  80401. break;
  80402. case 222: /* expr ::= expr between_op expr AND expr */
  80403. {
  80404. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy122, 0);
  80405. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy122, 0);
  80406. yygotominor.yy122 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy122, 0, 0);
  80407. if( yygotominor.yy122 ){
  80408. yygotominor.yy122->pList = pList;
  80409. }else{
  80410. sqlite3ExprListDelete(pParse->db, pList);
  80411. }
  80412. if( yymsp[-3].minor.yy392 ) yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy122, 0, 0);
  80413. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-4].minor.yy122->span,&yymsp[0].minor.yy122->span);
  80414. }
  80415. break;
  80416. case 225: /* expr ::= expr in_op LP exprlist RP */
  80417. {
  80418. yygotominor.yy122 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy122, 0, 0);
  80419. if( yygotominor.yy122 ){
  80420. yygotominor.yy122->pList = yymsp[-1].minor.yy442;
  80421. sqlite3ExprSetHeight(pParse, yygotominor.yy122);
  80422. }else{
  80423. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
  80424. }
  80425. if( yymsp[-3].minor.yy392 ) yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy122, 0, 0);
  80426. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-4].minor.yy122->span,&yymsp[0].minor.yy0);
  80427. }
  80428. break;
  80429. case 226: /* expr ::= LP select RP */
  80430. {
  80431. yygotominor.yy122 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  80432. if( yygotominor.yy122 ){
  80433. yygotominor.yy122->pSelect = yymsp[-1].minor.yy159;
  80434. sqlite3ExprSetHeight(pParse, yygotominor.yy122);
  80435. }else{
  80436. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  80437. }
  80438. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  80439. }
  80440. break;
  80441. case 227: /* expr ::= expr in_op LP select RP */
  80442. {
  80443. yygotominor.yy122 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy122, 0, 0);
  80444. if( yygotominor.yy122 ){
  80445. yygotominor.yy122->pSelect = yymsp[-1].minor.yy159;
  80446. sqlite3ExprSetHeight(pParse, yygotominor.yy122);
  80447. }else{
  80448. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  80449. }
  80450. if( yymsp[-3].minor.yy392 ) yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy122, 0, 0);
  80451. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-4].minor.yy122->span,&yymsp[0].minor.yy0);
  80452. }
  80453. break;
  80454. case 228: /* expr ::= expr in_op nm dbnm */
  80455. {
  80456. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  80457. yygotominor.yy122 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy122, 0, 0);
  80458. if( yygotominor.yy122 ){
  80459. yygotominor.yy122->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  80460. sqlite3ExprSetHeight(pParse, yygotominor.yy122);
  80461. }else{
  80462. sqlite3SrcListDelete(pParse->db, pSrc);
  80463. }
  80464. if( yymsp[-2].minor.yy392 ) yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy122, 0, 0);
  80465. sqlite3ExprSpan(yygotominor.yy122,&yymsp[-3].minor.yy122->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
  80466. }
  80467. break;
  80468. case 229: /* expr ::= EXISTS LP select RP */
  80469. {
  80470. Expr *p = yygotominor.yy122 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  80471. if( p ){
  80472. p->pSelect = yymsp[-1].minor.yy159;
  80473. sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  80474. sqlite3ExprSetHeight(pParse, yygotominor.yy122);
  80475. }else{
  80476. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  80477. }
  80478. }
  80479. break;
  80480. case 230: /* expr ::= CASE case_operand case_exprlist case_else END */
  80481. {
  80482. yygotominor.yy122 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
  80483. if( yygotominor.yy122 ){
  80484. yygotominor.yy122->pList = yymsp[-2].minor.yy442;
  80485. sqlite3ExprSetHeight(pParse, yygotominor.yy122);
  80486. }else{
  80487. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
  80488. }
  80489. sqlite3ExprSpan(yygotominor.yy122, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
  80490. }
  80491. break;
  80492. case 231: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  80493. {
  80494. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy122, 0);
  80495. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy122, 0);
  80496. }
  80497. break;
  80498. case 232: /* case_exprlist ::= WHEN expr THEN expr */
  80499. {
  80500. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy122, 0);
  80501. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy122, 0);
  80502. }
  80503. break;
  80504. case 241: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
  80505. {
  80506. sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
  80507. sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
  80508. &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
  80509. }
  80510. break;
  80511. case 242: /* uniqueflag ::= UNIQUE */
  80512. case 289: /* raisetype ::= ABORT */
  80513. {yygotominor.yy392 = OE_Abort;}
  80514. break;
  80515. case 243: /* uniqueflag ::= */
  80516. {yygotominor.yy392 = OE_None;}
  80517. break;
  80518. case 246: /* idxlist ::= idxlist COMMA nm collate sortorder */
  80519. {
  80520. Expr *p = 0;
  80521. if( yymsp[-1].minor.yy0.n>0 ){
  80522. p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
  80523. sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
  80524. }
  80525. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p, &yymsp[-2].minor.yy0);
  80526. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  80527. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  80528. }
  80529. break;
  80530. case 247: /* idxlist ::= nm collate sortorder */
  80531. {
  80532. Expr *p = 0;
  80533. if( yymsp[-1].minor.yy0.n>0 ){
  80534. p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
  80535. sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
  80536. }
  80537. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy0);
  80538. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  80539. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  80540. }
  80541. break;
  80542. case 248: /* collate ::= */
  80543. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  80544. break;
  80545. case 250: /* cmd ::= DROP INDEX ifexists fullname */
  80546. {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
  80547. break;
  80548. case 251: /* cmd ::= VACUUM */
  80549. case 252: /* cmd ::= VACUUM nm */
  80550. {sqlite3Vacuum(pParse);}
  80551. break;
  80552. case 253: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  80553. case 254: /* cmd ::= PRAGMA nm dbnm EQ ON */
  80554. case 255: /* cmd ::= PRAGMA nm dbnm EQ DELETE */
  80555. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  80556. break;
  80557. case 256: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  80558. {
  80559. sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);
  80560. }
  80561. break;
  80562. case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  80563. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  80564. break;
  80565. case 258: /* cmd ::= PRAGMA nm dbnm */
  80566. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  80567. break;
  80568. case 266: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
  80569. {
  80570. Token all;
  80571. all.z = yymsp[-3].minor.yy0.z;
  80572. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  80573. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
  80574. }
  80575. break;
  80576. case 267: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  80577. {
  80578. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
  80579. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  80580. }
  80581. break;
  80582. case 268: /* trigger_time ::= BEFORE */
  80583. case 271: /* trigger_time ::= */
  80584. { yygotominor.yy392 = TK_BEFORE; }
  80585. break;
  80586. case 269: /* trigger_time ::= AFTER */
  80587. { yygotominor.yy392 = TK_AFTER; }
  80588. break;
  80589. case 270: /* trigger_time ::= INSTEAD OF */
  80590. { yygotominor.yy392 = TK_INSTEAD;}
  80591. break;
  80592. case 272: /* trigger_event ::= DELETE|INSERT */
  80593. case 273: /* trigger_event ::= UPDATE */
  80594. {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
  80595. break;
  80596. case 274: /* trigger_event ::= UPDATE OF inscollist */
  80597. {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
  80598. break;
  80599. case 277: /* when_clause ::= */
  80600. case 294: /* key_opt ::= */
  80601. { yygotominor.yy122 = 0; }
  80602. break;
  80603. case 278: /* when_clause ::= WHEN expr */
  80604. case 295: /* key_opt ::= KEY expr */
  80605. { yygotominor.yy122 = yymsp[0].minor.yy122; }
  80606. break;
  80607. case 279: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  80608. {
  80609. /*
  80610. if( yymsp[-2].minor.yy327 ){
  80611. yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
  80612. }else{
  80613. yymsp[-2].minor.yy327 = yymsp[-1].minor.yy327;
  80614. }
  80615. */
  80616. assert( yymsp[-2].minor.yy327!=0 );
  80617. yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
  80618. yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
  80619. yygotominor.yy327 = yymsp[-2].minor.yy327;
  80620. }
  80621. break;
  80622. case 280: /* trigger_cmd_list ::= trigger_cmd SEMI */
  80623. {
  80624. /* if( yymsp[-1].minor.yy327 ) */
  80625. assert( yymsp[-1].minor.yy327!=0 );
  80626. yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
  80627. yygotominor.yy327 = yymsp[-1].minor.yy327;
  80628. }
  80629. break;
  80630. case 281: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
  80631. { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-4].minor.yy392); }
  80632. break;
  80633. case 282: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
  80634. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy180, yymsp[-1].minor.yy442, 0, yymsp[-7].minor.yy392);}
  80635. break;
  80636. case 283: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
  80637. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy392);}
  80638. break;
  80639. case 284: /* trigger_cmd ::= DELETE FROM nm where_opt */
  80640. {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy0, yymsp[0].minor.yy122);}
  80641. break;
  80642. case 285: /* trigger_cmd ::= select */
  80643. {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
  80644. break;
  80645. case 286: /* expr ::= RAISE LP IGNORE RP */
  80646. {
  80647. yygotominor.yy122 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  80648. if( yygotominor.yy122 ){
  80649. yygotominor.yy122->iColumn = OE_Ignore;
  80650. sqlite3ExprSpan(yygotominor.yy122, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
  80651. }
  80652. }
  80653. break;
  80654. case 287: /* expr ::= RAISE LP raisetype COMMA nm RP */
  80655. {
  80656. yygotominor.yy122 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  80657. if( yygotominor.yy122 ) {
  80658. yygotominor.yy122->iColumn = yymsp[-3].minor.yy392;
  80659. sqlite3ExprSpan(yygotominor.yy122, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
  80660. }
  80661. }
  80662. break;
  80663. case 288: /* raisetype ::= ROLLBACK */
  80664. {yygotominor.yy392 = OE_Rollback;}
  80665. break;
  80666. case 290: /* raisetype ::= FAIL */
  80667. {yygotominor.yy392 = OE_Fail;}
  80668. break;
  80669. case 291: /* cmd ::= DROP TRIGGER ifexists fullname */
  80670. {
  80671. sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
  80672. }
  80673. break;
  80674. case 292: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  80675. {
  80676. sqlite3Attach(pParse, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, yymsp[0].minor.yy122);
  80677. }
  80678. break;
  80679. case 293: /* cmd ::= DETACH database_kw_opt expr */
  80680. {
  80681. sqlite3Detach(pParse, yymsp[0].minor.yy122);
  80682. }
  80683. break;
  80684. case 298: /* cmd ::= REINDEX */
  80685. {sqlite3Reindex(pParse, 0, 0);}
  80686. break;
  80687. case 299: /* cmd ::= REINDEX nm dbnm */
  80688. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  80689. break;
  80690. case 300: /* cmd ::= ANALYZE */
  80691. {sqlite3Analyze(pParse, 0, 0);}
  80692. break;
  80693. case 301: /* cmd ::= ANALYZE nm dbnm */
  80694. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  80695. break;
  80696. case 302: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  80697. {
  80698. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
  80699. }
  80700. break;
  80701. case 303: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  80702. {
  80703. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  80704. }
  80705. break;
  80706. case 304: /* add_column_fullname ::= fullname */
  80707. {
  80708. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
  80709. }
  80710. break;
  80711. case 307: /* cmd ::= create_vtab */
  80712. {sqlite3VtabFinishParse(pParse,0);}
  80713. break;
  80714. case 308: /* cmd ::= create_vtab LP vtabarglist RP */
  80715. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  80716. break;
  80717. case 309: /* create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm */
  80718. {
  80719. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
  80720. }
  80721. break;
  80722. case 312: /* vtabarg ::= */
  80723. {sqlite3VtabArgInit(pParse);}
  80724. break;
  80725. case 314: /* vtabargtoken ::= ANY */
  80726. case 315: /* vtabargtoken ::= lp anylist RP */
  80727. case 316: /* lp ::= LP */
  80728. case 318: /* anylist ::= anylist ANY */
  80729. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  80730. break;
  80731. };
  80732. yygoto = yyRuleInfo[yyruleno].lhs;
  80733. yysize = yyRuleInfo[yyruleno].nrhs;
  80734. yypParser->yyidx -= yysize;
  80735. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  80736. if( yyact < YYNSTATE ){
  80737. #ifdef NDEBUG
  80738. /* If we are not debugging and the reduce action popped at least
  80739. ** one element off the stack, then we can push the new element back
  80740. ** onto the stack here, and skip the stack overflow test in yy_shift().
  80741. ** That gives a significant speed improvement. */
  80742. if( yysize ){
  80743. yypParser->yyidx++;
  80744. yymsp -= yysize-1;
  80745. yymsp->stateno = yyact;
  80746. yymsp->major = yygoto;
  80747. yymsp->minor = yygotominor;
  80748. }else
  80749. #endif
  80750. {
  80751. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  80752. }
  80753. }else{
  80754. assert( yyact == YYNSTATE + YYNRULE + 1 );
  80755. yy_accept(yypParser);
  80756. }
  80757. }
  80758. /*
  80759. ** The following code executes when the parse fails
  80760. */
  80761. static void yy_parse_failed(
  80762. yyParser *yypParser /* The parser */
  80763. ){
  80764. sqlite3ParserARG_FETCH;
  80765. #ifndef NDEBUG
  80766. if( yyTraceFILE ){
  80767. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  80768. }
  80769. #endif
  80770. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  80771. /* Here code is inserted which will be executed whenever the
  80772. ** parser fails */
  80773. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  80774. }
  80775. /*
  80776. ** The following code executes when a syntax error first occurs.
  80777. */
  80778. static void yy_syntax_error(
  80779. yyParser *yypParser, /* The parser */
  80780. int yymajor, /* The major type of the error token */
  80781. YYMINORTYPE yyminor /* The minor type of the error token */
  80782. ){
  80783. sqlite3ParserARG_FETCH;
  80784. #define TOKEN (yyminor.yy0)
  80785. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  80786. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  80787. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  80788. pParse->parseError = 1;
  80789. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  80790. }
  80791. /*
  80792. ** The following is executed when the parser accepts
  80793. */
  80794. static void yy_accept(
  80795. yyParser *yypParser /* The parser */
  80796. ){
  80797. sqlite3ParserARG_FETCH;
  80798. #ifndef NDEBUG
  80799. if( yyTraceFILE ){
  80800. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  80801. }
  80802. #endif
  80803. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  80804. /* Here code is inserted which will be executed whenever the
  80805. ** parser accepts */
  80806. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  80807. }
  80808. /* The main parser program.
  80809. ** The first argument is a pointer to a structure obtained from
  80810. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  80811. ** The second argument is the major token number. The third is
  80812. ** the minor token. The fourth optional argument is whatever the
  80813. ** user wants (and specified in the grammar) and is available for
  80814. ** use by the action routines.
  80815. **
  80816. ** Inputs:
  80817. ** <ul>
  80818. ** <li> A pointer to the parser (an opaque structure.)
  80819. ** <li> The major token number.
  80820. ** <li> The minor token number.
  80821. ** <li> An option argument of a grammar-specified type.
  80822. ** </ul>
  80823. **
  80824. ** Outputs:
  80825. ** None.
  80826. */
  80827. SQLITE_PRIVATE void sqlite3Parser(
  80828. void *yyp, /* The parser */
  80829. int yymajor, /* The major token code number */
  80830. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  80831. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  80832. ){
  80833. YYMINORTYPE yyminorunion;
  80834. int yyact; /* The parser action. */
  80835. int yyendofinput; /* True if we are at the end of input */
  80836. #ifdef YYERRORSYMBOL
  80837. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  80838. #endif
  80839. yyParser *yypParser; /* The parser */
  80840. /* (re)initialize the parser, if necessary */
  80841. yypParser = (yyParser*)yyp;
  80842. if( yypParser->yyidx<0 ){
  80843. #if YYSTACKDEPTH<=0
  80844. if( yypParser->yystksz <=0 ){
  80845. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  80846. yyminorunion = yyzerominor;
  80847. yyStackOverflow(yypParser, &yyminorunion);
  80848. return;
  80849. }
  80850. #endif
  80851. yypParser->yyidx = 0;
  80852. yypParser->yyerrcnt = -1;
  80853. yypParser->yystack[0].stateno = 0;
  80854. yypParser->yystack[0].major = 0;
  80855. }
  80856. yyminorunion.yy0 = yyminor;
  80857. yyendofinput = (yymajor==0);
  80858. sqlite3ParserARG_STORE;
  80859. #ifndef NDEBUG
  80860. if( yyTraceFILE ){
  80861. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  80862. }
  80863. #endif
  80864. do{
  80865. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  80866. if( yyact<YYNSTATE ){
  80867. assert( !yyendofinput ); /* Impossible to shift the $ token */
  80868. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  80869. yypParser->yyerrcnt--;
  80870. yymajor = YYNOCODE;
  80871. }else if( yyact < YYNSTATE + YYNRULE ){
  80872. yy_reduce(yypParser,yyact-YYNSTATE);
  80873. }else{
  80874. assert( yyact == YY_ERROR_ACTION );
  80875. #ifdef YYERRORSYMBOL
  80876. int yymx;
  80877. #endif
  80878. #ifndef NDEBUG
  80879. if( yyTraceFILE ){
  80880. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  80881. }
  80882. #endif
  80883. #ifdef YYERRORSYMBOL
  80884. /* A syntax error has occurred.
  80885. ** The response to an error depends upon whether or not the
  80886. ** grammar defines an error token "ERROR".
  80887. **
  80888. ** This is what we do if the grammar does define ERROR:
  80889. **
  80890. ** * Call the %syntax_error function.
  80891. **
  80892. ** * Begin popping the stack until we enter a state where
  80893. ** it is legal to shift the error symbol, then shift
  80894. ** the error symbol.
  80895. **
  80896. ** * Set the error count to three.
  80897. **
  80898. ** * Begin accepting and shifting new tokens. No new error
  80899. ** processing will occur until three tokens have been
  80900. ** shifted successfully.
  80901. **
  80902. */
  80903. if( yypParser->yyerrcnt<0 ){
  80904. yy_syntax_error(yypParser,yymajor,yyminorunion);
  80905. }
  80906. yymx = yypParser->yystack[yypParser->yyidx].major;
  80907. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  80908. #ifndef NDEBUG
  80909. if( yyTraceFILE ){
  80910. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  80911. yyTracePrompt,yyTokenName[yymajor]);
  80912. }
  80913. #endif
  80914. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  80915. yymajor = YYNOCODE;
  80916. }else{
  80917. while(
  80918. yypParser->yyidx >= 0 &&
  80919. yymx != YYERRORSYMBOL &&
  80920. (yyact = yy_find_reduce_action(
  80921. yypParser->yystack[yypParser->yyidx].stateno,
  80922. YYERRORSYMBOL)) >= YYNSTATE
  80923. ){
  80924. yy_pop_parser_stack(yypParser);
  80925. }
  80926. if( yypParser->yyidx < 0 || yymajor==0 ){
  80927. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  80928. yy_parse_failed(yypParser);
  80929. yymajor = YYNOCODE;
  80930. }else if( yymx!=YYERRORSYMBOL ){
  80931. YYMINORTYPE u2;
  80932. u2.YYERRSYMDT = 0;
  80933. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  80934. }
  80935. }
  80936. yypParser->yyerrcnt = 3;
  80937. yyerrorhit = 1;
  80938. #else /* YYERRORSYMBOL is not defined */
  80939. /* This is what we do if the grammar does not define ERROR:
  80940. **
  80941. ** * Report an error message, and throw away the input token.
  80942. **
  80943. ** * If the input token is $, then fail the parse.
  80944. **
  80945. ** As before, subsequent error messages are suppressed until
  80946. ** three input tokens have been successfully shifted.
  80947. */
  80948. if( yypParser->yyerrcnt<=0 ){
  80949. yy_syntax_error(yypParser,yymajor,yyminorunion);
  80950. }
  80951. yypParser->yyerrcnt = 3;
  80952. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  80953. if( yyendofinput ){
  80954. yy_parse_failed(yypParser);
  80955. }
  80956. yymajor = YYNOCODE;
  80957. #endif
  80958. }
  80959. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  80960. return;
  80961. }
  80962. /************** End of parse.c ***********************************************/
  80963. /************** Begin file tokenize.c ****************************************/
  80964. /*
  80965. ** 2001 September 15
  80966. **
  80967. ** The author disclaims copyright to this source code. In place of
  80968. ** a legal notice, here is a blessing:
  80969. **
  80970. ** May you do good and not evil.
  80971. ** May you find forgiveness for yourself and forgive others.
  80972. ** May you share freely, never taking more than you give.
  80973. **
  80974. *************************************************************************
  80975. ** An tokenizer for SQL
  80976. **
  80977. ** This file contains C code that splits an SQL input string up into
  80978. ** individual tokens and sends those tokens one-by-one over to the
  80979. ** parser for analysis.
  80980. **
  80981. ** $Id: tokenize.c,v 1.152 2008/09/01 15:52:11 drh Exp $
  80982. */
  80983. /*
  80984. ** The charMap() macro maps alphabetic characters into their
  80985. ** lower-case ASCII equivalent. On ASCII machines, this is just
  80986. ** an upper-to-lower case map. On EBCDIC machines we also need
  80987. ** to adjust the encoding. Only alphabetic characters and underscores
  80988. ** need to be translated.
  80989. */
  80990. #ifdef SQLITE_ASCII
  80991. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  80992. #endif
  80993. #ifdef SQLITE_EBCDIC
  80994. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  80995. const unsigned char ebcdicToAscii[] = {
  80996. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  80997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  80998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  80999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  81000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  81001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  81002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  81003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  81004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  81005. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  81006. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  81007. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  81008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  81009. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  81010. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  81011. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  81012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  81013. };
  81014. #endif
  81015. /*
  81016. ** The sqlite3KeywordCode function looks up an identifier to determine if
  81017. ** it is a keyword. If it is a keyword, the token code of that keyword is
  81018. ** returned. If the input is not a keyword, TK_ID is returned.
  81019. **
  81020. ** The implementation of this routine was generated by a program,
  81021. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  81022. ** The output of the mkkeywordhash.c program is written into a file
  81023. ** named keywordhash.h and then included into this source file by
  81024. ** the #include below.
  81025. */
  81026. /************** Include keywordhash.h in the middle of tokenize.c ************/
  81027. /************** Begin file keywordhash.h *************************************/
  81028. /***** This file contains automatically generated code ******
  81029. **
  81030. ** The code in this file has been automatically generated by
  81031. **
  81032. ** $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.36 2008/12/31 21:52:41 drh Exp $
  81033. **
  81034. ** The code in this file implements a function that determines whether
  81035. ** or not a given identifier is really an SQL keyword. The same thing
  81036. ** might be implemented more directly using a hand-written hash table.
  81037. ** But by using this automatically generated code, the size of the code
  81038. ** is substantially reduced. This is important for embedded applications
  81039. ** on platforms with limited memory.
  81040. */
  81041. /* Hash score: 171 */
  81042. static int keywordCode(const char *z, int n){
  81043. /* zText[] encodes 801 bytes of keywords in 541 bytes */
  81044. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  81045. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  81046. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  81047. /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
  81048. /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
  81049. /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
  81050. /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  81051. /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
  81052. /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
  81053. /* INITIALLY */
  81054. static const char zText[540] = {
  81055. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  81056. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  81057. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  81058. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  81059. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  81060. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  81061. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  81062. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  81063. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  81064. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  81065. 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
  81066. 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
  81067. 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
  81068. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  81069. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  81070. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  81071. 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
  81072. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  81073. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
  81074. 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
  81075. 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
  81076. 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
  81077. 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
  81078. 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
  81079. 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
  81080. 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
  81081. 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
  81082. 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
  81083. 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
  81084. 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
  81085. };
  81086. static const unsigned char aHash[127] = {
  81087. 70, 99, 112, 68, 0, 43, 0, 0, 76, 0, 71, 0, 0,
  81088. 41, 12, 72, 15, 0, 111, 79, 49, 106, 0, 19, 0, 0,
  81089. 116, 0, 114, 109, 0, 22, 87, 0, 9, 0, 0, 64, 65,
  81090. 0, 63, 6, 0, 47, 84, 96, 0, 113, 95, 0, 0, 44,
  81091. 0, 97, 24, 0, 17, 0, 117, 48, 23, 0, 5, 104, 25,
  81092. 90, 0, 0, 119, 100, 55, 118, 52, 7, 50, 0, 85, 0,
  81093. 94, 26, 0, 93, 0, 0, 0, 89, 86, 91, 82, 103, 14,
  81094. 38, 102, 0, 75, 0, 18, 83, 105, 31, 0, 115, 74, 107,
  81095. 57, 45, 78, 0, 0, 88, 39, 0, 110, 0, 35, 0, 0,
  81096. 28, 0, 80, 53, 58, 0, 20, 56, 0, 51,
  81097. };
  81098. static const unsigned char aNext[119] = {
  81099. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  81100. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  81101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  81102. 0, 0, 0, 0, 32, 21, 0, 0, 0, 42, 3, 46, 0,
  81103. 0, 0, 0, 29, 0, 0, 37, 0, 0, 0, 1, 60, 0,
  81104. 0, 61, 0, 40, 0, 0, 0, 0, 0, 0, 0, 59, 0,
  81105. 0, 0, 0, 30, 54, 16, 33, 10, 0, 0, 0, 0, 0,
  81106. 0, 0, 11, 66, 73, 0, 8, 0, 98, 92, 0, 101, 0,
  81107. 81, 0, 69, 0, 0, 108, 27, 36, 67, 77, 0, 34, 62,
  81108. 0, 0,
  81109. };
  81110. static const unsigned char aLen[119] = {
  81111. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  81112. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  81113. 11, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, 4,
  81114. 6, 2, 3, 4, 9, 2, 6, 5, 6, 6, 5, 6, 5,
  81115. 5, 7, 7, 7, 3, 4, 4, 7, 3, 6, 4, 7, 6,
  81116. 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6, 7, 5,
  81117. 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4, 6, 6,
  81118. 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4, 4, 4,
  81119. 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5, 6, 4,
  81120. 9, 3,
  81121. };
  81122. static const unsigned short int aOffset[119] = {
  81123. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  81124. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  81125. 86, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, 159,
  81126. 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197, 203,
  81127. 206, 210, 217, 223, 223, 226, 229, 233, 234, 238, 244, 248, 255,
  81128. 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320, 326, 332,
  81129. 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383, 387, 393,
  81130. 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458, 462, 466,
  81131. 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516, 521, 527,
  81132. 531, 536,
  81133. };
  81134. static const unsigned char aCode[119] = {
  81135. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  81136. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  81137. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  81138. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  81139. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  81140. TK_EXCEPT, TK_TRANSACTION,TK_ON, TK_JOIN_KW, TK_ALTER,
  81141. TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, TK_INTERSECT,
  81142. TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, TK_OFFSET,
  81143. TK_OF, TK_SET, TK_TEMP, TK_TEMP, TK_OR,
  81144. TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING, TK_GROUP,
  81145. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE, TK_BETWEEN,
  81146. TK_NOTNULL, TK_NOT, TK_NULL, TK_LIKE_KW, TK_CASCADE,
  81147. TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE, TK_CREATE,
  81148. TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN, TK_INSERT,
  81149. TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT,
  81150. TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, TK_WHERE,
  81151. TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND, TK_DEFAULT,
  81152. TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, TK_COLUMNKW,
  81153. TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW,
  81154. TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, TK_DROP,
  81155. TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, TK_BY,
  81156. TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT, TK_JOIN_KW,
  81157. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  81158. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  81159. };
  81160. int h, i;
  81161. if( n<2 ) return TK_ID;
  81162. h = ((charMap(z[0])*4) ^
  81163. (charMap(z[n-1])*3) ^
  81164. n) % 127;
  81165. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  81166. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  81167. testcase( i==0 ); /* TK_REINDEX */
  81168. testcase( i==1 ); /* TK_INDEXED */
  81169. testcase( i==2 ); /* TK_INDEX */
  81170. testcase( i==3 ); /* TK_DESC */
  81171. testcase( i==4 ); /* TK_ESCAPE */
  81172. testcase( i==5 ); /* TK_EACH */
  81173. testcase( i==6 ); /* TK_CHECK */
  81174. testcase( i==7 ); /* TK_KEY */
  81175. testcase( i==8 ); /* TK_BEFORE */
  81176. testcase( i==9 ); /* TK_FOREIGN */
  81177. testcase( i==10 ); /* TK_FOR */
  81178. testcase( i==11 ); /* TK_IGNORE */
  81179. testcase( i==12 ); /* TK_LIKE_KW */
  81180. testcase( i==13 ); /* TK_EXPLAIN */
  81181. testcase( i==14 ); /* TK_INSTEAD */
  81182. testcase( i==15 ); /* TK_ADD */
  81183. testcase( i==16 ); /* TK_DATABASE */
  81184. testcase( i==17 ); /* TK_AS */
  81185. testcase( i==18 ); /* TK_SELECT */
  81186. testcase( i==19 ); /* TK_TABLE */
  81187. testcase( i==20 ); /* TK_JOIN_KW */
  81188. testcase( i==21 ); /* TK_THEN */
  81189. testcase( i==22 ); /* TK_END */
  81190. testcase( i==23 ); /* TK_DEFERRABLE */
  81191. testcase( i==24 ); /* TK_ELSE */
  81192. testcase( i==25 ); /* TK_EXCEPT */
  81193. testcase( i==26 ); /* TK_TRANSACTION */
  81194. testcase( i==27 ); /* TK_ON */
  81195. testcase( i==28 ); /* TK_JOIN_KW */
  81196. testcase( i==29 ); /* TK_ALTER */
  81197. testcase( i==30 ); /* TK_RAISE */
  81198. testcase( i==31 ); /* TK_EXCLUSIVE */
  81199. testcase( i==32 ); /* TK_EXISTS */
  81200. testcase( i==33 ); /* TK_SAVEPOINT */
  81201. testcase( i==34 ); /* TK_INTERSECT */
  81202. testcase( i==35 ); /* TK_TRIGGER */
  81203. testcase( i==36 ); /* TK_REFERENCES */
  81204. testcase( i==37 ); /* TK_CONSTRAINT */
  81205. testcase( i==38 ); /* TK_INTO */
  81206. testcase( i==39 ); /* TK_OFFSET */
  81207. testcase( i==40 ); /* TK_OF */
  81208. testcase( i==41 ); /* TK_SET */
  81209. testcase( i==42 ); /* TK_TEMP */
  81210. testcase( i==43 ); /* TK_TEMP */
  81211. testcase( i==44 ); /* TK_OR */
  81212. testcase( i==45 ); /* TK_UNIQUE */
  81213. testcase( i==46 ); /* TK_QUERY */
  81214. testcase( i==47 ); /* TK_ATTACH */
  81215. testcase( i==48 ); /* TK_HAVING */
  81216. testcase( i==49 ); /* TK_GROUP */
  81217. testcase( i==50 ); /* TK_UPDATE */
  81218. testcase( i==51 ); /* TK_BEGIN */
  81219. testcase( i==52 ); /* TK_JOIN_KW */
  81220. testcase( i==53 ); /* TK_RELEASE */
  81221. testcase( i==54 ); /* TK_BETWEEN */
  81222. testcase( i==55 ); /* TK_NOTNULL */
  81223. testcase( i==56 ); /* TK_NOT */
  81224. testcase( i==57 ); /* TK_NULL */
  81225. testcase( i==58 ); /* TK_LIKE_KW */
  81226. testcase( i==59 ); /* TK_CASCADE */
  81227. testcase( i==60 ); /* TK_ASC */
  81228. testcase( i==61 ); /* TK_DELETE */
  81229. testcase( i==62 ); /* TK_CASE */
  81230. testcase( i==63 ); /* TK_COLLATE */
  81231. testcase( i==64 ); /* TK_CREATE */
  81232. testcase( i==65 ); /* TK_CTIME_KW */
  81233. testcase( i==66 ); /* TK_DETACH */
  81234. testcase( i==67 ); /* TK_IMMEDIATE */
  81235. testcase( i==68 ); /* TK_JOIN */
  81236. testcase( i==69 ); /* TK_INSERT */
  81237. testcase( i==70 ); /* TK_MATCH */
  81238. testcase( i==71 ); /* TK_PLAN */
  81239. testcase( i==72 ); /* TK_ANALYZE */
  81240. testcase( i==73 ); /* TK_PRAGMA */
  81241. testcase( i==74 ); /* TK_ABORT */
  81242. testcase( i==75 ); /* TK_VALUES */
  81243. testcase( i==76 ); /* TK_VIRTUAL */
  81244. testcase( i==77 ); /* TK_LIMIT */
  81245. testcase( i==78 ); /* TK_WHEN */
  81246. testcase( i==79 ); /* TK_WHERE */
  81247. testcase( i==80 ); /* TK_RENAME */
  81248. testcase( i==81 ); /* TK_AFTER */
  81249. testcase( i==82 ); /* TK_REPLACE */
  81250. testcase( i==83 ); /* TK_AND */
  81251. testcase( i==84 ); /* TK_DEFAULT */
  81252. testcase( i==85 ); /* TK_AUTOINCR */
  81253. testcase( i==86 ); /* TK_TO */
  81254. testcase( i==87 ); /* TK_IN */
  81255. testcase( i==88 ); /* TK_CAST */
  81256. testcase( i==89 ); /* TK_COLUMNKW */
  81257. testcase( i==90 ); /* TK_COMMIT */
  81258. testcase( i==91 ); /* TK_CONFLICT */
  81259. testcase( i==92 ); /* TK_JOIN_KW */
  81260. testcase( i==93 ); /* TK_CTIME_KW */
  81261. testcase( i==94 ); /* TK_CTIME_KW */
  81262. testcase( i==95 ); /* TK_PRIMARY */
  81263. testcase( i==96 ); /* TK_DEFERRED */
  81264. testcase( i==97 ); /* TK_DISTINCT */
  81265. testcase( i==98 ); /* TK_IS */
  81266. testcase( i==99 ); /* TK_DROP */
  81267. testcase( i==100 ); /* TK_FAIL */
  81268. testcase( i==101 ); /* TK_FROM */
  81269. testcase( i==102 ); /* TK_JOIN_KW */
  81270. testcase( i==103 ); /* TK_LIKE_KW */
  81271. testcase( i==104 ); /* TK_BY */
  81272. testcase( i==105 ); /* TK_IF */
  81273. testcase( i==106 ); /* TK_ISNULL */
  81274. testcase( i==107 ); /* TK_ORDER */
  81275. testcase( i==108 ); /* TK_RESTRICT */
  81276. testcase( i==109 ); /* TK_JOIN_KW */
  81277. testcase( i==110 ); /* TK_JOIN_KW */
  81278. testcase( i==111 ); /* TK_ROLLBACK */
  81279. testcase( i==112 ); /* TK_ROW */
  81280. testcase( i==113 ); /* TK_UNION */
  81281. testcase( i==114 ); /* TK_USING */
  81282. testcase( i==115 ); /* TK_VACUUM */
  81283. testcase( i==116 ); /* TK_VIEW */
  81284. testcase( i==117 ); /* TK_INITIALLY */
  81285. testcase( i==118 ); /* TK_ALL */
  81286. return aCode[i];
  81287. }
  81288. }
  81289. return TK_ID;
  81290. }
  81291. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  81292. return keywordCode((char*)z, n);
  81293. }
  81294. /************** End of keywordhash.h *****************************************/
  81295. /************** Continuing where we left off in tokenize.c *******************/
  81296. /*
  81297. ** If X is a character that can be used in an identifier then
  81298. ** IdChar(X) will be true. Otherwise it is false.
  81299. **
  81300. ** For ASCII, any character with the high-order bit set is
  81301. ** allowed in an identifier. For 7-bit characters,
  81302. ** sqlite3IsIdChar[X] must be 1.
  81303. **
  81304. ** For EBCDIC, the rules are more complex but have the same
  81305. ** end result.
  81306. **
  81307. ** Ticket #1066. the SQL standard does not allow '$' in the
  81308. ** middle of identfiers. But many SQL implementations do.
  81309. ** SQLite will allow '$' in identifiers for compatibility.
  81310. ** But the feature is undocumented.
  81311. */
  81312. #ifdef SQLITE_ASCII
  81313. SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[] = {
  81314. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  81315. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  81316. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  81317. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  81318. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  81319. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  81320. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  81321. };
  81322. #define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
  81323. #endif
  81324. #ifdef SQLITE_EBCDIC
  81325. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  81326. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  81327. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  81328. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  81329. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  81330. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  81331. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  81332. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  81333. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  81334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  81335. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  81336. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  81337. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  81338. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  81339. };
  81340. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  81341. #endif
  81342. /*
  81343. ** Return the length of the token that begins at z[0].
  81344. ** Store the token type in *tokenType before returning.
  81345. */
  81346. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  81347. int i, c;
  81348. switch( *z ){
  81349. case ' ': case '\t': case '\n': case '\f': case '\r': {
  81350. for(i=1; isspace(z[i]); i++){}
  81351. *tokenType = TK_SPACE;
  81352. return i;
  81353. }
  81354. case '-': {
  81355. if( z[1]=='-' ){
  81356. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  81357. *tokenType = TK_SPACE;
  81358. return i;
  81359. }
  81360. *tokenType = TK_MINUS;
  81361. return 1;
  81362. }
  81363. case '(': {
  81364. *tokenType = TK_LP;
  81365. return 1;
  81366. }
  81367. case ')': {
  81368. *tokenType = TK_RP;
  81369. return 1;
  81370. }
  81371. case ';': {
  81372. *tokenType = TK_SEMI;
  81373. return 1;
  81374. }
  81375. case '+': {
  81376. *tokenType = TK_PLUS;
  81377. return 1;
  81378. }
  81379. case '*': {
  81380. *tokenType = TK_STAR;
  81381. return 1;
  81382. }
  81383. case '/': {
  81384. if( z[1]!='*' || z[2]==0 ){
  81385. *tokenType = TK_SLASH;
  81386. return 1;
  81387. }
  81388. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  81389. if( c ) i++;
  81390. *tokenType = TK_SPACE;
  81391. return i;
  81392. }
  81393. case '%': {
  81394. *tokenType = TK_REM;
  81395. return 1;
  81396. }
  81397. case '=': {
  81398. *tokenType = TK_EQ;
  81399. return 1 + (z[1]=='=');
  81400. }
  81401. case '<': {
  81402. if( (c=z[1])=='=' ){
  81403. *tokenType = TK_LE;
  81404. return 2;
  81405. }else if( c=='>' ){
  81406. *tokenType = TK_NE;
  81407. return 2;
  81408. }else if( c=='<' ){
  81409. *tokenType = TK_LSHIFT;
  81410. return 2;
  81411. }else{
  81412. *tokenType = TK_LT;
  81413. return 1;
  81414. }
  81415. }
  81416. case '>': {
  81417. if( (c=z[1])=='=' ){
  81418. *tokenType = TK_GE;
  81419. return 2;
  81420. }else if( c=='>' ){
  81421. *tokenType = TK_RSHIFT;
  81422. return 2;
  81423. }else{
  81424. *tokenType = TK_GT;
  81425. return 1;
  81426. }
  81427. }
  81428. case '!': {
  81429. if( z[1]!='=' ){
  81430. *tokenType = TK_ILLEGAL;
  81431. return 2;
  81432. }else{
  81433. *tokenType = TK_NE;
  81434. return 2;
  81435. }
  81436. }
  81437. case '|': {
  81438. if( z[1]!='|' ){
  81439. *tokenType = TK_BITOR;
  81440. return 1;
  81441. }else{
  81442. *tokenType = TK_CONCAT;
  81443. return 2;
  81444. }
  81445. }
  81446. case ',': {
  81447. *tokenType = TK_COMMA;
  81448. return 1;
  81449. }
  81450. case '&': {
  81451. *tokenType = TK_BITAND;
  81452. return 1;
  81453. }
  81454. case '~': {
  81455. *tokenType = TK_BITNOT;
  81456. return 1;
  81457. }
  81458. case '`':
  81459. case '\'':
  81460. case '"': {
  81461. int delim = z[0];
  81462. for(i=1; (c=z[i])!=0; i++){
  81463. if( c==delim ){
  81464. if( z[i+1]==delim ){
  81465. i++;
  81466. }else{
  81467. break;
  81468. }
  81469. }
  81470. }
  81471. if( c=='\'' ){
  81472. *tokenType = TK_STRING;
  81473. return i+1;
  81474. }else if( c!=0 ){
  81475. *tokenType = TK_ID;
  81476. return i+1;
  81477. }else{
  81478. *tokenType = TK_ILLEGAL;
  81479. return i;
  81480. }
  81481. }
  81482. case '.': {
  81483. #ifndef SQLITE_OMIT_FLOATING_POINT
  81484. if( !isdigit(z[1]) )
  81485. #endif
  81486. {
  81487. *tokenType = TK_DOT;
  81488. return 1;
  81489. }
  81490. /* If the next character is a digit, this is a floating point
  81491. ** number that begins with ".". Fall thru into the next case */
  81492. }
  81493. case '0': case '1': case '2': case '3': case '4':
  81494. case '5': case '6': case '7': case '8': case '9': {
  81495. *tokenType = TK_INTEGER;
  81496. for(i=0; isdigit(z[i]); i++){}
  81497. #ifndef SQLITE_OMIT_FLOATING_POINT
  81498. if( z[i]=='.' ){
  81499. i++;
  81500. while( isdigit(z[i]) ){ i++; }
  81501. *tokenType = TK_FLOAT;
  81502. }
  81503. if( (z[i]=='e' || z[i]=='E') &&
  81504. ( isdigit(z[i+1])
  81505. || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
  81506. )
  81507. ){
  81508. i += 2;
  81509. while( isdigit(z[i]) ){ i++; }
  81510. *tokenType = TK_FLOAT;
  81511. }
  81512. #endif
  81513. while( IdChar(z[i]) ){
  81514. *tokenType = TK_ILLEGAL;
  81515. i++;
  81516. }
  81517. return i;
  81518. }
  81519. case '[': {
  81520. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  81521. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  81522. return i;
  81523. }
  81524. case '?': {
  81525. *tokenType = TK_VARIABLE;
  81526. for(i=1; isdigit(z[i]); i++){}
  81527. return i;
  81528. }
  81529. case '#': {
  81530. for(i=1; isdigit(z[i]); i++){}
  81531. if( i>1 ){
  81532. /* Parameters of the form #NNN (where NNN is a number) are used
  81533. ** internally by sqlite3NestedParse. */
  81534. *tokenType = TK_REGISTER;
  81535. return i;
  81536. }
  81537. /* Fall through into the next case if the '#' is not followed by
  81538. ** a digit. Try to match #AAAA where AAAA is a parameter name. */
  81539. }
  81540. #ifndef SQLITE_OMIT_TCL_VARIABLE
  81541. case '$':
  81542. #endif
  81543. case '@': /* For compatibility with MS SQL Server */
  81544. case ':': {
  81545. int n = 0;
  81546. *tokenType = TK_VARIABLE;
  81547. for(i=1; (c=z[i])!=0; i++){
  81548. if( IdChar(c) ){
  81549. n++;
  81550. #ifndef SQLITE_OMIT_TCL_VARIABLE
  81551. }else if( c=='(' && n>0 ){
  81552. do{
  81553. i++;
  81554. }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
  81555. if( c==')' ){
  81556. i++;
  81557. }else{
  81558. *tokenType = TK_ILLEGAL;
  81559. }
  81560. break;
  81561. }else if( c==':' && z[i+1]==':' ){
  81562. i++;
  81563. #endif
  81564. }else{
  81565. break;
  81566. }
  81567. }
  81568. if( n==0 ) *tokenType = TK_ILLEGAL;
  81569. return i;
  81570. }
  81571. #ifndef SQLITE_OMIT_BLOB_LITERAL
  81572. case 'x': case 'X': {
  81573. if( z[1]=='\'' ){
  81574. *tokenType = TK_BLOB;
  81575. for(i=2; (c=z[i])!=0 && c!='\''; i++){
  81576. if( !isxdigit(c) ){
  81577. *tokenType = TK_ILLEGAL;
  81578. }
  81579. }
  81580. if( i%2 || !c ) *tokenType = TK_ILLEGAL;
  81581. if( c ) i++;
  81582. return i;
  81583. }
  81584. /* Otherwise fall through to the next case */
  81585. }
  81586. #endif
  81587. default: {
  81588. if( !IdChar(*z) ){
  81589. break;
  81590. }
  81591. for(i=1; IdChar(z[i]); i++){}
  81592. *tokenType = keywordCode((char*)z, i);
  81593. return i;
  81594. }
  81595. }
  81596. *tokenType = TK_ILLEGAL;
  81597. return 1;
  81598. }
  81599. /*
  81600. ** Run the parser on the given SQL string. The parser structure is
  81601. ** passed in. An SQLITE_ status code is returned. If an error occurs
  81602. ** then an and attempt is made to write an error message into
  81603. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  81604. ** error message.
  81605. */
  81606. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  81607. int nErr = 0;
  81608. int i;
  81609. void *pEngine;
  81610. int tokenType;
  81611. int lastTokenParsed = -1;
  81612. sqlite3 *db = pParse->db;
  81613. int mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  81614. if( db->activeVdbeCnt==0 ){
  81615. db->u1.isInterrupted = 0;
  81616. }
  81617. pParse->rc = SQLITE_OK;
  81618. pParse->zTail = pParse->zSql = zSql;
  81619. i = 0;
  81620. assert( pzErrMsg!=0 );
  81621. pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  81622. if( pEngine==0 ){
  81623. db->mallocFailed = 1;
  81624. return SQLITE_NOMEM;
  81625. }
  81626. assert( pParse->sLastToken.dyn==0 );
  81627. assert( pParse->pNewTable==0 );
  81628. assert( pParse->pNewTrigger==0 );
  81629. assert( pParse->nVar==0 );
  81630. assert( pParse->nVarExpr==0 );
  81631. assert( pParse->nVarExprAlloc==0 );
  81632. assert( pParse->apVarExpr==0 );
  81633. while( !db->mallocFailed && zSql[i]!=0 ){
  81634. assert( i>=0 );
  81635. pParse->sLastToken.z = (u8*)&zSql[i];
  81636. assert( pParse->sLastToken.dyn==0 );
  81637. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  81638. i += pParse->sLastToken.n;
  81639. if( i>mxSqlLen ){
  81640. pParse->rc = SQLITE_TOOBIG;
  81641. break;
  81642. }
  81643. switch( tokenType ){
  81644. case TK_SPACE: {
  81645. if( db->u1.isInterrupted ){
  81646. pParse->rc = SQLITE_INTERRUPT;
  81647. sqlite3SetString(pzErrMsg, db, "interrupt");
  81648. goto abort_parse;
  81649. }
  81650. break;
  81651. }
  81652. case TK_ILLEGAL: {
  81653. sqlite3DbFree(db, *pzErrMsg);
  81654. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  81655. &pParse->sLastToken);
  81656. nErr++;
  81657. goto abort_parse;
  81658. }
  81659. case TK_SEMI: {
  81660. pParse->zTail = &zSql[i];
  81661. /* Fall thru into the default case */
  81662. }
  81663. default: {
  81664. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  81665. lastTokenParsed = tokenType;
  81666. if( pParse->rc!=SQLITE_OK ){
  81667. goto abort_parse;
  81668. }
  81669. break;
  81670. }
  81671. }
  81672. }
  81673. abort_parse:
  81674. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  81675. if( lastTokenParsed!=TK_SEMI ){
  81676. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  81677. pParse->zTail = &zSql[i];
  81678. }
  81679. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  81680. }
  81681. #ifdef YYTRACKMAXSTACKDEPTH
  81682. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  81683. sqlite3ParserStackPeak(pEngine)
  81684. );
  81685. #endif /* YYDEBUG */
  81686. sqlite3ParserFree(pEngine, sqlite3_free);
  81687. if( db->mallocFailed ){
  81688. pParse->rc = SQLITE_NOMEM;
  81689. }
  81690. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  81691. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  81692. }
  81693. if( pParse->zErrMsg ){
  81694. if( *pzErrMsg==0 ){
  81695. *pzErrMsg = pParse->zErrMsg;
  81696. }else{
  81697. sqlite3DbFree(db, pParse->zErrMsg);
  81698. }
  81699. pParse->zErrMsg = 0;
  81700. nErr++;
  81701. }
  81702. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  81703. sqlite3VdbeDelete(pParse->pVdbe);
  81704. pParse->pVdbe = 0;
  81705. }
  81706. #ifndef SQLITE_OMIT_SHARED_CACHE
  81707. if( pParse->nested==0 ){
  81708. sqlite3DbFree(db, pParse->aTableLock);
  81709. pParse->aTableLock = 0;
  81710. pParse->nTableLock = 0;
  81711. }
  81712. #endif
  81713. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81714. sqlite3DbFree(db, pParse->apVtabLock);
  81715. #endif
  81716. if( !IN_DECLARE_VTAB ){
  81717. /* If the pParse->declareVtab flag is set, do not delete any table
  81718. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  81719. ** will take responsibility for freeing the Table structure.
  81720. */
  81721. sqlite3DeleteTable(pParse->pNewTable);
  81722. }
  81723. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  81724. sqlite3DbFree(db, pParse->apVarExpr);
  81725. sqlite3DbFree(db, pParse->aAlias);
  81726. while( pParse->pZombieTab ){
  81727. Table *p = pParse->pZombieTab;
  81728. pParse->pZombieTab = p->pNextZombie;
  81729. sqlite3DeleteTable(p);
  81730. }
  81731. if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
  81732. pParse->rc = SQLITE_ERROR;
  81733. }
  81734. return nErr;
  81735. }
  81736. /************** End of tokenize.c ********************************************/
  81737. /************** Begin file complete.c ****************************************/
  81738. /*
  81739. ** 2001 September 15
  81740. **
  81741. ** The author disclaims copyright to this source code. In place of
  81742. ** a legal notice, here is a blessing:
  81743. **
  81744. ** May you do good and not evil.
  81745. ** May you find forgiveness for yourself and forgive others.
  81746. ** May you share freely, never taking more than you give.
  81747. **
  81748. *************************************************************************
  81749. ** An tokenizer for SQL
  81750. **
  81751. ** This file contains C code that implements the sqlite3_complete() API.
  81752. ** This code used to be part of the tokenizer.c source file. But by
  81753. ** separating it out, the code will be automatically omitted from
  81754. ** static links that do not use it.
  81755. **
  81756. ** $Id: complete.c,v 1.7 2008/06/13 18:24:27 drh Exp $
  81757. */
  81758. #ifndef SQLITE_OMIT_COMPLETE
  81759. /*
  81760. ** This is defined in tokenize.c. We just have to import the definition.
  81761. */
  81762. #ifndef SQLITE_AMALGAMATION
  81763. #ifdef SQLITE_ASCII
  81764. SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[];
  81765. #define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
  81766. #endif
  81767. #ifdef SQLITE_EBCDIC
  81768. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  81769. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  81770. #endif
  81771. #endif /* SQLITE_AMALGAMATION */
  81772. /*
  81773. ** Token types used by the sqlite3_complete() routine. See the header
  81774. ** comments on that procedure for additional information.
  81775. */
  81776. #define tkSEMI 0
  81777. #define tkWS 1
  81778. #define tkOTHER 2
  81779. #define tkEXPLAIN 3
  81780. #define tkCREATE 4
  81781. #define tkTEMP 5
  81782. #define tkTRIGGER 6
  81783. #define tkEND 7
  81784. /*
  81785. ** Return TRUE if the given SQL string ends in a semicolon.
  81786. **
  81787. ** Special handling is require for CREATE TRIGGER statements.
  81788. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  81789. ** must end with ";END;".
  81790. **
  81791. ** This implementation uses a state machine with 7 states:
  81792. **
  81793. ** (0) START At the beginning or end of an SQL statement. This routine
  81794. ** returns 1 if it ends in the START state and 0 if it ends
  81795. ** in any other state.
  81796. **
  81797. ** (1) NORMAL We are in the middle of statement which ends with a single
  81798. ** semicolon.
  81799. **
  81800. ** (2) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  81801. ** a statement.
  81802. **
  81803. ** (3) CREATE The keyword CREATE has been seen at the beginning of a
  81804. ** statement, possibly preceeded by EXPLAIN and/or followed by
  81805. ** TEMP or TEMPORARY
  81806. **
  81807. ** (4) TRIGGER We are in the middle of a trigger definition that must be
  81808. ** ended by a semicolon, the keyword END, and another semicolon.
  81809. **
  81810. ** (5) SEMI We've seen the first semicolon in the ";END;" that occurs at
  81811. ** the end of a trigger definition.
  81812. **
  81813. ** (6) END We've seen the ";END" of the ";END;" that occurs at the end
  81814. ** of a trigger difinition.
  81815. **
  81816. ** Transitions between states above are determined by tokens extracted
  81817. ** from the input. The following tokens are significant:
  81818. **
  81819. ** (0) tkSEMI A semicolon.
  81820. ** (1) tkWS Whitespace
  81821. ** (2) tkOTHER Any other SQL token.
  81822. ** (3) tkEXPLAIN The "explain" keyword.
  81823. ** (4) tkCREATE The "create" keyword.
  81824. ** (5) tkTEMP The "temp" or "temporary" keyword.
  81825. ** (6) tkTRIGGER The "trigger" keyword.
  81826. ** (7) tkEND The "end" keyword.
  81827. **
  81828. ** Whitespace never causes a state transition and is always ignored.
  81829. **
  81830. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  81831. ** to recognize the end of a trigger can be omitted. All we have to do
  81832. ** is look for a semicolon that is not part of an string or comment.
  81833. */
  81834. SQLITE_API int sqlite3_complete(const char *zSql){
  81835. u8 state = 0; /* Current state, using numbers defined in header comment */
  81836. u8 token; /* Value of the next token */
  81837. #ifndef SQLITE_OMIT_TRIGGER
  81838. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  81839. ** statement. This is the normal case.
  81840. */
  81841. static const u8 trans[7][8] = {
  81842. /* Token: */
  81843. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  81844. /* 0 START: */ { 0, 0, 1, 2, 3, 1, 1, 1, },
  81845. /* 1 NORMAL: */ { 0, 1, 1, 1, 1, 1, 1, 1, },
  81846. /* 2 EXPLAIN: */ { 0, 2, 1, 1, 3, 1, 1, 1, },
  81847. /* 3 CREATE: */ { 0, 3, 1, 1, 1, 3, 4, 1, },
  81848. /* 4 TRIGGER: */ { 5, 4, 4, 4, 4, 4, 4, 4, },
  81849. /* 5 SEMI: */ { 5, 5, 4, 4, 4, 4, 4, 6, },
  81850. /* 6 END: */ { 0, 6, 4, 4, 4, 4, 4, 4, },
  81851. };
  81852. #else
  81853. /* If triggers are not suppored by this compile then the statement machine
  81854. ** used to detect the end of a statement is much simplier
  81855. */
  81856. static const u8 trans[2][3] = {
  81857. /* Token: */
  81858. /* State: ** SEMI WS OTHER */
  81859. /* 0 START: */ { 0, 0, 1, },
  81860. /* 1 NORMAL: */ { 0, 1, 1, },
  81861. };
  81862. #endif /* SQLITE_OMIT_TRIGGER */
  81863. while( *zSql ){
  81864. switch( *zSql ){
  81865. case ';': { /* A semicolon */
  81866. token = tkSEMI;
  81867. break;
  81868. }
  81869. case ' ':
  81870. case '\r':
  81871. case '\t':
  81872. case '\n':
  81873. case '\f': { /* White space is ignored */
  81874. token = tkWS;
  81875. break;
  81876. }
  81877. case '/': { /* C-style comments */
  81878. if( zSql[1]!='*' ){
  81879. token = tkOTHER;
  81880. break;
  81881. }
  81882. zSql += 2;
  81883. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  81884. if( zSql[0]==0 ) return 0;
  81885. zSql++;
  81886. token = tkWS;
  81887. break;
  81888. }
  81889. case '-': { /* SQL-style comments from "--" to end of line */
  81890. if( zSql[1]!='-' ){
  81891. token = tkOTHER;
  81892. break;
  81893. }
  81894. while( *zSql && *zSql!='\n' ){ zSql++; }
  81895. if( *zSql==0 ) return state==0;
  81896. token = tkWS;
  81897. break;
  81898. }
  81899. case '[': { /* Microsoft-style identifiers in [...] */
  81900. zSql++;
  81901. while( *zSql && *zSql!=']' ){ zSql++; }
  81902. if( *zSql==0 ) return 0;
  81903. token = tkOTHER;
  81904. break;
  81905. }
  81906. case '`': /* Grave-accent quoted symbols used by MySQL */
  81907. case '"': /* single- and double-quoted strings */
  81908. case '\'': {
  81909. int c = *zSql;
  81910. zSql++;
  81911. while( *zSql && *zSql!=c ){ zSql++; }
  81912. if( *zSql==0 ) return 0;
  81913. token = tkOTHER;
  81914. break;
  81915. }
  81916. default: {
  81917. int c;
  81918. if( IdChar((u8)*zSql) ){
  81919. /* Keywords and unquoted identifiers */
  81920. int nId;
  81921. for(nId=1; IdChar(zSql[nId]); nId++){}
  81922. #ifdef SQLITE_OMIT_TRIGGER
  81923. token = tkOTHER;
  81924. #else
  81925. switch( *zSql ){
  81926. case 'c': case 'C': {
  81927. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  81928. token = tkCREATE;
  81929. }else{
  81930. token = tkOTHER;
  81931. }
  81932. break;
  81933. }
  81934. case 't': case 'T': {
  81935. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  81936. token = tkTRIGGER;
  81937. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  81938. token = tkTEMP;
  81939. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  81940. token = tkTEMP;
  81941. }else{
  81942. token = tkOTHER;
  81943. }
  81944. break;
  81945. }
  81946. case 'e': case 'E': {
  81947. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  81948. token = tkEND;
  81949. }else
  81950. #ifndef SQLITE_OMIT_EXPLAIN
  81951. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  81952. token = tkEXPLAIN;
  81953. }else
  81954. #endif
  81955. {
  81956. token = tkOTHER;
  81957. }
  81958. break;
  81959. }
  81960. default: {
  81961. token = tkOTHER;
  81962. break;
  81963. }
  81964. }
  81965. #endif /* SQLITE_OMIT_TRIGGER */
  81966. zSql += nId-1;
  81967. }else{
  81968. /* Operators and special symbols */
  81969. token = tkOTHER;
  81970. }
  81971. break;
  81972. }
  81973. }
  81974. state = trans[state][token];
  81975. zSql++;
  81976. }
  81977. return state==0;
  81978. }
  81979. #ifndef SQLITE_OMIT_UTF16
  81980. /*
  81981. ** This routine is the same as the sqlite3_complete() routine described
  81982. ** above, except that the parameter is required to be UTF-16 encoded, not
  81983. ** UTF-8.
  81984. */
  81985. SQLITE_API int sqlite3_complete16(const void *zSql){
  81986. sqlite3_value *pVal;
  81987. char const *zSql8;
  81988. int rc = SQLITE_NOMEM;
  81989. #ifndef SQLITE_OMIT_AUTOINIT
  81990. rc = sqlite3_initialize();
  81991. if( rc ) return rc;
  81992. #endif
  81993. pVal = sqlite3ValueNew(0);
  81994. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  81995. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  81996. if( zSql8 ){
  81997. rc = sqlite3_complete(zSql8);
  81998. }else{
  81999. rc = SQLITE_NOMEM;
  82000. }
  82001. sqlite3ValueFree(pVal);
  82002. return sqlite3ApiExit(0, rc);
  82003. }
  82004. #endif /* SQLITE_OMIT_UTF16 */
  82005. #endif /* SQLITE_OMIT_COMPLETE */
  82006. /************** End of complete.c ********************************************/
  82007. /************** Begin file main.c ********************************************/
  82008. /*
  82009. ** 2001 September 15
  82010. **
  82011. ** The author disclaims copyright to this source code. In place of
  82012. ** a legal notice, here is a blessing:
  82013. **
  82014. ** May you do good and not evil.
  82015. ** May you find forgiveness for yourself and forgive others.
  82016. ** May you share freely, never taking more than you give.
  82017. **
  82018. *************************************************************************
  82019. ** Main file for the SQLite library. The routines in this file
  82020. ** implement the programmer interface to the library. Routines in
  82021. ** other files are for internal use by SQLite and should not be
  82022. ** accessed by users of the library.
  82023. **
  82024. ** $Id: main.c,v 1.521 2009/01/10 16:15:22 drh Exp $
  82025. */
  82026. #ifdef SQLITE_ENABLE_FTS3
  82027. /************** Include fts3.h in the middle of main.c ***********************/
  82028. /************** Begin file fts3.h ********************************************/
  82029. /*
  82030. ** 2006 Oct 10
  82031. **
  82032. ** The author disclaims copyright to this source code. In place of
  82033. ** a legal notice, here is a blessing:
  82034. **
  82035. ** May you do good and not evil.
  82036. ** May you find forgiveness for yourself and forgive others.
  82037. ** May you share freely, never taking more than you give.
  82038. **
  82039. ******************************************************************************
  82040. **
  82041. ** This header file is used by programs that want to link against the
  82042. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  82043. */
  82044. #if 0
  82045. extern "C" {
  82046. #endif /* __cplusplus */
  82047. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  82048. #if 0
  82049. } /* extern "C" */
  82050. #endif /* __cplusplus */
  82051. /************** End of fts3.h ************************************************/
  82052. /************** Continuing where we left off in main.c ***********************/
  82053. #endif
  82054. #ifdef SQLITE_ENABLE_RTREE
  82055. /************** Include rtree.h in the middle of main.c **********************/
  82056. /************** Begin file rtree.h *******************************************/
  82057. /*
  82058. ** 2008 May 26
  82059. **
  82060. ** The author disclaims copyright to this source code. In place of
  82061. ** a legal notice, here is a blessing:
  82062. **
  82063. ** May you do good and not evil.
  82064. ** May you find forgiveness for yourself and forgive others.
  82065. ** May you share freely, never taking more than you give.
  82066. **
  82067. ******************************************************************************
  82068. **
  82069. ** This header file is used by programs that want to link against the
  82070. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  82071. */
  82072. #if 0
  82073. extern "C" {
  82074. #endif /* __cplusplus */
  82075. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  82076. #if 0
  82077. } /* extern "C" */
  82078. #endif /* __cplusplus */
  82079. /************** End of rtree.h ***********************************************/
  82080. /************** Continuing where we left off in main.c ***********************/
  82081. #endif
  82082. #ifdef SQLITE_ENABLE_ICU
  82083. /************** Include sqliteicu.h in the middle of main.c ******************/
  82084. /************** Begin file sqliteicu.h ***************************************/
  82085. /*
  82086. ** 2008 May 26
  82087. **
  82088. ** The author disclaims copyright to this source code. In place of
  82089. ** a legal notice, here is a blessing:
  82090. **
  82091. ** May you do good and not evil.
  82092. ** May you find forgiveness for yourself and forgive others.
  82093. ** May you share freely, never taking more than you give.
  82094. **
  82095. ******************************************************************************
  82096. **
  82097. ** This header file is used by programs that want to link against the
  82098. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  82099. */
  82100. #if 0
  82101. extern "C" {
  82102. #endif /* __cplusplus */
  82103. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  82104. #if 0
  82105. } /* extern "C" */
  82106. #endif /* __cplusplus */
  82107. /************** End of sqliteicu.h *******************************************/
  82108. /************** Continuing where we left off in main.c ***********************/
  82109. #endif
  82110. /*
  82111. ** The version of the library
  82112. */
  82113. #ifndef SQLITE_AMALGAMATION
  82114. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  82115. #endif
  82116. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  82117. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  82118. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  82119. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  82120. /*
  82121. ** If the following function pointer is not NULL and if
  82122. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  82123. ** I/O active are written using this function. These messages
  82124. ** are intended for debugging activity only.
  82125. */
  82126. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  82127. #endif
  82128. /*
  82129. ** If the following global variable points to a string which is the
  82130. ** name of a directory, then that directory will be used to store
  82131. ** temporary files.
  82132. **
  82133. ** See also the "PRAGMA temp_store_directory" SQL command.
  82134. */
  82135. SQLITE_API char *sqlite3_temp_directory = 0;
  82136. /*
  82137. ** Initialize SQLite.
  82138. **
  82139. ** This routine must be called to initialize the memory allocation,
  82140. ** VFS, and mutex subsystems prior to doing any serious work with
  82141. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  82142. ** this routine will be called automatically by key routines such as
  82143. ** sqlite3_open().
  82144. **
  82145. ** This routine is a no-op except on its very first call for the process,
  82146. ** or for the first call after a call to sqlite3_shutdown.
  82147. **
  82148. ** The first thread to call this routine runs the initialization to
  82149. ** completion. If subsequent threads call this routine before the first
  82150. ** thread has finished the initialization process, then the subsequent
  82151. ** threads must block until the first thread finishes with the initialization.
  82152. **
  82153. ** The first thread might call this routine recursively. Recursive
  82154. ** calls to this routine should not block, of course. Otherwise the
  82155. ** initialization process would never complete.
  82156. **
  82157. ** Let X be the first thread to enter this routine. Let Y be some other
  82158. ** thread. Then while the initial invocation of this routine by X is
  82159. ** incomplete, it is required that:
  82160. **
  82161. ** * Calls to this routine from Y must block until the outer-most
  82162. ** call by X completes.
  82163. **
  82164. ** * Recursive calls to this routine from thread X return immediately
  82165. ** without blocking.
  82166. */
  82167. SQLITE_API int sqlite3_initialize(void){
  82168. sqlite3_mutex *pMaster; /* The main static mutex */
  82169. int rc; /* Result code */
  82170. #ifdef SQLITE_OMIT_WSD
  82171. rc = sqlite3_wsd_init(4096, 24);
  82172. if( rc!=SQLITE_OK ){
  82173. return rc;
  82174. }
  82175. #endif
  82176. /* If SQLite is already completely initialized, then this call
  82177. ** to sqlite3_initialize() should be a no-op. But the initialization
  82178. ** must be complete. So isInit must not be set until the very end
  82179. ** of this routine.
  82180. */
  82181. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  82182. /* Make sure the mutex subsystem is initialized. If unable to
  82183. ** initialize the mutex subsystem, return early with the error.
  82184. ** If the system is so sick that we are unable to allocate a mutex,
  82185. ** there is not much SQLite is going to be able to do.
  82186. **
  82187. ** The mutex subsystem must take care of serializing its own
  82188. ** initialization.
  82189. */
  82190. rc = sqlite3MutexInit();
  82191. if( rc ) return rc;
  82192. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  82193. ** This operation is protected by the STATIC_MASTER mutex. Note that
  82194. ** MutexAlloc() is called for a static mutex prior to initializing the
  82195. ** malloc subsystem - this implies that the allocation of a static
  82196. ** mutex must not require support from the malloc subsystem.
  82197. */
  82198. pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  82199. sqlite3_mutex_enter(pMaster);
  82200. if( !sqlite3GlobalConfig.isMallocInit ){
  82201. rc = sqlite3MallocInit();
  82202. }
  82203. if( rc==SQLITE_OK ){
  82204. sqlite3GlobalConfig.isMallocInit = 1;
  82205. if( !sqlite3GlobalConfig.pInitMutex ){
  82206. sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  82207. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  82208. rc = SQLITE_NOMEM;
  82209. }
  82210. }
  82211. }
  82212. if( rc==SQLITE_OK ){
  82213. sqlite3GlobalConfig.nRefInitMutex++;
  82214. }
  82215. sqlite3_mutex_leave(pMaster);
  82216. /* If unable to initialize the malloc subsystem, then return early.
  82217. ** There is little hope of getting SQLite to run if the malloc
  82218. ** subsystem cannot be initialized.
  82219. */
  82220. if( rc!=SQLITE_OK ){
  82221. return rc;
  82222. }
  82223. /* Do the rest of the initialization under the recursive mutex so
  82224. ** that we will be able to handle recursive calls into
  82225. ** sqlite3_initialize(). The recursive calls normally come through
  82226. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  82227. ** recursive calls might also be possible.
  82228. */
  82229. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  82230. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  82231. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  82232. sqlite3GlobalConfig.inProgress = 1;
  82233. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  82234. sqlite3RegisterGlobalFunctions();
  82235. rc = sqlite3_os_init();
  82236. if( rc==SQLITE_OK ){
  82237. rc = sqlite3PcacheInitialize();
  82238. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  82239. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  82240. }
  82241. sqlite3GlobalConfig.inProgress = 0;
  82242. sqlite3GlobalConfig.isInit = (rc==SQLITE_OK ? 1 : 0);
  82243. }
  82244. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  82245. /* Go back under the static mutex and clean up the recursive
  82246. ** mutex to prevent a resource leak.
  82247. */
  82248. sqlite3_mutex_enter(pMaster);
  82249. sqlite3GlobalConfig.nRefInitMutex--;
  82250. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  82251. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  82252. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  82253. sqlite3GlobalConfig.pInitMutex = 0;
  82254. }
  82255. sqlite3_mutex_leave(pMaster);
  82256. /* The following is just a sanity check to make sure SQLite has
  82257. ** been compiled correctly. It is important to run this code, but
  82258. ** we don't want to run it too often and soak up CPU cycles for no
  82259. ** reason. So we run it once during initialization.
  82260. */
  82261. #ifndef NDEBUG
  82262. /* This section of code's only "output" is via assert() statements. */
  82263. if ( rc==SQLITE_OK ){
  82264. u64 x = (((u64)1)<<63)-1;
  82265. double y;
  82266. assert(sizeof(x)==8);
  82267. assert(sizeof(x)==sizeof(y));
  82268. memcpy(&y, &x, 8);
  82269. assert( sqlite3IsNaN(y) );
  82270. }
  82271. #endif
  82272. return rc;
  82273. }
  82274. /*
  82275. ** Undo the effects of sqlite3_initialize(). Must not be called while
  82276. ** there are outstanding database connections or memory allocations or
  82277. ** while any part of SQLite is otherwise in use in any thread. This
  82278. ** routine is not threadsafe. Not by a long shot.
  82279. */
  82280. SQLITE_API int sqlite3_shutdown(void){
  82281. sqlite3GlobalConfig.isMallocInit = 0;
  82282. sqlite3PcacheShutdown();
  82283. if( sqlite3GlobalConfig.isInit ){
  82284. sqlite3_os_end();
  82285. }
  82286. sqlite3MallocEnd();
  82287. sqlite3MutexEnd();
  82288. sqlite3GlobalConfig.isInit = 0;
  82289. return SQLITE_OK;
  82290. }
  82291. /*
  82292. ** This API allows applications to modify the global configuration of
  82293. ** the SQLite library at run-time.
  82294. **
  82295. ** This routine should only be called when there are no outstanding
  82296. ** database connections or memory allocations. This routine is not
  82297. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  82298. ** behavior.
  82299. */
  82300. SQLITE_API int sqlite3_config(int op, ...){
  82301. va_list ap;
  82302. int rc = SQLITE_OK;
  82303. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  82304. ** the SQLite library is in use. */
  82305. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
  82306. va_start(ap, op);
  82307. switch( op ){
  82308. /* Mutex configuration options are only available in a threadsafe
  82309. ** compile.
  82310. */
  82311. #if SQLITE_THREADSAFE
  82312. case SQLITE_CONFIG_SINGLETHREAD: {
  82313. /* Disable all mutexing */
  82314. sqlite3GlobalConfig.bCoreMutex = 0;
  82315. sqlite3GlobalConfig.bFullMutex = 0;
  82316. break;
  82317. }
  82318. case SQLITE_CONFIG_MULTITHREAD: {
  82319. /* Disable mutexing of database connections */
  82320. /* Enable mutexing of core data structures */
  82321. sqlite3GlobalConfig.bCoreMutex = 1;
  82322. sqlite3GlobalConfig.bFullMutex = 0;
  82323. break;
  82324. }
  82325. case SQLITE_CONFIG_SERIALIZED: {
  82326. /* Enable all mutexing */
  82327. sqlite3GlobalConfig.bCoreMutex = 1;
  82328. sqlite3GlobalConfig.bFullMutex = 1;
  82329. break;
  82330. }
  82331. case SQLITE_CONFIG_MUTEX: {
  82332. /* Specify an alternative mutex implementation */
  82333. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  82334. break;
  82335. }
  82336. case SQLITE_CONFIG_GETMUTEX: {
  82337. /* Retrieve the current mutex implementation */
  82338. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  82339. break;
  82340. }
  82341. #endif
  82342. case SQLITE_CONFIG_MALLOC: {
  82343. /* Specify an alternative malloc implementation */
  82344. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  82345. break;
  82346. }
  82347. case SQLITE_CONFIG_GETMALLOC: {
  82348. /* Retrieve the current malloc() implementation */
  82349. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  82350. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  82351. break;
  82352. }
  82353. case SQLITE_CONFIG_MEMSTATUS: {
  82354. /* Enable or disable the malloc status collection */
  82355. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  82356. break;
  82357. }
  82358. case SQLITE_CONFIG_SCRATCH: {
  82359. /* Designate a buffer for scratch memory space */
  82360. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  82361. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  82362. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  82363. break;
  82364. }
  82365. case SQLITE_CONFIG_PAGECACHE: {
  82366. /* Designate a buffer for scratch memory space */
  82367. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  82368. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  82369. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  82370. break;
  82371. }
  82372. case SQLITE_CONFIG_PCACHE: {
  82373. /* Specify an alternative malloc implementation */
  82374. sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
  82375. break;
  82376. }
  82377. case SQLITE_CONFIG_GETPCACHE: {
  82378. if( sqlite3GlobalConfig.pcache.xInit==0 ){
  82379. sqlite3PCacheSetDefault();
  82380. }
  82381. *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
  82382. break;
  82383. }
  82384. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  82385. case SQLITE_CONFIG_HEAP: {
  82386. /* Designate a buffer for heap memory space */
  82387. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  82388. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  82389. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  82390. if( sqlite3GlobalConfig.pHeap==0 ){
  82391. /* If the heap pointer is NULL, then restore the malloc implementation
  82392. ** back to NULL pointers too. This will cause the malloc to go
  82393. ** back to its default implementation when sqlite3_initialize() is
  82394. ** run.
  82395. */
  82396. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  82397. }else{
  82398. /* The heap pointer is not NULL, then install one of the
  82399. ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
  82400. ** ENABLE_MEMSYS5 is defined, return an error.
  82401. ** the default case and return an error.
  82402. */
  82403. #ifdef SQLITE_ENABLE_MEMSYS3
  82404. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  82405. #endif
  82406. #ifdef SQLITE_ENABLE_MEMSYS5
  82407. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  82408. #endif
  82409. }
  82410. break;
  82411. }
  82412. #endif
  82413. case SQLITE_CONFIG_LOOKASIDE: {
  82414. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  82415. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  82416. break;
  82417. }
  82418. default: {
  82419. rc = SQLITE_ERROR;
  82420. break;
  82421. }
  82422. }
  82423. va_end(ap);
  82424. return rc;
  82425. }
  82426. /*
  82427. ** Set up the lookaside buffers for a database connection.
  82428. ** Return SQLITE_OK on success.
  82429. ** If lookaside is already active, return SQLITE_BUSY.
  82430. **
  82431. ** The sz parameter is the number of bytes in each lookaside slot.
  82432. ** The cnt parameter is the number of slots. If pStart is NULL the
  82433. ** space for the lookaside memory is obtained from sqlite3_malloc().
  82434. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  82435. ** the lookaside memory.
  82436. */
  82437. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  82438. void *pStart;
  82439. if( db->lookaside.nOut ){
  82440. return SQLITE_BUSY;
  82441. }
  82442. if( sz<0 ) sz = 0;
  82443. if( cnt<0 ) cnt = 0;
  82444. if( pBuf==0 ){
  82445. sz = (sz + 7)&~7;
  82446. sqlite3BeginBenignMalloc();
  82447. pStart = sqlite3Malloc( sz*cnt );
  82448. sqlite3EndBenignMalloc();
  82449. }else{
  82450. sz = sz&~7;
  82451. pStart = pBuf;
  82452. }
  82453. if( db->lookaside.bMalloced ){
  82454. sqlite3_free(db->lookaside.pStart);
  82455. }
  82456. db->lookaside.pStart = pStart;
  82457. db->lookaside.pFree = 0;
  82458. db->lookaside.sz = (u16)sz;
  82459. db->lookaside.bMalloced = pBuf==0 ?1:0;
  82460. if( pStart ){
  82461. int i;
  82462. LookasideSlot *p;
  82463. p = (LookasideSlot*)pStart;
  82464. for(i=cnt-1; i>=0; i--){
  82465. p->pNext = db->lookaside.pFree;
  82466. db->lookaside.pFree = p;
  82467. p = (LookasideSlot*)&((u8*)p)[sz];
  82468. }
  82469. db->lookaside.pEnd = p;
  82470. db->lookaside.bEnabled = 1;
  82471. }else{
  82472. db->lookaside.pEnd = 0;
  82473. db->lookaside.bEnabled = 0;
  82474. }
  82475. return SQLITE_OK;
  82476. }
  82477. /*
  82478. ** Return the mutex associated with a database connection.
  82479. */
  82480. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  82481. return db->mutex;
  82482. }
  82483. /*
  82484. ** Configuration settings for an individual database connection
  82485. */
  82486. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  82487. va_list ap;
  82488. int rc;
  82489. va_start(ap, op);
  82490. switch( op ){
  82491. case SQLITE_DBCONFIG_LOOKASIDE: {
  82492. void *pBuf = va_arg(ap, void*);
  82493. int sz = va_arg(ap, int);
  82494. int cnt = va_arg(ap, int);
  82495. rc = setupLookaside(db, pBuf, sz, cnt);
  82496. break;
  82497. }
  82498. default: {
  82499. rc = SQLITE_ERROR;
  82500. break;
  82501. }
  82502. }
  82503. va_end(ap);
  82504. return rc;
  82505. }
  82506. /*
  82507. ** Return true if the buffer z[0..n-1] contains all spaces.
  82508. */
  82509. static int allSpaces(const char *z, int n){
  82510. while( n>0 && z[n-1]==' ' ){ n--; }
  82511. return n==0;
  82512. }
  82513. /*
  82514. ** This is the default collating function named "BINARY" which is always
  82515. ** available.
  82516. **
  82517. ** If the padFlag argument is not NULL then space padding at the end
  82518. ** of strings is ignored. This implements the RTRIM collation.
  82519. */
  82520. static int binCollFunc(
  82521. void *padFlag,
  82522. int nKey1, const void *pKey1,
  82523. int nKey2, const void *pKey2
  82524. ){
  82525. int rc, n;
  82526. n = nKey1<nKey2 ? nKey1 : nKey2;
  82527. rc = memcmp(pKey1, pKey2, n);
  82528. if( rc==0 ){
  82529. if( padFlag
  82530. && allSpaces(((char*)pKey1)+n, nKey1-n)
  82531. && allSpaces(((char*)pKey2)+n, nKey2-n)
  82532. ){
  82533. /* Leave rc unchanged at 0 */
  82534. }else{
  82535. rc = nKey1 - nKey2;
  82536. }
  82537. }
  82538. return rc;
  82539. }
  82540. /*
  82541. ** Another built-in collating sequence: NOCASE.
  82542. **
  82543. ** This collating sequence is intended to be used for "case independant
  82544. ** comparison". SQLite's knowledge of upper and lower case equivalents
  82545. ** extends only to the 26 characters used in the English language.
  82546. **
  82547. ** At the moment there is only a UTF-8 implementation.
  82548. */
  82549. static int nocaseCollatingFunc(
  82550. void *NotUsed,
  82551. int nKey1, const void *pKey1,
  82552. int nKey2, const void *pKey2
  82553. ){
  82554. int r = sqlite3StrNICmp(
  82555. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  82556. UNUSED_PARAMETER(NotUsed);
  82557. if( 0==r ){
  82558. r = nKey1-nKey2;
  82559. }
  82560. return r;
  82561. }
  82562. /*
  82563. ** Return the ROWID of the most recent insert
  82564. */
  82565. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  82566. return db->lastRowid;
  82567. }
  82568. /*
  82569. ** Return the number of changes in the most recent call to sqlite3_exec().
  82570. */
  82571. SQLITE_API int sqlite3_changes(sqlite3 *db){
  82572. return db->nChange;
  82573. }
  82574. /*
  82575. ** Return the number of changes since the database handle was opened.
  82576. */
  82577. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  82578. return db->nTotalChange;
  82579. }
  82580. /*
  82581. ** Close all open savepoints. This function only manipulates fields of the
  82582. ** database handle object, it does not close any savepoints that may be open
  82583. ** at the b-tree/pager level.
  82584. */
  82585. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  82586. while( db->pSavepoint ){
  82587. Savepoint *pTmp = db->pSavepoint;
  82588. db->pSavepoint = pTmp->pNext;
  82589. sqlite3DbFree(db, pTmp);
  82590. }
  82591. db->nSavepoint = 0;
  82592. db->isTransactionSavepoint = 0;
  82593. }
  82594. /*
  82595. ** Close an existing SQLite database
  82596. */
  82597. SQLITE_API int sqlite3_close(sqlite3 *db){
  82598. HashElem *i;
  82599. int j;
  82600. if( !db ){
  82601. return SQLITE_OK;
  82602. }
  82603. if( !sqlite3SafetyCheckSickOrOk(db) ){
  82604. return SQLITE_MISUSE;
  82605. }
  82606. sqlite3_mutex_enter(db->mutex);
  82607. #ifdef SQLITE_SSE
  82608. {
  82609. extern void sqlite3SseCleanup(sqlite3*);
  82610. sqlite3SseCleanup(db);
  82611. }
  82612. #endif
  82613. sqlite3ResetInternalSchema(db, 0);
  82614. /* If a transaction is open, the ResetInternalSchema() call above
  82615. ** will not have called the xDisconnect() method on any virtual
  82616. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  82617. ** call will do so. We need to do this before the check for active
  82618. ** SQL statements below, as the v-table implementation may be storing
  82619. ** some prepared statements internally.
  82620. */
  82621. sqlite3VtabRollback(db);
  82622. /* If there are any outstanding VMs, return SQLITE_BUSY. */
  82623. if( db->pVdbe ){
  82624. sqlite3Error(db, SQLITE_BUSY,
  82625. "Unable to close due to unfinalised statements");
  82626. sqlite3_mutex_leave(db->mutex);
  82627. return SQLITE_BUSY;
  82628. }
  82629. assert( sqlite3SafetyCheckSickOrOk(db) );
  82630. /* Free any outstanding Savepoint structures. */
  82631. sqlite3CloseSavepoints(db);
  82632. for(j=0; j<db->nDb; j++){
  82633. struct Db *pDb = &db->aDb[j];
  82634. if( pDb->pBt ){
  82635. sqlite3BtreeClose(pDb->pBt);
  82636. pDb->pBt = 0;
  82637. if( j!=1 ){
  82638. pDb->pSchema = 0;
  82639. }
  82640. }
  82641. }
  82642. sqlite3ResetInternalSchema(db, 0);
  82643. assert( db->nDb<=2 );
  82644. assert( db->aDb==db->aDbStatic );
  82645. for(j=0; j<ArraySize(db->aFunc.a); j++){
  82646. FuncDef *pNext, *pHash, *p;
  82647. for(p=db->aFunc.a[j]; p; p=pHash){
  82648. pHash = p->pHash;
  82649. while( p ){
  82650. pNext = p->pNext;
  82651. sqlite3DbFree(db, p);
  82652. p = pNext;
  82653. }
  82654. }
  82655. }
  82656. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  82657. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  82658. /* Invoke any destructors registered for collation sequence user data. */
  82659. for(j=0; j<3; j++){
  82660. if( pColl[j].xDel ){
  82661. pColl[j].xDel(pColl[j].pUser);
  82662. }
  82663. }
  82664. sqlite3DbFree(db, pColl);
  82665. }
  82666. sqlite3HashClear(&db->aCollSeq);
  82667. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82668. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  82669. Module *pMod = (Module *)sqliteHashData(i);
  82670. if( pMod->xDestroy ){
  82671. pMod->xDestroy(pMod->pAux);
  82672. }
  82673. sqlite3DbFree(db, pMod);
  82674. }
  82675. sqlite3HashClear(&db->aModule);
  82676. #endif
  82677. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  82678. if( db->pErr ){
  82679. sqlite3ValueFree(db->pErr);
  82680. }
  82681. sqlite3CloseExtensions(db);
  82682. db->magic = SQLITE_MAGIC_ERROR;
  82683. /* The temp-database schema is allocated differently from the other schema
  82684. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  82685. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  82686. ** the same sqliteMalloc() as the one that allocates the database
  82687. ** structure?
  82688. */
  82689. sqlite3DbFree(db, db->aDb[1].pSchema);
  82690. sqlite3_mutex_leave(db->mutex);
  82691. db->magic = SQLITE_MAGIC_CLOSED;
  82692. sqlite3_mutex_free(db->mutex);
  82693. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  82694. if( db->lookaside.bMalloced ){
  82695. sqlite3_free(db->lookaside.pStart);
  82696. }
  82697. sqlite3_free(db);
  82698. return SQLITE_OK;
  82699. }
  82700. /*
  82701. ** Rollback all database files.
  82702. */
  82703. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
  82704. int i;
  82705. int inTrans = 0;
  82706. assert( sqlite3_mutex_held(db->mutex) );
  82707. sqlite3BeginBenignMalloc();
  82708. for(i=0; i<db->nDb; i++){
  82709. if( db->aDb[i].pBt ){
  82710. if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
  82711. inTrans = 1;
  82712. }
  82713. sqlite3BtreeRollback(db->aDb[i].pBt);
  82714. db->aDb[i].inTrans = 0;
  82715. }
  82716. }
  82717. sqlite3VtabRollback(db);
  82718. sqlite3EndBenignMalloc();
  82719. if( db->flags&SQLITE_InternChanges ){
  82720. sqlite3ExpirePreparedStatements(db);
  82721. sqlite3ResetInternalSchema(db, 0);
  82722. }
  82723. /* If one has been configured, invoke the rollback-hook callback */
  82724. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  82725. db->xRollbackCallback(db->pRollbackArg);
  82726. }
  82727. }
  82728. /*
  82729. ** Return a static string that describes the kind of error specified in the
  82730. ** argument.
  82731. */
  82732. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  82733. const char *z;
  82734. switch( rc & 0xff ){
  82735. case SQLITE_ROW:
  82736. case SQLITE_DONE:
  82737. case SQLITE_OK: z = "not an error"; break;
  82738. case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
  82739. case SQLITE_PERM: z = "access permission denied"; break;
  82740. case SQLITE_ABORT: z = "callback requested query abort"; break;
  82741. case SQLITE_BUSY: z = "database is locked"; break;
  82742. case SQLITE_LOCKED: z = "database table is locked"; break;
  82743. case SQLITE_NOMEM: z = "out of memory"; break;
  82744. case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
  82745. case SQLITE_INTERRUPT: z = "interrupted"; break;
  82746. case SQLITE_IOERR: z = "disk I/O error"; break;
  82747. case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
  82748. case SQLITE_FULL: z = "database or disk is full"; break;
  82749. case SQLITE_CANTOPEN: z = "unable to open database file"; break;
  82750. case SQLITE_EMPTY: z = "table contains no data"; break;
  82751. case SQLITE_SCHEMA: z = "database schema has changed"; break;
  82752. case SQLITE_TOOBIG: z = "String or BLOB exceeded size limit"; break;
  82753. case SQLITE_CONSTRAINT: z = "constraint failed"; break;
  82754. case SQLITE_MISMATCH: z = "datatype mismatch"; break;
  82755. case SQLITE_MISUSE: z = "library routine called out of sequence";break;
  82756. case SQLITE_NOLFS: z = "large file support is disabled"; break;
  82757. case SQLITE_AUTH: z = "authorization denied"; break;
  82758. case SQLITE_FORMAT: z = "auxiliary database format error"; break;
  82759. case SQLITE_RANGE: z = "bind or column index out of range"; break;
  82760. case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
  82761. default: z = "unknown error"; break;
  82762. }
  82763. return z;
  82764. }
  82765. /*
  82766. ** This routine implements a busy callback that sleeps and tries
  82767. ** again until a timeout value is reached. The timeout value is
  82768. ** an integer number of milliseconds passed in as the first
  82769. ** argument.
  82770. */
  82771. static int sqliteDefaultBusyCallback(
  82772. void *ptr, /* Database connection */
  82773. int count /* Number of times table has been busy */
  82774. ){
  82775. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  82776. static const u8 delays[] =
  82777. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  82778. static const u8 totals[] =
  82779. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  82780. # define NDELAY (sizeof(delays)/sizeof(delays[0]))
  82781. sqlite3 *db = (sqlite3 *)ptr;
  82782. int timeout = db->busyTimeout;
  82783. int delay, prior;
  82784. assert( count>=0 );
  82785. if( count < NDELAY ){
  82786. delay = delays[count];
  82787. prior = totals[count];
  82788. }else{
  82789. delay = delays[NDELAY-1];
  82790. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  82791. }
  82792. if( prior + delay > timeout ){
  82793. delay = timeout - prior;
  82794. if( delay<=0 ) return 0;
  82795. }
  82796. sqlite3OsSleep(db->pVfs, delay*1000);
  82797. return 1;
  82798. #else
  82799. sqlite3 *db = (sqlite3 *)ptr;
  82800. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  82801. if( (count+1)*1000 > timeout ){
  82802. return 0;
  82803. }
  82804. sqlite3OsSleep(db->pVfs, 1000000);
  82805. return 1;
  82806. #endif
  82807. }
  82808. /*
  82809. ** Invoke the given busy handler.
  82810. **
  82811. ** This routine is called when an operation failed with a lock.
  82812. ** If this routine returns non-zero, the lock is retried. If it
  82813. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  82814. */
  82815. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  82816. int rc;
  82817. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  82818. rc = p->xFunc(p->pArg, p->nBusy);
  82819. if( rc==0 ){
  82820. p->nBusy = -1;
  82821. }else{
  82822. p->nBusy++;
  82823. }
  82824. return rc;
  82825. }
  82826. /*
  82827. ** This routine sets the busy callback for an Sqlite database to the
  82828. ** given callback function with the given argument.
  82829. */
  82830. SQLITE_API int sqlite3_busy_handler(
  82831. sqlite3 *db,
  82832. int (*xBusy)(void*,int),
  82833. void *pArg
  82834. ){
  82835. sqlite3_mutex_enter(db->mutex);
  82836. db->busyHandler.xFunc = xBusy;
  82837. db->busyHandler.pArg = pArg;
  82838. db->busyHandler.nBusy = 0;
  82839. sqlite3_mutex_leave(db->mutex);
  82840. return SQLITE_OK;
  82841. }
  82842. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  82843. /*
  82844. ** This routine sets the progress callback for an Sqlite database to the
  82845. ** given callback function with the given argument. The progress callback will
  82846. ** be invoked every nOps opcodes.
  82847. */
  82848. SQLITE_API void sqlite3_progress_handler(
  82849. sqlite3 *db,
  82850. int nOps,
  82851. int (*xProgress)(void*),
  82852. void *pArg
  82853. ){
  82854. sqlite3_mutex_enter(db->mutex);
  82855. if( nOps>0 ){
  82856. db->xProgress = xProgress;
  82857. db->nProgressOps = nOps;
  82858. db->pProgressArg = pArg;
  82859. }else{
  82860. db->xProgress = 0;
  82861. db->nProgressOps = 0;
  82862. db->pProgressArg = 0;
  82863. }
  82864. sqlite3_mutex_leave(db->mutex);
  82865. }
  82866. #endif
  82867. /*
  82868. ** This routine installs a default busy handler that waits for the
  82869. ** specified number of milliseconds before returning 0.
  82870. */
  82871. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  82872. if( ms>0 ){
  82873. db->busyTimeout = ms;
  82874. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  82875. }else{
  82876. sqlite3_busy_handler(db, 0, 0);
  82877. }
  82878. return SQLITE_OK;
  82879. }
  82880. /*
  82881. ** Cause any pending operation to stop at its earliest opportunity.
  82882. */
  82883. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  82884. db->u1.isInterrupted = 1;
  82885. }
  82886. /*
  82887. ** This function is exactly the same as sqlite3_create_function(), except
  82888. ** that it is designed to be called by internal code. The difference is
  82889. ** that if a malloc() fails in sqlite3_create_function(), an error code
  82890. ** is returned and the mallocFailed flag cleared.
  82891. */
  82892. SQLITE_PRIVATE int sqlite3CreateFunc(
  82893. sqlite3 *db,
  82894. const char *zFunctionName,
  82895. int nArg,
  82896. int enc,
  82897. void *pUserData,
  82898. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  82899. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  82900. void (*xFinal)(sqlite3_context*)
  82901. ){
  82902. FuncDef *p;
  82903. int nName;
  82904. assert( sqlite3_mutex_held(db->mutex) );
  82905. if( zFunctionName==0 ||
  82906. (xFunc && (xFinal || xStep)) ||
  82907. (!xFunc && (xFinal && !xStep)) ||
  82908. (!xFunc && (!xFinal && xStep)) ||
  82909. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  82910. (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
  82911. sqlite3Error(db, SQLITE_ERROR, "bad parameters");
  82912. return SQLITE_ERROR;
  82913. }
  82914. #ifndef SQLITE_OMIT_UTF16
  82915. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  82916. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  82917. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  82918. **
  82919. ** If SQLITE_ANY is specified, add three versions of the function
  82920. ** to the hash table.
  82921. */
  82922. if( enc==SQLITE_UTF16 ){
  82923. enc = SQLITE_UTF16NATIVE;
  82924. }else if( enc==SQLITE_ANY ){
  82925. int rc;
  82926. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  82927. pUserData, xFunc, xStep, xFinal);
  82928. if( rc==SQLITE_OK ){
  82929. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  82930. pUserData, xFunc, xStep, xFinal);
  82931. }
  82932. if( rc!=SQLITE_OK ){
  82933. return rc;
  82934. }
  82935. enc = SQLITE_UTF16BE;
  82936. }
  82937. #else
  82938. enc = SQLITE_UTF8;
  82939. #endif
  82940. /* Check if an existing function is being overridden or deleted. If so,
  82941. ** and there are active VMs, then return SQLITE_BUSY. If a function
  82942. ** is being overridden/deleted but there are no active VMs, allow the
  82943. ** operation to continue but invalidate all precompiled statements.
  82944. */
  82945. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  82946. if( p && p->iPrefEnc==enc && p->nArg==nArg ){
  82947. if( db->activeVdbeCnt ){
  82948. sqlite3Error(db, SQLITE_BUSY,
  82949. "Unable to delete/modify user-function due to active statements");
  82950. assert( !db->mallocFailed );
  82951. return SQLITE_BUSY;
  82952. }else{
  82953. sqlite3ExpirePreparedStatements(db);
  82954. }
  82955. }
  82956. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  82957. assert(p || db->mallocFailed);
  82958. if( !p ){
  82959. return SQLITE_NOMEM;
  82960. }
  82961. p->flags = 0;
  82962. p->xFunc = xFunc;
  82963. p->xStep = xStep;
  82964. p->xFinalize = xFinal;
  82965. p->pUserData = pUserData;
  82966. p->nArg = (u16)nArg;
  82967. return SQLITE_OK;
  82968. }
  82969. /*
  82970. ** Create new user functions.
  82971. */
  82972. SQLITE_API int sqlite3_create_function(
  82973. sqlite3 *db,
  82974. const char *zFunctionName,
  82975. int nArg,
  82976. int enc,
  82977. void *p,
  82978. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  82979. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  82980. void (*xFinal)(sqlite3_context*)
  82981. ){
  82982. int rc;
  82983. sqlite3_mutex_enter(db->mutex);
  82984. rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
  82985. rc = sqlite3ApiExit(db, rc);
  82986. sqlite3_mutex_leave(db->mutex);
  82987. return rc;
  82988. }
  82989. #ifndef SQLITE_OMIT_UTF16
  82990. SQLITE_API int sqlite3_create_function16(
  82991. sqlite3 *db,
  82992. const void *zFunctionName,
  82993. int nArg,
  82994. int eTextRep,
  82995. void *p,
  82996. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  82997. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  82998. void (*xFinal)(sqlite3_context*)
  82999. ){
  83000. int rc;
  83001. char *zFunc8;
  83002. sqlite3_mutex_enter(db->mutex);
  83003. assert( !db->mallocFailed );
  83004. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
  83005. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
  83006. sqlite3DbFree(db, zFunc8);
  83007. rc = sqlite3ApiExit(db, rc);
  83008. sqlite3_mutex_leave(db->mutex);
  83009. return rc;
  83010. }
  83011. #endif
  83012. /*
  83013. ** Declare that a function has been overloaded by a virtual table.
  83014. **
  83015. ** If the function already exists as a regular global function, then
  83016. ** this routine is a no-op. If the function does not exist, then create
  83017. ** a new one that always throws a run-time error.
  83018. **
  83019. ** When virtual tables intend to provide an overloaded function, they
  83020. ** should call this routine to make sure the global function exists.
  83021. ** A global function must exist in order for name resolution to work
  83022. ** properly.
  83023. */
  83024. SQLITE_API int sqlite3_overload_function(
  83025. sqlite3 *db,
  83026. const char *zName,
  83027. int nArg
  83028. ){
  83029. int nName = sqlite3Strlen(db, zName);
  83030. int rc;
  83031. sqlite3_mutex_enter(db->mutex);
  83032. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  83033. sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  83034. 0, sqlite3InvalidFunction, 0, 0);
  83035. }
  83036. rc = sqlite3ApiExit(db, SQLITE_OK);
  83037. sqlite3_mutex_leave(db->mutex);
  83038. return rc;
  83039. }
  83040. #ifndef SQLITE_OMIT_TRACE
  83041. /*
  83042. ** Register a trace function. The pArg from the previously registered trace
  83043. ** is returned.
  83044. **
  83045. ** A NULL trace function means that no tracing is executes. A non-NULL
  83046. ** trace is a pointer to a function that is invoked at the start of each
  83047. ** SQL statement.
  83048. */
  83049. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  83050. void *pOld;
  83051. sqlite3_mutex_enter(db->mutex);
  83052. pOld = db->pTraceArg;
  83053. db->xTrace = xTrace;
  83054. db->pTraceArg = pArg;
  83055. sqlite3_mutex_leave(db->mutex);
  83056. return pOld;
  83057. }
  83058. /*
  83059. ** Register a profile function. The pArg from the previously registered
  83060. ** profile function is returned.
  83061. **
  83062. ** A NULL profile function means that no profiling is executes. A non-NULL
  83063. ** profile is a pointer to a function that is invoked at the conclusion of
  83064. ** each SQL statement that is run.
  83065. */
  83066. SQLITE_API void *sqlite3_profile(
  83067. sqlite3 *db,
  83068. void (*xProfile)(void*,const char*,sqlite_uint64),
  83069. void *pArg
  83070. ){
  83071. void *pOld;
  83072. sqlite3_mutex_enter(db->mutex);
  83073. pOld = db->pProfileArg;
  83074. db->xProfile = xProfile;
  83075. db->pProfileArg = pArg;
  83076. sqlite3_mutex_leave(db->mutex);
  83077. return pOld;
  83078. }
  83079. #endif /* SQLITE_OMIT_TRACE */
  83080. /*** EXPERIMENTAL ***
  83081. **
  83082. ** Register a function to be invoked when a transaction comments.
  83083. ** If the invoked function returns non-zero, then the commit becomes a
  83084. ** rollback.
  83085. */
  83086. SQLITE_API void *sqlite3_commit_hook(
  83087. sqlite3 *db, /* Attach the hook to this database */
  83088. int (*xCallback)(void*), /* Function to invoke on each commit */
  83089. void *pArg /* Argument to the function */
  83090. ){
  83091. void *pOld;
  83092. sqlite3_mutex_enter(db->mutex);
  83093. pOld = db->pCommitArg;
  83094. db->xCommitCallback = xCallback;
  83095. db->pCommitArg = pArg;
  83096. sqlite3_mutex_leave(db->mutex);
  83097. return pOld;
  83098. }
  83099. /*
  83100. ** Register a callback to be invoked each time a row is updated,
  83101. ** inserted or deleted using this database connection.
  83102. */
  83103. SQLITE_API void *sqlite3_update_hook(
  83104. sqlite3 *db, /* Attach the hook to this database */
  83105. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  83106. void *pArg /* Argument to the function */
  83107. ){
  83108. void *pRet;
  83109. sqlite3_mutex_enter(db->mutex);
  83110. pRet = db->pUpdateArg;
  83111. db->xUpdateCallback = xCallback;
  83112. db->pUpdateArg = pArg;
  83113. sqlite3_mutex_leave(db->mutex);
  83114. return pRet;
  83115. }
  83116. /*
  83117. ** Register a callback to be invoked each time a transaction is rolled
  83118. ** back by this database connection.
  83119. */
  83120. SQLITE_API void *sqlite3_rollback_hook(
  83121. sqlite3 *db, /* Attach the hook to this database */
  83122. void (*xCallback)(void*), /* Callback function */
  83123. void *pArg /* Argument to the function */
  83124. ){
  83125. void *pRet;
  83126. sqlite3_mutex_enter(db->mutex);
  83127. pRet = db->pRollbackArg;
  83128. db->xRollbackCallback = xCallback;
  83129. db->pRollbackArg = pArg;
  83130. sqlite3_mutex_leave(db->mutex);
  83131. return pRet;
  83132. }
  83133. /*
  83134. ** This routine is called to create a connection to a database BTree
  83135. ** driver. If zFilename is the name of a file, then that file is
  83136. ** opened and used. If zFilename is the magic name ":memory:" then
  83137. ** the database is stored in memory (and is thus forgotten as soon as
  83138. ** the connection is closed.) If zFilename is NULL then the database
  83139. ** is a "virtual" database for transient use only and is deleted as
  83140. ** soon as the connection is closed.
  83141. **
  83142. ** A virtual database can be either a disk file (that is automatically
  83143. ** deleted when the file is closed) or it an be held entirely in memory,
  83144. ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
  83145. ** db->temp_store variable, according to the following chart:
  83146. **
  83147. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  83148. ** ----------------- -------------- ------------------------------
  83149. ** 0 any file
  83150. ** 1 1 file
  83151. ** 1 2 memory
  83152. ** 1 0 file
  83153. ** 2 1 file
  83154. ** 2 2 memory
  83155. ** 2 0 memory
  83156. ** 3 any memory
  83157. */
  83158. SQLITE_PRIVATE int sqlite3BtreeFactory(
  83159. const sqlite3 *db, /* Main database when opening aux otherwise 0 */
  83160. const char *zFilename, /* Name of the file containing the BTree database */
  83161. int omitJournal, /* if TRUE then do not journal this file */
  83162. int nCache, /* How many pages in the page cache */
  83163. int vfsFlags, /* Flags passed through to vfsOpen */
  83164. Btree **ppBtree /* Pointer to new Btree object written here */
  83165. ){
  83166. int btFlags = 0;
  83167. int rc;
  83168. assert( sqlite3_mutex_held(db->mutex) );
  83169. assert( ppBtree != 0);
  83170. if( omitJournal ){
  83171. btFlags |= BTREE_OMIT_JOURNAL;
  83172. }
  83173. if( db->flags & SQLITE_NoReadlock ){
  83174. btFlags |= BTREE_NO_READLOCK;
  83175. }
  83176. if( zFilename==0 ){
  83177. #if SQLITE_TEMP_STORE==0
  83178. /* Do nothing */
  83179. #endif
  83180. #ifndef SQLITE_OMIT_MEMORYDB
  83181. #if SQLITE_TEMP_STORE==1
  83182. if( db->temp_store==2 ) zFilename = ":memory:";
  83183. #endif
  83184. #if SQLITE_TEMP_STORE==2
  83185. if( db->temp_store!=1 ) zFilename = ":memory:";
  83186. #endif
  83187. #if SQLITE_TEMP_STORE==3
  83188. zFilename = ":memory:";
  83189. #endif
  83190. #endif /* SQLITE_OMIT_MEMORYDB */
  83191. }
  83192. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
  83193. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  83194. }
  83195. rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
  83196. /* If the B-Tree was successfully opened, set the pager-cache size to the
  83197. ** default value. Except, if the call to BtreeOpen() returned a handle
  83198. ** open on an existing shared pager-cache, do not change the pager-cache
  83199. ** size.
  83200. */
  83201. if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
  83202. sqlite3BtreeSetCacheSize(*ppBtree, nCache);
  83203. }
  83204. return rc;
  83205. }
  83206. /*
  83207. ** Return UTF-8 encoded English language explanation of the most recent
  83208. ** error.
  83209. */
  83210. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  83211. const char *z;
  83212. if( !db ){
  83213. return sqlite3ErrStr(SQLITE_NOMEM);
  83214. }
  83215. if( !sqlite3SafetyCheckSickOrOk(db) ){
  83216. return sqlite3ErrStr(SQLITE_MISUSE);
  83217. }
  83218. if( db->mallocFailed ){
  83219. return sqlite3ErrStr(SQLITE_NOMEM);
  83220. }
  83221. sqlite3_mutex_enter(db->mutex);
  83222. assert( !db->mallocFailed );
  83223. z = (char*)sqlite3_value_text(db->pErr);
  83224. assert( !db->mallocFailed );
  83225. if( z==0 ){
  83226. z = sqlite3ErrStr(db->errCode);
  83227. }
  83228. sqlite3_mutex_leave(db->mutex);
  83229. return z;
  83230. }
  83231. #ifndef SQLITE_OMIT_UTF16
  83232. /*
  83233. ** Return UTF-16 encoded English language explanation of the most recent
  83234. ** error.
  83235. */
  83236. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  83237. /* Because all the characters in the string are in the unicode
  83238. ** range 0x00-0xFF, if we pad the big-endian string with a
  83239. ** zero byte, we can obtain the little-endian string with
  83240. ** &big_endian[1].
  83241. */
  83242. static const char outOfMemBe[] = {
  83243. 0, 'o', 0, 'u', 0, 't', 0, ' ',
  83244. 0, 'o', 0, 'f', 0, ' ',
  83245. 0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
  83246. };
  83247. static const char misuseBe [] = {
  83248. 0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ',
  83249. 0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ',
  83250. 0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ',
  83251. 0, 'o', 0, 'u', 0, 't', 0, ' ',
  83252. 0, 'o', 0, 'f', 0, ' ',
  83253. 0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
  83254. };
  83255. const void *z;
  83256. if( !db ){
  83257. return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
  83258. }
  83259. if( !sqlite3SafetyCheckSickOrOk(db) ){
  83260. return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
  83261. }
  83262. sqlite3_mutex_enter(db->mutex);
  83263. assert( !db->mallocFailed );
  83264. z = sqlite3_value_text16(db->pErr);
  83265. if( z==0 ){
  83266. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  83267. SQLITE_UTF8, SQLITE_STATIC);
  83268. z = sqlite3_value_text16(db->pErr);
  83269. }
  83270. /* A malloc() may have failed within the call to sqlite3_value_text16()
  83271. ** above. If this is the case, then the db->mallocFailed flag needs to
  83272. ** be cleared before returning. Do this directly, instead of via
  83273. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  83274. */
  83275. db->mallocFailed = 0;
  83276. sqlite3_mutex_leave(db->mutex);
  83277. return z;
  83278. }
  83279. #endif /* SQLITE_OMIT_UTF16 */
  83280. /*
  83281. ** Return the most recent error code generated by an SQLite routine. If NULL is
  83282. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  83283. */
  83284. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  83285. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  83286. return SQLITE_MISUSE;
  83287. }
  83288. if( !db || db->mallocFailed ){
  83289. return SQLITE_NOMEM;
  83290. }
  83291. return db->errCode & db->errMask;
  83292. }
  83293. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  83294. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  83295. return SQLITE_MISUSE;
  83296. }
  83297. if( !db || db->mallocFailed ){
  83298. return SQLITE_NOMEM;
  83299. }
  83300. return db->errCode;
  83301. }
  83302. /*
  83303. ** Create a new collating function for database "db". The name is zName
  83304. ** and the encoding is enc.
  83305. */
  83306. static int createCollation(
  83307. sqlite3* db,
  83308. const char *zName,
  83309. int enc,
  83310. void* pCtx,
  83311. int(*xCompare)(void*,int,const void*,int,const void*),
  83312. void(*xDel)(void*)
  83313. ){
  83314. CollSeq *pColl;
  83315. int enc2;
  83316. int nName;
  83317. assert( sqlite3_mutex_held(db->mutex) );
  83318. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  83319. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  83320. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  83321. */
  83322. enc2 = enc & ~SQLITE_UTF16_ALIGNED;
  83323. if( enc2==SQLITE_UTF16 ){
  83324. enc2 = SQLITE_UTF16NATIVE;
  83325. }
  83326. if( (enc2&~3)!=0 ){
  83327. return SQLITE_MISUSE;
  83328. }
  83329. /* Check if this call is removing or replacing an existing collation
  83330. ** sequence. If so, and there are active VMs, return busy. If there
  83331. ** are no active VMs, invalidate any pre-compiled statements.
  83332. */
  83333. nName = sqlite3Strlen(db, zName);
  83334. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
  83335. if( pColl && pColl->xCmp ){
  83336. if( db->activeVdbeCnt ){
  83337. sqlite3Error(db, SQLITE_BUSY,
  83338. "Unable to delete/modify collation sequence due to active statements");
  83339. return SQLITE_BUSY;
  83340. }
  83341. sqlite3ExpirePreparedStatements(db);
  83342. /* If collation sequence pColl was created directly by a call to
  83343. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  83344. ** then any copies made by synthCollSeq() need to be invalidated.
  83345. ** Also, collation destructor - CollSeq.xDel() - function may need
  83346. ** to be called.
  83347. */
  83348. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  83349. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  83350. int j;
  83351. for(j=0; j<3; j++){
  83352. CollSeq *p = &aColl[j];
  83353. if( p->enc==pColl->enc ){
  83354. if( p->xDel ){
  83355. p->xDel(p->pUser);
  83356. }
  83357. p->xCmp = 0;
  83358. }
  83359. }
  83360. }
  83361. }
  83362. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
  83363. if( pColl ){
  83364. pColl->xCmp = xCompare;
  83365. pColl->pUser = pCtx;
  83366. pColl->xDel = xDel;
  83367. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  83368. }
  83369. sqlite3Error(db, SQLITE_OK, 0);
  83370. return SQLITE_OK;
  83371. }
  83372. /*
  83373. ** This array defines hard upper bounds on limit values. The
  83374. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  83375. ** #defines in sqlite3.h.
  83376. */
  83377. static const int aHardLimit[] = {
  83378. SQLITE_MAX_LENGTH,
  83379. SQLITE_MAX_SQL_LENGTH,
  83380. SQLITE_MAX_COLUMN,
  83381. SQLITE_MAX_EXPR_DEPTH,
  83382. SQLITE_MAX_COMPOUND_SELECT,
  83383. SQLITE_MAX_VDBE_OP,
  83384. SQLITE_MAX_FUNCTION_ARG,
  83385. SQLITE_MAX_ATTACHED,
  83386. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  83387. SQLITE_MAX_VARIABLE_NUMBER,
  83388. };
  83389. /*
  83390. ** Make sure the hard limits are set to reasonable values
  83391. */
  83392. #if SQLITE_MAX_LENGTH<100
  83393. # error SQLITE_MAX_LENGTH must be at least 100
  83394. #endif
  83395. #if SQLITE_MAX_SQL_LENGTH<100
  83396. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  83397. #endif
  83398. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  83399. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  83400. #endif
  83401. #if SQLITE_MAX_COMPOUND_SELECT<2
  83402. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  83403. #endif
  83404. #if SQLITE_MAX_VDBE_OP<40
  83405. # error SQLITE_MAX_VDBE_OP must be at least 40
  83406. #endif
  83407. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  83408. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  83409. #endif
  83410. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
  83411. # error SQLITE_MAX_ATTACHED must be between 0 and 30
  83412. #endif
  83413. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  83414. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  83415. #endif
  83416. #if SQLITE_MAX_VARIABLE_NUMBER<1
  83417. # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
  83418. #endif
  83419. #if SQLITE_MAX_COLUMN>32767
  83420. # error SQLITE_MAX_COLUMN must not exceed 32767
  83421. #endif
  83422. /*
  83423. ** Change the value of a limit. Report the old value.
  83424. ** If an invalid limit index is supplied, report -1.
  83425. ** Make no changes but still report the old value if the
  83426. ** new limit is negative.
  83427. **
  83428. ** A new lower limit does not shrink existing constructs.
  83429. ** It merely prevents new constructs that exceed the limit
  83430. ** from forming.
  83431. */
  83432. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  83433. int oldLimit;
  83434. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  83435. return -1;
  83436. }
  83437. oldLimit = db->aLimit[limitId];
  83438. if( newLimit>=0 ){
  83439. if( newLimit>aHardLimit[limitId] ){
  83440. newLimit = aHardLimit[limitId];
  83441. }
  83442. db->aLimit[limitId] = newLimit;
  83443. }
  83444. return oldLimit;
  83445. }
  83446. /*
  83447. ** This routine does the work of opening a database on behalf of
  83448. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  83449. ** is UTF-8 encoded.
  83450. */
  83451. static int openDatabase(
  83452. const char *zFilename, /* Database filename UTF-8 encoded */
  83453. sqlite3 **ppDb, /* OUT: Returned database handle */
  83454. unsigned flags, /* Operational flags */
  83455. const char *zVfs /* Name of the VFS to use */
  83456. ){
  83457. sqlite3 *db;
  83458. int rc;
  83459. CollSeq *pColl;
  83460. int isThreadsafe;
  83461. #ifndef SQLITE_OMIT_AUTOINIT
  83462. rc = sqlite3_initialize();
  83463. if( rc ) return rc;
  83464. #endif
  83465. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  83466. isThreadsafe = 0;
  83467. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  83468. isThreadsafe = 0;
  83469. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  83470. isThreadsafe = 1;
  83471. }else{
  83472. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  83473. }
  83474. /* Remove harmful bits from the flags parameter */
  83475. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  83476. SQLITE_OPEN_MAIN_DB |
  83477. SQLITE_OPEN_TEMP_DB |
  83478. SQLITE_OPEN_TRANSIENT_DB |
  83479. SQLITE_OPEN_MAIN_JOURNAL |
  83480. SQLITE_OPEN_TEMP_JOURNAL |
  83481. SQLITE_OPEN_SUBJOURNAL |
  83482. SQLITE_OPEN_MASTER_JOURNAL |
  83483. SQLITE_OPEN_NOMUTEX |
  83484. SQLITE_OPEN_FULLMUTEX
  83485. );
  83486. /* Allocate the sqlite data structure */
  83487. db = sqlite3MallocZero( sizeof(sqlite3) );
  83488. if( db==0 ) goto opendb_out;
  83489. if( isThreadsafe ){
  83490. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  83491. if( db->mutex==0 ){
  83492. sqlite3_free(db);
  83493. db = 0;
  83494. goto opendb_out;
  83495. }
  83496. }
  83497. sqlite3_mutex_enter(db->mutex);
  83498. db->errMask = 0xff;
  83499. db->priorNewRowid = 0;
  83500. db->nDb = 2;
  83501. db->magic = SQLITE_MAGIC_BUSY;
  83502. db->aDb = db->aDbStatic;
  83503. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  83504. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  83505. db->autoCommit = 1;
  83506. db->nextAutovac = -1;
  83507. db->nextPagesize = 0;
  83508. db->flags |= SQLITE_ShortColNames
  83509. #if SQLITE_DEFAULT_FILE_FORMAT<4
  83510. | SQLITE_LegacyFileFmt
  83511. #endif
  83512. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  83513. | SQLITE_LoadExtension
  83514. #endif
  83515. ;
  83516. sqlite3HashInit(&db->aCollSeq, 0);
  83517. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83518. sqlite3HashInit(&db->aModule, 0);
  83519. #endif
  83520. db->pVfs = sqlite3_vfs_find(zVfs);
  83521. if( !db->pVfs ){
  83522. rc = SQLITE_ERROR;
  83523. sqlite3Error(db, rc, "no such vfs: %s", zVfs);
  83524. goto opendb_out;
  83525. }
  83526. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  83527. ** and UTF-16, so add a version for each to avoid any unnecessary
  83528. ** conversions. The only error that can occur here is a malloc() failure.
  83529. */
  83530. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  83531. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  83532. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  83533. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  83534. if( db->mallocFailed ){
  83535. goto opendb_out;
  83536. }
  83537. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
  83538. assert( db->pDfltColl!=0 );
  83539. /* Also add a UTF-8 case-insensitive collation sequence. */
  83540. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  83541. /* Set flags on the built-in collating sequences */
  83542. db->pDfltColl->type = SQLITE_COLL_BINARY;
  83543. pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
  83544. if( pColl ){
  83545. pColl->type = SQLITE_COLL_NOCASE;
  83546. }
  83547. /* Open the backend database driver */
  83548. db->openFlags = flags;
  83549. rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
  83550. flags | SQLITE_OPEN_MAIN_DB,
  83551. &db->aDb[0].pBt);
  83552. if( rc!=SQLITE_OK ){
  83553. if( rc==SQLITE_IOERR_NOMEM ){
  83554. rc = SQLITE_NOMEM;
  83555. }
  83556. sqlite3Error(db, rc, 0);
  83557. goto opendb_out;
  83558. }
  83559. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  83560. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  83561. /* The default safety_level for the main database is 'full'; for the temp
  83562. ** database it is 'NONE'. This matches the pager layer defaults.
  83563. */
  83564. db->aDb[0].zName = "main";
  83565. db->aDb[0].safety_level = 3;
  83566. #ifndef SQLITE_OMIT_TEMPDB
  83567. db->aDb[1].zName = "temp";
  83568. db->aDb[1].safety_level = 1;
  83569. #endif
  83570. db->magic = SQLITE_MAGIC_OPEN;
  83571. if( db->mallocFailed ){
  83572. goto opendb_out;
  83573. }
  83574. /* Register all built-in functions, but do not attempt to read the
  83575. ** database schema yet. This is delayed until the first time the database
  83576. ** is accessed.
  83577. */
  83578. sqlite3Error(db, SQLITE_OK, 0);
  83579. sqlite3RegisterBuiltinFunctions(db);
  83580. /* Load automatic extensions - extensions that have been registered
  83581. ** using the sqlite3_automatic_extension() API.
  83582. */
  83583. (void)sqlite3AutoLoadExtensions(db);
  83584. if( sqlite3_errcode(db)!=SQLITE_OK ){
  83585. goto opendb_out;
  83586. }
  83587. #ifdef SQLITE_ENABLE_FTS1
  83588. if( !db->mallocFailed ){
  83589. extern int sqlite3Fts1Init(sqlite3*);
  83590. rc = sqlite3Fts1Init(db);
  83591. }
  83592. #endif
  83593. #ifdef SQLITE_ENABLE_FTS2
  83594. if( !db->mallocFailed && rc==SQLITE_OK ){
  83595. extern int sqlite3Fts2Init(sqlite3*);
  83596. rc = sqlite3Fts2Init(db);
  83597. }
  83598. #endif
  83599. #ifdef SQLITE_ENABLE_FTS3
  83600. if( !db->mallocFailed && rc==SQLITE_OK ){
  83601. rc = sqlite3Fts3Init(db);
  83602. }
  83603. #endif
  83604. #ifdef SQLITE_ENABLE_ICU
  83605. if( !db->mallocFailed && rc==SQLITE_OK ){
  83606. rc = sqlite3IcuInit(db);
  83607. }
  83608. #endif
  83609. #ifdef SQLITE_ENABLE_RTREE
  83610. if( !db->mallocFailed && rc==SQLITE_OK){
  83611. rc = sqlite3RtreeInit(db);
  83612. }
  83613. #endif
  83614. sqlite3Error(db, rc, 0);
  83615. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  83616. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  83617. ** mode. Doing nothing at all also makes NORMAL the default.
  83618. */
  83619. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  83620. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  83621. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  83622. SQLITE_DEFAULT_LOCKING_MODE);
  83623. #endif
  83624. /* Enable the lookaside-malloc subsystem */
  83625. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  83626. sqlite3GlobalConfig.nLookaside);
  83627. opendb_out:
  83628. if( db ){
  83629. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  83630. sqlite3_mutex_leave(db->mutex);
  83631. }
  83632. rc = sqlite3_errcode(db);
  83633. if( rc==SQLITE_NOMEM ){
  83634. sqlite3_close(db);
  83635. db = 0;
  83636. }else if( rc!=SQLITE_OK ){
  83637. db->magic = SQLITE_MAGIC_SICK;
  83638. }
  83639. *ppDb = db;
  83640. return sqlite3ApiExit(0, rc);
  83641. }
  83642. /*
  83643. ** Open a new database handle.
  83644. */
  83645. SQLITE_API int sqlite3_open(
  83646. const char *zFilename,
  83647. sqlite3 **ppDb
  83648. ){
  83649. return openDatabase(zFilename, ppDb,
  83650. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  83651. }
  83652. SQLITE_API int sqlite3_open_v2(
  83653. const char *filename, /* Database filename (UTF-8) */
  83654. sqlite3 **ppDb, /* OUT: SQLite db handle */
  83655. int flags, /* Flags */
  83656. const char *zVfs /* Name of VFS module to use */
  83657. ){
  83658. return openDatabase(filename, ppDb, flags, zVfs);
  83659. }
  83660. #ifndef SQLITE_OMIT_UTF16
  83661. /*
  83662. ** Open a new database handle.
  83663. */
  83664. SQLITE_API int sqlite3_open16(
  83665. const void *zFilename,
  83666. sqlite3 **ppDb
  83667. ){
  83668. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  83669. sqlite3_value *pVal;
  83670. int rc;
  83671. assert( zFilename );
  83672. assert( ppDb );
  83673. *ppDb = 0;
  83674. #ifndef SQLITE_OMIT_AUTOINIT
  83675. rc = sqlite3_initialize();
  83676. if( rc ) return rc;
  83677. #endif
  83678. pVal = sqlite3ValueNew(0);
  83679. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  83680. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  83681. if( zFilename8 ){
  83682. rc = openDatabase(zFilename8, ppDb,
  83683. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  83684. assert( *ppDb || rc==SQLITE_NOMEM );
  83685. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  83686. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  83687. }
  83688. }else{
  83689. rc = SQLITE_NOMEM;
  83690. }
  83691. sqlite3ValueFree(pVal);
  83692. return sqlite3ApiExit(0, rc);
  83693. }
  83694. #endif /* SQLITE_OMIT_UTF16 */
  83695. /*
  83696. ** Register a new collation sequence with the database handle db.
  83697. */
  83698. SQLITE_API int sqlite3_create_collation(
  83699. sqlite3* db,
  83700. const char *zName,
  83701. int enc,
  83702. void* pCtx,
  83703. int(*xCompare)(void*,int,const void*,int,const void*)
  83704. ){
  83705. int rc;
  83706. sqlite3_mutex_enter(db->mutex);
  83707. assert( !db->mallocFailed );
  83708. rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
  83709. rc = sqlite3ApiExit(db, rc);
  83710. sqlite3_mutex_leave(db->mutex);
  83711. return rc;
  83712. }
  83713. /*
  83714. ** Register a new collation sequence with the database handle db.
  83715. */
  83716. SQLITE_API int sqlite3_create_collation_v2(
  83717. sqlite3* db,
  83718. const char *zName,
  83719. int enc,
  83720. void* pCtx,
  83721. int(*xCompare)(void*,int,const void*,int,const void*),
  83722. void(*xDel)(void*)
  83723. ){
  83724. int rc;
  83725. sqlite3_mutex_enter(db->mutex);
  83726. assert( !db->mallocFailed );
  83727. rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
  83728. rc = sqlite3ApiExit(db, rc);
  83729. sqlite3_mutex_leave(db->mutex);
  83730. return rc;
  83731. }
  83732. #ifndef SQLITE_OMIT_UTF16
  83733. /*
  83734. ** Register a new collation sequence with the database handle db.
  83735. */
  83736. SQLITE_API int sqlite3_create_collation16(
  83737. sqlite3* db,
  83738. const void *zName,
  83739. int enc,
  83740. void* pCtx,
  83741. int(*xCompare)(void*,int,const void*,int,const void*)
  83742. ){
  83743. int rc = SQLITE_OK;
  83744. char *zName8;
  83745. sqlite3_mutex_enter(db->mutex);
  83746. assert( !db->mallocFailed );
  83747. zName8 = sqlite3Utf16to8(db, zName, -1);
  83748. if( zName8 ){
  83749. rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
  83750. sqlite3DbFree(db, zName8);
  83751. }
  83752. rc = sqlite3ApiExit(db, rc);
  83753. sqlite3_mutex_leave(db->mutex);
  83754. return rc;
  83755. }
  83756. #endif /* SQLITE_OMIT_UTF16 */
  83757. /*
  83758. ** Register a collation sequence factory callback with the database handle
  83759. ** db. Replace any previously installed collation sequence factory.
  83760. */
  83761. SQLITE_API int sqlite3_collation_needed(
  83762. sqlite3 *db,
  83763. void *pCollNeededArg,
  83764. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  83765. ){
  83766. sqlite3_mutex_enter(db->mutex);
  83767. db->xCollNeeded = xCollNeeded;
  83768. db->xCollNeeded16 = 0;
  83769. db->pCollNeededArg = pCollNeededArg;
  83770. sqlite3_mutex_leave(db->mutex);
  83771. return SQLITE_OK;
  83772. }
  83773. #ifndef SQLITE_OMIT_UTF16
  83774. /*
  83775. ** Register a collation sequence factory callback with the database handle
  83776. ** db. Replace any previously installed collation sequence factory.
  83777. */
  83778. SQLITE_API int sqlite3_collation_needed16(
  83779. sqlite3 *db,
  83780. void *pCollNeededArg,
  83781. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  83782. ){
  83783. sqlite3_mutex_enter(db->mutex);
  83784. db->xCollNeeded = 0;
  83785. db->xCollNeeded16 = xCollNeeded16;
  83786. db->pCollNeededArg = pCollNeededArg;
  83787. sqlite3_mutex_leave(db->mutex);
  83788. return SQLITE_OK;
  83789. }
  83790. #endif /* SQLITE_OMIT_UTF16 */
  83791. #ifndef SQLITE_OMIT_GLOBALRECOVER
  83792. #ifndef SQLITE_OMIT_DEPRECATED
  83793. /*
  83794. ** This function is now an anachronism. It used to be used to recover from a
  83795. ** malloc() failure, but SQLite now does this automatically.
  83796. */
  83797. SQLITE_API int sqlite3_global_recover(void){
  83798. return SQLITE_OK;
  83799. }
  83800. #endif
  83801. #endif
  83802. /*
  83803. ** Test to see whether or not the database connection is in autocommit
  83804. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  83805. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  83806. ** by the next COMMIT or ROLLBACK.
  83807. **
  83808. ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  83809. */
  83810. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  83811. return db->autoCommit;
  83812. }
  83813. #ifdef SQLITE_DEBUG
  83814. /*
  83815. ** The following routine is subtituted for constant SQLITE_CORRUPT in
  83816. ** debugging builds. This provides a way to set a breakpoint for when
  83817. ** corruption is first detected.
  83818. */
  83819. SQLITE_PRIVATE int sqlite3Corrupt(void){
  83820. return SQLITE_CORRUPT;
  83821. }
  83822. #endif
  83823. #ifndef SQLITE_OMIT_DEPRECATED
  83824. /*
  83825. ** This is a convenience routine that makes sure that all thread-specific
  83826. ** data for this thread has been deallocated.
  83827. **
  83828. ** SQLite no longer uses thread-specific data so this routine is now a
  83829. ** no-op. It is retained for historical compatibility.
  83830. */
  83831. SQLITE_API void sqlite3_thread_cleanup(void){
  83832. }
  83833. #endif
  83834. /*
  83835. ** Return meta information about a specific column of a database table.
  83836. ** See comment in sqlite3.h (sqlite.h.in) for details.
  83837. */
  83838. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  83839. SQLITE_API int sqlite3_table_column_metadata(
  83840. sqlite3 *db, /* Connection handle */
  83841. const char *zDbName, /* Database name or NULL */
  83842. const char *zTableName, /* Table name */
  83843. const char *zColumnName, /* Column name */
  83844. char const **pzDataType, /* OUTPUT: Declared data type */
  83845. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  83846. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  83847. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  83848. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  83849. ){
  83850. int rc;
  83851. char *zErrMsg = 0;
  83852. Table *pTab = 0;
  83853. Column *pCol = 0;
  83854. int iCol;
  83855. char const *zDataType = 0;
  83856. char const *zCollSeq = 0;
  83857. int notnull = 0;
  83858. int primarykey = 0;
  83859. int autoinc = 0;
  83860. /* Ensure the database schema has been loaded */
  83861. sqlite3_mutex_enter(db->mutex);
  83862. (void)sqlite3SafetyOn(db);
  83863. sqlite3BtreeEnterAll(db);
  83864. rc = sqlite3Init(db, &zErrMsg);
  83865. sqlite3BtreeLeaveAll(db);
  83866. if( SQLITE_OK!=rc ){
  83867. goto error_out;
  83868. }
  83869. /* Locate the table in question */
  83870. pTab = sqlite3FindTable(db, zTableName, zDbName);
  83871. if( !pTab || pTab->pSelect ){
  83872. pTab = 0;
  83873. goto error_out;
  83874. }
  83875. /* Find the column for which info is requested */
  83876. if( sqlite3IsRowid(zColumnName) ){
  83877. iCol = pTab->iPKey;
  83878. if( iCol>=0 ){
  83879. pCol = &pTab->aCol[iCol];
  83880. }
  83881. }else{
  83882. for(iCol=0; iCol<pTab->nCol; iCol++){
  83883. pCol = &pTab->aCol[iCol];
  83884. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  83885. break;
  83886. }
  83887. }
  83888. if( iCol==pTab->nCol ){
  83889. pTab = 0;
  83890. goto error_out;
  83891. }
  83892. }
  83893. /* The following block stores the meta information that will be returned
  83894. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  83895. ** and autoinc. At this point there are two possibilities:
  83896. **
  83897. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  83898. ** and there is no explicitly declared IPK column.
  83899. **
  83900. ** 2. The table is not a view and the column name identified an
  83901. ** explicitly declared column. Copy meta information from *pCol.
  83902. */
  83903. if( pCol ){
  83904. zDataType = pCol->zType;
  83905. zCollSeq = pCol->zColl;
  83906. notnull = pCol->notNull!=0;
  83907. primarykey = pCol->isPrimKey!=0;
  83908. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  83909. }else{
  83910. zDataType = "INTEGER";
  83911. primarykey = 1;
  83912. }
  83913. if( !zCollSeq ){
  83914. zCollSeq = "BINARY";
  83915. }
  83916. error_out:
  83917. (void)sqlite3SafetyOff(db);
  83918. /* Whether the function call succeeded or failed, set the output parameters
  83919. ** to whatever their local counterparts contain. If an error did occur,
  83920. ** this has the effect of zeroing all output parameters.
  83921. */
  83922. if( pzDataType ) *pzDataType = zDataType;
  83923. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  83924. if( pNotNull ) *pNotNull = notnull;
  83925. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  83926. if( pAutoinc ) *pAutoinc = autoinc;
  83927. if( SQLITE_OK==rc && !pTab ){
  83928. sqlite3DbFree(db, zErrMsg);
  83929. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  83930. zColumnName);
  83931. rc = SQLITE_ERROR;
  83932. }
  83933. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  83934. sqlite3DbFree(db, zErrMsg);
  83935. rc = sqlite3ApiExit(db, rc);
  83936. sqlite3_mutex_leave(db->mutex);
  83937. return rc;
  83938. }
  83939. #endif
  83940. /*
  83941. ** Sleep for a little while. Return the amount of time slept.
  83942. */
  83943. SQLITE_API int sqlite3_sleep(int ms){
  83944. sqlite3_vfs *pVfs;
  83945. int rc;
  83946. pVfs = sqlite3_vfs_find(0);
  83947. if( pVfs==0 ) return 0;
  83948. /* This function works in milliseconds, but the underlying OsSleep()
  83949. ** API uses microseconds. Hence the 1000's.
  83950. */
  83951. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  83952. return rc;
  83953. }
  83954. /*
  83955. ** Enable or disable the extended result codes.
  83956. */
  83957. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  83958. sqlite3_mutex_enter(db->mutex);
  83959. db->errMask = onoff ? 0xffffffff : 0xff;
  83960. sqlite3_mutex_leave(db->mutex);
  83961. return SQLITE_OK;
  83962. }
  83963. /*
  83964. ** Invoke the xFileControl method on a particular database.
  83965. */
  83966. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  83967. int rc = SQLITE_ERROR;
  83968. int iDb;
  83969. sqlite3_mutex_enter(db->mutex);
  83970. if( zDbName==0 ){
  83971. iDb = 0;
  83972. }else{
  83973. for(iDb=0; iDb<db->nDb; iDb++){
  83974. if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
  83975. }
  83976. }
  83977. if( iDb<db->nDb ){
  83978. Btree *pBtree = db->aDb[iDb].pBt;
  83979. if( pBtree ){
  83980. Pager *pPager;
  83981. sqlite3_file *fd;
  83982. sqlite3BtreeEnter(pBtree);
  83983. pPager = sqlite3BtreePager(pBtree);
  83984. assert( pPager!=0 );
  83985. fd = sqlite3PagerFile(pPager);
  83986. assert( fd!=0 );
  83987. if( fd->pMethods ){
  83988. rc = sqlite3OsFileControl(fd, op, pArg);
  83989. }
  83990. sqlite3BtreeLeave(pBtree);
  83991. }
  83992. }
  83993. sqlite3_mutex_leave(db->mutex);
  83994. return rc;
  83995. }
  83996. /*
  83997. ** Interface to the testing logic.
  83998. */
  83999. SQLITE_API int sqlite3_test_control(int op, ...){
  84000. int rc = 0;
  84001. #ifndef SQLITE_OMIT_BUILTIN_TEST
  84002. va_list ap;
  84003. va_start(ap, op);
  84004. switch( op ){
  84005. /*
  84006. ** Save the current state of the PRNG.
  84007. */
  84008. case SQLITE_TESTCTRL_PRNG_SAVE: {
  84009. sqlite3PrngSaveState();
  84010. break;
  84011. }
  84012. /*
  84013. ** Restore the state of the PRNG to the last state saved using
  84014. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  84015. ** this verb acts like PRNG_RESET.
  84016. */
  84017. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  84018. sqlite3PrngRestoreState();
  84019. break;
  84020. }
  84021. /*
  84022. ** Reset the PRNG back to its uninitialized state. The next call
  84023. ** to sqlite3_randomness() will reseed the PRNG using a single call
  84024. ** to the xRandomness method of the default VFS.
  84025. */
  84026. case SQLITE_TESTCTRL_PRNG_RESET: {
  84027. sqlite3PrngResetState();
  84028. break;
  84029. }
  84030. /*
  84031. ** sqlite3_test_control(BITVEC_TEST, size, program)
  84032. **
  84033. ** Run a test against a Bitvec object of size. The program argument
  84034. ** is an array of integers that defines the test. Return -1 on a
  84035. ** memory allocation error, 0 on success, or non-zero for an error.
  84036. ** See the sqlite3BitvecBuiltinTest() for additional information.
  84037. */
  84038. case SQLITE_TESTCTRL_BITVEC_TEST: {
  84039. int sz = va_arg(ap, int);
  84040. int *aProg = va_arg(ap, int*);
  84041. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  84042. break;
  84043. }
  84044. /*
  84045. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  84046. **
  84047. ** Register hooks to call to indicate which malloc() failures
  84048. ** are benign.
  84049. */
  84050. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  84051. typedef void (*void_function)(void);
  84052. void_function xBenignBegin;
  84053. void_function xBenignEnd;
  84054. xBenignBegin = va_arg(ap, void_function);
  84055. xBenignEnd = va_arg(ap, void_function);
  84056. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  84057. break;
  84058. }
  84059. }
  84060. va_end(ap);
  84061. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  84062. return rc;
  84063. }
  84064. /************** End of main.c ************************************************/
  84065. /************** Begin file fts3.c ********************************************/
  84066. /*
  84067. ** 2006 Oct 10
  84068. **
  84069. ** The author disclaims copyright to this source code. In place of
  84070. ** a legal notice, here is a blessing:
  84071. **
  84072. ** May you do good and not evil.
  84073. ** May you find forgiveness for yourself and forgive others.
  84074. ** May you share freely, never taking more than you give.
  84075. **
  84076. ******************************************************************************
  84077. **
  84078. ** This is an SQLite module implementing full-text search.
  84079. */
  84080. /*
  84081. ** The code in this file is only compiled if:
  84082. **
  84083. ** * The FTS3 module is being built as an extension
  84084. ** (in which case SQLITE_CORE is not defined), or
  84085. **
  84086. ** * The FTS3 module is being built into the core of
  84087. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  84088. */
  84089. /* TODO(shess) Consider exporting this comment to an HTML file or the
  84090. ** wiki.
  84091. */
  84092. /* The full-text index is stored in a series of b+tree (-like)
  84093. ** structures called segments which map terms to doclists. The
  84094. ** structures are like b+trees in layout, but are constructed from the
  84095. ** bottom up in optimal fashion and are not updatable. Since trees
  84096. ** are built from the bottom up, things will be described from the
  84097. ** bottom up.
  84098. **
  84099. **
  84100. **** Varints ****
  84101. ** The basic unit of encoding is a variable-length integer called a
  84102. ** varint. We encode variable-length integers in little-endian order
  84103. ** using seven bits * per byte as follows:
  84104. **
  84105. ** KEY:
  84106. ** A = 0xxxxxxx 7 bits of data and one flag bit
  84107. ** B = 1xxxxxxx 7 bits of data and one flag bit
  84108. **
  84109. ** 7 bits - A
  84110. ** 14 bits - BA
  84111. ** 21 bits - BBA
  84112. ** and so on.
  84113. **
  84114. ** This is identical to how sqlite encodes varints (see util.c).
  84115. **
  84116. **
  84117. **** Document lists ****
  84118. ** A doclist (document list) holds a docid-sorted list of hits for a
  84119. ** given term. Doclists hold docids, and can optionally associate
  84120. ** token positions and offsets with docids.
  84121. **
  84122. ** A DL_POSITIONS_OFFSETS doclist is stored like this:
  84123. **
  84124. ** array {
  84125. ** varint docid;
  84126. ** array { (position list for column 0)
  84127. ** varint position; (delta from previous position plus POS_BASE)
  84128. ** varint startOffset; (delta from previous startOffset)
  84129. ** varint endOffset; (delta from startOffset)
  84130. ** }
  84131. ** array {
  84132. ** varint POS_COLUMN; (marks start of position list for new column)
  84133. ** varint column; (index of new column)
  84134. ** array {
  84135. ** varint position; (delta from previous position plus POS_BASE)
  84136. ** varint startOffset;(delta from previous startOffset)
  84137. ** varint endOffset; (delta from startOffset)
  84138. ** }
  84139. ** }
  84140. ** varint POS_END; (marks end of positions for this document.
  84141. ** }
  84142. **
  84143. ** Here, array { X } means zero or more occurrences of X, adjacent in
  84144. ** memory. A "position" is an index of a token in the token stream
  84145. ** generated by the tokenizer, while an "offset" is a byte offset,
  84146. ** both based at 0. Note that POS_END and POS_COLUMN occur in the
  84147. ** same logical place as the position element, and act as sentinals
  84148. ** ending a position list array.
  84149. **
  84150. ** A DL_POSITIONS doclist omits the startOffset and endOffset
  84151. ** information. A DL_DOCIDS doclist omits both the position and
  84152. ** offset information, becoming an array of varint-encoded docids.
  84153. **
  84154. ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
  84155. ** the type. Due to how deletion is implemented in the segmentation
  84156. ** system, on-disk doclists MUST store at least positions.
  84157. **
  84158. **
  84159. **** Segment leaf nodes ****
  84160. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  84161. ** nodes are written using LeafWriter, and read using LeafReader (to
  84162. ** iterate through a single leaf node's data) and LeavesReader (to
  84163. ** iterate through a segment's entire leaf layer). Leaf nodes have
  84164. ** the format:
  84165. **
  84166. ** varint iHeight; (height from leaf level, always 0)
  84167. ** varint nTerm; (length of first term)
  84168. ** char pTerm[nTerm]; (content of first term)
  84169. ** varint nDoclist; (length of term's associated doclist)
  84170. ** char pDoclist[nDoclist]; (content of doclist)
  84171. ** array {
  84172. ** (further terms are delta-encoded)
  84173. ** varint nPrefix; (length of prefix shared with previous term)
  84174. ** varint nSuffix; (length of unshared suffix)
  84175. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  84176. ** varint nDoclist; (length of term's associated doclist)
  84177. ** char pDoclist[nDoclist]; (content of doclist)
  84178. ** }
  84179. **
  84180. ** Here, array { X } means zero or more occurrences of X, adjacent in
  84181. ** memory.
  84182. **
  84183. ** Leaf nodes are broken into blocks which are stored contiguously in
  84184. ** the %_segments table in sorted order. This means that when the end
  84185. ** of a node is reached, the next term is in the node with the next
  84186. ** greater node id.
  84187. **
  84188. ** New data is spilled to a new leaf node when the current node
  84189. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  84190. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  84191. ** node (a leaf node with a single term and doclist). The goal of
  84192. ** these settings is to pack together groups of small doclists while
  84193. ** making it efficient to directly access large doclists. The
  84194. ** assumption is that large doclists represent terms which are more
  84195. ** likely to be query targets.
  84196. **
  84197. ** TODO(shess) It may be useful for blocking decisions to be more
  84198. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  84199. ** node rather than splitting into 2k and .5k nodes. My intuition is
  84200. ** that this might extend through 2x or 4x the pagesize.
  84201. **
  84202. **
  84203. **** Segment interior nodes ****
  84204. ** Segment interior nodes store blockids for subtree nodes and terms
  84205. ** to describe what data is stored by the each subtree. Interior
  84206. ** nodes are written using InteriorWriter, and read using
  84207. ** InteriorReader. InteriorWriters are created as needed when
  84208. ** SegmentWriter creates new leaf nodes, or when an interior node
  84209. ** itself grows too big and must be split. The format of interior
  84210. ** nodes:
  84211. **
  84212. ** varint iHeight; (height from leaf level, always >0)
  84213. ** varint iBlockid; (block id of node's leftmost subtree)
  84214. ** optional {
  84215. ** varint nTerm; (length of first term)
  84216. ** char pTerm[nTerm]; (content of first term)
  84217. ** array {
  84218. ** (further terms are delta-encoded)
  84219. ** varint nPrefix; (length of shared prefix with previous term)
  84220. ** varint nSuffix; (length of unshared suffix)
  84221. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  84222. ** }
  84223. ** }
  84224. **
  84225. ** Here, optional { X } means an optional element, while array { X }
  84226. ** means zero or more occurrences of X, adjacent in memory.
  84227. **
  84228. ** An interior node encodes n terms separating n+1 subtrees. The
  84229. ** subtree blocks are contiguous, so only the first subtree's blockid
  84230. ** is encoded. The subtree at iBlockid will contain all terms less
  84231. ** than the first term encoded (or all terms if no term is encoded).
  84232. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  84233. ** than pTerm[i+1], the subtree for that term will be rooted at
  84234. ** iBlockid+i. Interior nodes only store enough term data to
  84235. ** distinguish adjacent children (if the rightmost term of the left
  84236. ** child is "something", and the leftmost term of the right child is
  84237. ** "wicked", only "w" is stored).
  84238. **
  84239. ** New data is spilled to a new interior node at the same height when
  84240. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  84241. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  84242. ** interior nodes and making the tree too skinny. The interior nodes
  84243. ** at a given height are naturally tracked by interior nodes at
  84244. ** height+1, and so on.
  84245. **
  84246. **
  84247. **** Segment directory ****
  84248. ** The segment directory in table %_segdir stores meta-information for
  84249. ** merging and deleting segments, and also the root node of the
  84250. ** segment's tree.
  84251. **
  84252. ** The root node is the top node of the segment's tree after encoding
  84253. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  84254. ** This could be either a leaf node or an interior node. If the top
  84255. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  84256. ** and a new root interior node is generated (which should always fit
  84257. ** within ROOT_MAX because it only needs space for 2 varints, the
  84258. ** height and the blockid of the previous root).
  84259. **
  84260. ** The meta-information in the segment directory is:
  84261. ** level - segment level (see below)
  84262. ** idx - index within level
  84263. ** - (level,idx uniquely identify a segment)
  84264. ** start_block - first leaf node
  84265. ** leaves_end_block - last leaf node
  84266. ** end_block - last block (including interior nodes)
  84267. ** root - contents of root node
  84268. **
  84269. ** If the root node is a leaf node, then start_block,
  84270. ** leaves_end_block, and end_block are all 0.
  84271. **
  84272. **
  84273. **** Segment merging ****
  84274. ** To amortize update costs, segments are grouped into levels and
  84275. ** merged in batches. Each increase in level represents exponentially
  84276. ** more documents.
  84277. **
  84278. ** New documents (actually, document updates) are tokenized and
  84279. ** written individually (using LeafWriter) to a level 0 segment, with
  84280. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  84281. ** level 0 segments are merged into a single level 1 segment. Level 1
  84282. ** is populated like level 0, and eventually MERGE_COUNT level 1
  84283. ** segments are merged to a single level 2 segment (representing
  84284. ** MERGE_COUNT^2 updates), and so on.
  84285. **
  84286. ** A segment merge traverses all segments at a given level in
  84287. ** parallel, performing a straightforward sorted merge. Since segment
  84288. ** leaf nodes are written in to the %_segments table in order, this
  84289. ** merge traverses the underlying sqlite disk structures efficiently.
  84290. ** After the merge, all segment blocks from the merged level are
  84291. ** deleted.
  84292. **
  84293. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  84294. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  84295. ** very similar performance numbers to 16 on insertion, though they're
  84296. ** a tiny bit slower (perhaps due to more overhead in merge-time
  84297. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  84298. ** 16, 2 about 66% slower than 16.
  84299. **
  84300. ** At query time, high MERGE_COUNT increases the number of segments
  84301. ** which need to be scanned and merged. For instance, with 100k docs
  84302. ** inserted:
  84303. **
  84304. ** MERGE_COUNT segments
  84305. ** 16 25
  84306. ** 8 12
  84307. ** 4 10
  84308. ** 2 6
  84309. **
  84310. ** This appears to have only a moderate impact on queries for very
  84311. ** frequent terms (which are somewhat dominated by segment merge
  84312. ** costs), and infrequent and non-existent terms still seem to be fast
  84313. ** even with many segments.
  84314. **
  84315. ** TODO(shess) That said, it would be nice to have a better query-side
  84316. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  84317. ** optimizations to things like doclist merging will swing the sweet
  84318. ** spot around.
  84319. **
  84320. **
  84321. **
  84322. **** Handling of deletions and updates ****
  84323. ** Since we're using a segmented structure, with no docid-oriented
  84324. ** index into the term index, we clearly cannot simply update the term
  84325. ** index when a document is deleted or updated. For deletions, we
  84326. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  84327. ** we simply write the new doclist. Segment merges overwrite older
  84328. ** data for a particular docid with newer data, so deletes or updates
  84329. ** will eventually overtake the earlier data and knock it out. The
  84330. ** query logic likewise merges doclists so that newer data knocks out
  84331. ** older data.
  84332. **
  84333. ** TODO(shess) Provide a VACUUM type operation to clear out all
  84334. ** deletions and duplications. This would basically be a forced merge
  84335. ** into a single segment.
  84336. */
  84337. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  84338. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  84339. # define SQLITE_CORE 1
  84340. #endif
  84341. /************** Include fts3_expr.h in the middle of fts3.c ******************/
  84342. /************** Begin file fts3_expr.h ***************************************/
  84343. /*
  84344. ** 2008 Nov 28
  84345. **
  84346. ** The author disclaims copyright to this source code. In place of
  84347. ** a legal notice, here is a blessing:
  84348. **
  84349. ** May you do good and not evil.
  84350. ** May you find forgiveness for yourself and forgive others.
  84351. ** May you share freely, never taking more than you give.
  84352. **
  84353. ******************************************************************************
  84354. **
  84355. */
  84356. /************** Include fts3_tokenizer.h in the middle of fts3_expr.h ********/
  84357. /************** Begin file fts3_tokenizer.h **********************************/
  84358. /*
  84359. ** 2006 July 10
  84360. **
  84361. ** The author disclaims copyright to this source code.
  84362. **
  84363. *************************************************************************
  84364. ** Defines the interface to tokenizers used by fulltext-search. There
  84365. ** are three basic components:
  84366. **
  84367. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  84368. ** interface functions. This is essentially the class structure for
  84369. ** tokenizers.
  84370. **
  84371. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  84372. ** including customization information defined at creation time.
  84373. **
  84374. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  84375. ** tokens from a particular input.
  84376. */
  84377. #ifndef _FTS3_TOKENIZER_H_
  84378. #define _FTS3_TOKENIZER_H_
  84379. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  84380. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  84381. ** we will need a way to register the API consistently.
  84382. */
  84383. /*
  84384. ** Structures used by the tokenizer interface. When a new tokenizer
  84385. ** implementation is registered, the caller provides a pointer to
  84386. ** an sqlite3_tokenizer_module containing pointers to the callback
  84387. ** functions that make up an implementation.
  84388. **
  84389. ** When an fts3 table is created, it passes any arguments passed to
  84390. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  84391. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  84392. ** implementation. The xCreate() function in turn returns an
  84393. ** sqlite3_tokenizer structure representing the specific tokenizer to
  84394. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  84395. **
  84396. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  84397. ** method is called. It returns an sqlite3_tokenizer_cursor object
  84398. ** that may be used to tokenize a specific input buffer based on
  84399. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  84400. ** object.
  84401. */
  84402. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  84403. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  84404. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  84405. struct sqlite3_tokenizer_module {
  84406. /*
  84407. ** Structure version. Should always be set to 0.
  84408. */
  84409. int iVersion;
  84410. /*
  84411. ** Create a new tokenizer. The values in the argv[] array are the
  84412. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  84413. ** TABLE statement that created the fts3 table. For example, if
  84414. ** the following SQL is executed:
  84415. **
  84416. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  84417. **
  84418. ** then argc is set to 2, and the argv[] array contains pointers
  84419. ** to the strings "arg1" and "arg2".
  84420. **
  84421. ** This method should return either SQLITE_OK (0), or an SQLite error
  84422. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  84423. ** to point at the newly created tokenizer structure. The generic
  84424. ** sqlite3_tokenizer.pModule variable should not be initialised by
  84425. ** this callback. The caller will do so.
  84426. */
  84427. int (*xCreate)(
  84428. int argc, /* Size of argv array */
  84429. const char *const*argv, /* Tokenizer argument strings */
  84430. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  84431. );
  84432. /*
  84433. ** Destroy an existing tokenizer. The fts3 module calls this method
  84434. ** exactly once for each successful call to xCreate().
  84435. */
  84436. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  84437. /*
  84438. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  84439. ** is responsible for ensuring that the input buffer remains valid
  84440. ** until the cursor is closed (using the xClose() method).
  84441. */
  84442. int (*xOpen)(
  84443. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  84444. const char *pInput, int nBytes, /* Input buffer */
  84445. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  84446. );
  84447. /*
  84448. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  84449. ** method exactly once for each successful call to xOpen().
  84450. */
  84451. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  84452. /*
  84453. ** Retrieve the next token from the tokenizer cursor pCursor. This
  84454. ** method should either return SQLITE_OK and set the values of the
  84455. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  84456. ** the end of the buffer has been reached, or an SQLite error code.
  84457. **
  84458. ** *ppToken should be set to point at a buffer containing the
  84459. ** normalized version of the token (i.e. after any case-folding and/or
  84460. ** stemming has been performed). *pnBytes should be set to the length
  84461. ** of this buffer in bytes. The input text that generated the token is
  84462. ** identified by the byte offsets returned in *piStartOffset and
  84463. ** *piEndOffset.
  84464. **
  84465. ** The buffer *ppToken is set to point at is managed by the tokenizer
  84466. ** implementation. It is only required to be valid until the next call
  84467. ** to xNext() or xClose().
  84468. */
  84469. /* TODO(shess) current implementation requires pInput to be
  84470. ** nul-terminated. This should either be fixed, or pInput/nBytes
  84471. ** should be converted to zInput.
  84472. */
  84473. int (*xNext)(
  84474. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  84475. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  84476. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  84477. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  84478. int *piPosition /* OUT: Number of tokens returned before this one */
  84479. );
  84480. };
  84481. struct sqlite3_tokenizer {
  84482. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  84483. /* Tokenizer implementations will typically add additional fields */
  84484. };
  84485. struct sqlite3_tokenizer_cursor {
  84486. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  84487. /* Tokenizer implementations will typically add additional fields */
  84488. };
  84489. #endif /* _FTS3_TOKENIZER_H_ */
  84490. /************** End of fts3_tokenizer.h **************************************/
  84491. /************** Continuing where we left off in fts3_expr.h ******************/
  84492. /*
  84493. ** The following describes the syntax supported by the fts3 MATCH
  84494. ** operator in a similar format to that used by the lemon parser
  84495. ** generator. This module does not use actually lemon, it uses a
  84496. ** custom parser.
  84497. **
  84498. ** query ::= andexpr (OR andexpr)*.
  84499. **
  84500. ** andexpr ::= notexpr (AND? notexpr)*.
  84501. **
  84502. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  84503. ** notexpr ::= LP query RP.
  84504. **
  84505. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  84506. **
  84507. ** distance_opt ::= .
  84508. ** distance_opt ::= / INTEGER.
  84509. **
  84510. ** phrase ::= TOKEN.
  84511. ** phrase ::= COLUMN:TOKEN.
  84512. ** phrase ::= "TOKEN TOKEN TOKEN...".
  84513. */
  84514. typedef struct Fts3Expr Fts3Expr;
  84515. typedef struct Fts3Phrase Fts3Phrase;
  84516. /*
  84517. ** A "phrase" is a sequence of one or more tokens that must match in
  84518. ** sequence. A single token is the base case and the most common case.
  84519. ** For a sequence of tokens contained in "...", nToken will be the number
  84520. ** of tokens in the string.
  84521. */
  84522. struct Fts3Phrase {
  84523. int nToken; /* Number of tokens in the phrase */
  84524. int iColumn; /* Index of column this phrase must match */
  84525. int isNot; /* Phrase prefixed by unary not (-) operator */
  84526. struct PhraseToken {
  84527. char *z; /* Text of the token */
  84528. int n; /* Number of bytes in buffer pointed to by z */
  84529. int isPrefix; /* True if token ends in with a "*" character */
  84530. } aToken[1]; /* One entry for each token in the phrase */
  84531. };
  84532. /*
  84533. ** A tree of these objects forms the RHS of a MATCH operator.
  84534. */
  84535. struct Fts3Expr {
  84536. int eType; /* One of the FTSQUERY_XXX values defined below */
  84537. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  84538. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  84539. Fts3Expr *pLeft; /* Left operand */
  84540. Fts3Expr *pRight; /* Right operand */
  84541. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  84542. };
  84543. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, char **, int, int,
  84544. const char *, int, Fts3Expr **);
  84545. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  84546. /*
  84547. ** Candidate values for Fts3Query.eType. Note that the order of the first
  84548. ** four values is in order of precedence when parsing expressions. For
  84549. ** example, the following:
  84550. **
  84551. ** "a OR b AND c NOT d NEAR e"
  84552. **
  84553. ** is equivalent to:
  84554. **
  84555. ** "a OR (b AND (c NOT (d NEAR e)))"
  84556. */
  84557. #define FTSQUERY_NEAR 1
  84558. #define FTSQUERY_NOT 2
  84559. #define FTSQUERY_AND 3
  84560. #define FTSQUERY_OR 4
  84561. #define FTSQUERY_PHRASE 5
  84562. #ifdef SQLITE_TEST
  84563. SQLITE_PRIVATE void sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  84564. #endif
  84565. /************** End of fts3_expr.h *******************************************/
  84566. /************** Continuing where we left off in fts3.c ***********************/
  84567. /************** Include fts3_hash.h in the middle of fts3.c ******************/
  84568. /************** Begin file fts3_hash.h ***************************************/
  84569. /*
  84570. ** 2001 September 22
  84571. **
  84572. ** The author disclaims copyright to this source code. In place of
  84573. ** a legal notice, here is a blessing:
  84574. **
  84575. ** May you do good and not evil.
  84576. ** May you find forgiveness for yourself and forgive others.
  84577. ** May you share freely, never taking more than you give.
  84578. **
  84579. *************************************************************************
  84580. ** This is the header file for the generic hash-table implemenation
  84581. ** used in SQLite. We've modified it slightly to serve as a standalone
  84582. ** hash table implementation for the full-text indexing module.
  84583. **
  84584. */
  84585. #ifndef _FTS3_HASH_H_
  84586. #define _FTS3_HASH_H_
  84587. /* Forward declarations of structures. */
  84588. typedef struct fts3Hash fts3Hash;
  84589. typedef struct fts3HashElem fts3HashElem;
  84590. /* A complete hash table is an instance of the following structure.
  84591. ** The internals of this structure are intended to be opaque -- client
  84592. ** code should not attempt to access or modify the fields of this structure
  84593. ** directly. Change this structure only by using the routines below.
  84594. ** However, many of the "procedures" and "functions" for modifying and
  84595. ** accessing this structure are really macros, so we can't really make
  84596. ** this structure opaque.
  84597. */
  84598. struct fts3Hash {
  84599. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  84600. char copyKey; /* True if copy of key made on insert */
  84601. int count; /* Number of entries in this table */
  84602. fts3HashElem *first; /* The first element of the array */
  84603. int htsize; /* Number of buckets in the hash table */
  84604. struct _fts3ht { /* the hash table */
  84605. int count; /* Number of entries with this hash */
  84606. fts3HashElem *chain; /* Pointer to first entry with this hash */
  84607. } *ht;
  84608. };
  84609. /* Each element in the hash table is an instance of the following
  84610. ** structure. All elements are stored on a single doubly-linked list.
  84611. **
  84612. ** Again, this structure is intended to be opaque, but it can't really
  84613. ** be opaque because it is used by macros.
  84614. */
  84615. struct fts3HashElem {
  84616. fts3HashElem *next, *prev; /* Next and previous elements in the table */
  84617. void *data; /* Data associated with this element */
  84618. void *pKey; int nKey; /* Key associated with this element */
  84619. };
  84620. /*
  84621. ** There are 2 different modes of operation for a hash table:
  84622. **
  84623. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  84624. ** (including the null-terminator, if any). Case
  84625. ** is respected in comparisons.
  84626. **
  84627. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  84628. ** memcmp() is used to compare keys.
  84629. **
  84630. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  84631. */
  84632. #define FTS3_HASH_STRING 1
  84633. #define FTS3_HASH_BINARY 2
  84634. /*
  84635. ** Access routines. To delete, insert a NULL pointer.
  84636. */
  84637. SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
  84638. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
  84639. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
  84640. SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*);
  84641. /*
  84642. ** Shorthand for the functions above
  84643. */
  84644. #define fts3HashInit sqlite3Fts3HashInit
  84645. #define fts3HashInsert sqlite3Fts3HashInsert
  84646. #define fts3HashFind sqlite3Fts3HashFind
  84647. #define fts3HashClear sqlite3Fts3HashClear
  84648. /*
  84649. ** Macros for looping over all elements of a hash table. The idiom is
  84650. ** like this:
  84651. **
  84652. ** fts3Hash h;
  84653. ** fts3HashElem *p;
  84654. ** ...
  84655. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  84656. ** SomeStructure *pData = fts3HashData(p);
  84657. ** // do something with pData
  84658. ** }
  84659. */
  84660. #define fts3HashFirst(H) ((H)->first)
  84661. #define fts3HashNext(E) ((E)->next)
  84662. #define fts3HashData(E) ((E)->data)
  84663. #define fts3HashKey(E) ((E)->pKey)
  84664. #define fts3HashKeysize(E) ((E)->nKey)
  84665. /*
  84666. ** Number of entries in a hash table
  84667. */
  84668. #define fts3HashCount(H) ((H)->count)
  84669. #endif /* _FTS3_HASH_H_ */
  84670. /************** End of fts3_hash.h *******************************************/
  84671. /************** Continuing where we left off in fts3.c ***********************/
  84672. #ifndef SQLITE_CORE
  84673. SQLITE_EXTENSION_INIT1
  84674. #endif
  84675. /* TODO(shess) MAN, this thing needs some refactoring. At minimum, it
  84676. ** would be nice to order the file better, perhaps something along the
  84677. ** lines of:
  84678. **
  84679. ** - utility functions
  84680. ** - table setup functions
  84681. ** - table update functions
  84682. ** - table query functions
  84683. **
  84684. ** Put the query functions last because they're likely to reference
  84685. ** typedefs or functions from the table update section.
  84686. */
  84687. #if 0
  84688. # define FTSTRACE(A) printf A; fflush(stdout)
  84689. #else
  84690. # define FTSTRACE(A)
  84691. #endif
  84692. /* It is not safe to call isspace(), tolower(), or isalnum() on
  84693. ** hi-bit-set characters. This is the same solution used in the
  84694. ** tokenizer.
  84695. */
  84696. /* TODO(shess) The snippet-generation code should be using the
  84697. ** tokenizer-generated tokens rather than doing its own local
  84698. ** tokenization.
  84699. */
  84700. /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
  84701. static int safe_isspace(char c){
  84702. return (c&0x80)==0 ? isspace(c) : 0;
  84703. }
  84704. static int safe_tolower(char c){
  84705. return (c&0x80)==0 ? tolower(c) : c;
  84706. }
  84707. static int safe_isalnum(char c){
  84708. return (c&0x80)==0 ? isalnum(c) : 0;
  84709. }
  84710. typedef enum DocListType {
  84711. DL_DOCIDS, /* docids only */
  84712. DL_POSITIONS, /* docids + positions */
  84713. DL_POSITIONS_OFFSETS /* docids + positions + offsets */
  84714. } DocListType;
  84715. /*
  84716. ** By default, only positions and not offsets are stored in the doclists.
  84717. ** To change this so that offsets are stored too, compile with
  84718. **
  84719. ** -DDL_DEFAULT=DL_POSITIONS_OFFSETS
  84720. **
  84721. ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
  84722. ** into (no deletes or updates).
  84723. */
  84724. #ifndef DL_DEFAULT
  84725. # define DL_DEFAULT DL_POSITIONS
  84726. #endif
  84727. enum {
  84728. POS_END = 0, /* end of this position list */
  84729. POS_COLUMN, /* followed by new column number */
  84730. POS_BASE
  84731. };
  84732. /* MERGE_COUNT controls how often we merge segments (see comment at
  84733. ** top of file).
  84734. */
  84735. #define MERGE_COUNT 16
  84736. /* utility functions */
  84737. /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
  84738. ** record to prevent errors of the form:
  84739. **
  84740. ** my_function(SomeType *b){
  84741. ** memset(b, '\0', sizeof(b)); // sizeof(b)!=sizeof(*b)
  84742. ** }
  84743. */
  84744. /* TODO(shess) Obvious candidates for a header file. */
  84745. #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
  84746. #ifndef NDEBUG
  84747. # define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
  84748. #else
  84749. # define SCRAMBLE(b)
  84750. #endif
  84751. /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
  84752. #define VARINT_MAX 10
  84753. /* Write a 64-bit variable-length integer to memory starting at p[0].
  84754. * The length of data written will be between 1 and VARINT_MAX bytes.
  84755. * The number of bytes written is returned. */
  84756. static int fts3PutVarint(char *p, sqlite_int64 v){
  84757. unsigned char *q = (unsigned char *) p;
  84758. sqlite_uint64 vu = v;
  84759. do{
  84760. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  84761. vu >>= 7;
  84762. }while( vu!=0 );
  84763. q[-1] &= 0x7f; /* turn off high bit in final byte */
  84764. assert( q - (unsigned char *)p <= VARINT_MAX );
  84765. return (int) (q - (unsigned char *)p);
  84766. }
  84767. /* Read a 64-bit variable-length integer from memory starting at p[0].
  84768. * Return the number of bytes read, or 0 on error.
  84769. * The value is stored in *v. */
  84770. static int fts3GetVarint(const char *p, sqlite_int64 *v){
  84771. const unsigned char *q = (const unsigned char *) p;
  84772. sqlite_uint64 x = 0, y = 1;
  84773. while( (*q & 0x80) == 0x80 ){
  84774. x += y * (*q++ & 0x7f);
  84775. y <<= 7;
  84776. if( q - (unsigned char *)p >= VARINT_MAX ){ /* bad data */
  84777. assert( 0 );
  84778. return 0;
  84779. }
  84780. }
  84781. x += y * (*q++);
  84782. *v = (sqlite_int64) x;
  84783. return (int) (q - (unsigned char *)p);
  84784. }
  84785. static int fts3GetVarint32(const char *p, int *pi){
  84786. sqlite_int64 i;
  84787. int ret = fts3GetVarint(p, &i);
  84788. *pi = (int) i;
  84789. assert( *pi==i );
  84790. return ret;
  84791. }
  84792. /*******************************************************************/
  84793. /* DataBuffer is used to collect data into a buffer in piecemeal
  84794. ** fashion. It implements the usual distinction between amount of
  84795. ** data currently stored (nData) and buffer capacity (nCapacity).
  84796. **
  84797. ** dataBufferInit - create a buffer with given initial capacity.
  84798. ** dataBufferReset - forget buffer's data, retaining capacity.
  84799. ** dataBufferDestroy - free buffer's data.
  84800. ** dataBufferSwap - swap contents of two buffers.
  84801. ** dataBufferExpand - expand capacity without adding data.
  84802. ** dataBufferAppend - append data.
  84803. ** dataBufferAppend2 - append two pieces of data at once.
  84804. ** dataBufferReplace - replace buffer's data.
  84805. */
  84806. typedef struct DataBuffer {
  84807. char *pData; /* Pointer to malloc'ed buffer. */
  84808. int nCapacity; /* Size of pData buffer. */
  84809. int nData; /* End of data loaded into pData. */
  84810. } DataBuffer;
  84811. static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
  84812. assert( nCapacity>=0 );
  84813. pBuffer->nData = 0;
  84814. pBuffer->nCapacity = nCapacity;
  84815. pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
  84816. }
  84817. static void dataBufferReset(DataBuffer *pBuffer){
  84818. pBuffer->nData = 0;
  84819. }
  84820. static void dataBufferDestroy(DataBuffer *pBuffer){
  84821. if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
  84822. SCRAMBLE(pBuffer);
  84823. }
  84824. static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
  84825. DataBuffer tmp = *pBuffer1;
  84826. *pBuffer1 = *pBuffer2;
  84827. *pBuffer2 = tmp;
  84828. }
  84829. static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
  84830. assert( nAddCapacity>0 );
  84831. /* TODO(shess) Consider expanding more aggressively. Note that the
  84832. ** underlying malloc implementation may take care of such things for
  84833. ** us already.
  84834. */
  84835. if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
  84836. pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
  84837. pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
  84838. }
  84839. }
  84840. static void dataBufferAppend(DataBuffer *pBuffer,
  84841. const char *pSource, int nSource){
  84842. assert( nSource>0 && pSource!=NULL );
  84843. dataBufferExpand(pBuffer, nSource);
  84844. memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
  84845. pBuffer->nData += nSource;
  84846. }
  84847. static void dataBufferAppend2(DataBuffer *pBuffer,
  84848. const char *pSource1, int nSource1,
  84849. const char *pSource2, int nSource2){
  84850. assert( nSource1>0 && pSource1!=NULL );
  84851. assert( nSource2>0 && pSource2!=NULL );
  84852. dataBufferExpand(pBuffer, nSource1+nSource2);
  84853. memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
  84854. memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
  84855. pBuffer->nData += nSource1+nSource2;
  84856. }
  84857. static void dataBufferReplace(DataBuffer *pBuffer,
  84858. const char *pSource, int nSource){
  84859. dataBufferReset(pBuffer);
  84860. dataBufferAppend(pBuffer, pSource, nSource);
  84861. }
  84862. /* StringBuffer is a null-terminated version of DataBuffer. */
  84863. typedef struct StringBuffer {
  84864. DataBuffer b; /* Includes null terminator. */
  84865. } StringBuffer;
  84866. static void initStringBuffer(StringBuffer *sb){
  84867. dataBufferInit(&sb->b, 100);
  84868. dataBufferReplace(&sb->b, "", 1);
  84869. }
  84870. static int stringBufferLength(StringBuffer *sb){
  84871. return sb->b.nData-1;
  84872. }
  84873. static char *stringBufferData(StringBuffer *sb){
  84874. return sb->b.pData;
  84875. }
  84876. static void stringBufferDestroy(StringBuffer *sb){
  84877. dataBufferDestroy(&sb->b);
  84878. }
  84879. static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
  84880. assert( sb->b.nData>0 );
  84881. if( nFrom>0 ){
  84882. sb->b.nData--;
  84883. dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
  84884. }
  84885. }
  84886. static void append(StringBuffer *sb, const char *zFrom){
  84887. nappend(sb, zFrom, strlen(zFrom));
  84888. }
  84889. /* Append a list of strings separated by commas. */
  84890. static void appendList(StringBuffer *sb, int nString, char **azString){
  84891. int i;
  84892. for(i=0; i<nString; ++i){
  84893. if( i>0 ) append(sb, ", ");
  84894. append(sb, azString[i]);
  84895. }
  84896. }
  84897. static int endsInWhiteSpace(StringBuffer *p){
  84898. return stringBufferLength(p)>0 &&
  84899. safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
  84900. }
  84901. /* If the StringBuffer ends in something other than white space, add a
  84902. ** single space character to the end.
  84903. */
  84904. static void appendWhiteSpace(StringBuffer *p){
  84905. if( stringBufferLength(p)==0 ) return;
  84906. if( !endsInWhiteSpace(p) ) append(p, " ");
  84907. }
  84908. /* Remove white space from the end of the StringBuffer */
  84909. static void trimWhiteSpace(StringBuffer *p){
  84910. while( endsInWhiteSpace(p) ){
  84911. p->b.pData[--p->b.nData-1] = '\0';
  84912. }
  84913. }
  84914. /*******************************************************************/
  84915. /* DLReader is used to read document elements from a doclist. The
  84916. ** current docid is cached, so dlrDocid() is fast. DLReader does not
  84917. ** own the doclist buffer.
  84918. **
  84919. ** dlrAtEnd - true if there's no more data to read.
  84920. ** dlrDocid - docid of current document.
  84921. ** dlrDocData - doclist data for current document (including docid).
  84922. ** dlrDocDataBytes - length of same.
  84923. ** dlrAllDataBytes - length of all remaining data.
  84924. ** dlrPosData - position data for current document.
  84925. ** dlrPosDataLen - length of pos data for current document (incl POS_END).
  84926. ** dlrStep - step to current document.
  84927. ** dlrInit - initial for doclist of given type against given data.
  84928. ** dlrDestroy - clean up.
  84929. **
  84930. ** Expected usage is something like:
  84931. **
  84932. ** DLReader reader;
  84933. ** dlrInit(&reader, pData, nData);
  84934. ** while( !dlrAtEnd(&reader) ){
  84935. ** // calls to dlrDocid() and kin.
  84936. ** dlrStep(&reader);
  84937. ** }
  84938. ** dlrDestroy(&reader);
  84939. */
  84940. typedef struct DLReader {
  84941. DocListType iType;
  84942. const char *pData;
  84943. int nData;
  84944. sqlite_int64 iDocid;
  84945. int nElement;
  84946. } DLReader;
  84947. static int dlrAtEnd(DLReader *pReader){
  84948. assert( pReader->nData>=0 );
  84949. return pReader->nData==0;
  84950. }
  84951. static sqlite_int64 dlrDocid(DLReader *pReader){
  84952. assert( !dlrAtEnd(pReader) );
  84953. return pReader->iDocid;
  84954. }
  84955. static const char *dlrDocData(DLReader *pReader){
  84956. assert( !dlrAtEnd(pReader) );
  84957. return pReader->pData;
  84958. }
  84959. static int dlrDocDataBytes(DLReader *pReader){
  84960. assert( !dlrAtEnd(pReader) );
  84961. return pReader->nElement;
  84962. }
  84963. static int dlrAllDataBytes(DLReader *pReader){
  84964. assert( !dlrAtEnd(pReader) );
  84965. return pReader->nData;
  84966. }
  84967. /* TODO(shess) Consider adding a field to track iDocid varint length
  84968. ** to make these two functions faster. This might matter (a tiny bit)
  84969. ** for queries.
  84970. */
  84971. static const char *dlrPosData(DLReader *pReader){
  84972. sqlite_int64 iDummy;
  84973. int n = fts3GetVarint(pReader->pData, &iDummy);
  84974. assert( !dlrAtEnd(pReader) );
  84975. return pReader->pData+n;
  84976. }
  84977. static int dlrPosDataLen(DLReader *pReader){
  84978. sqlite_int64 iDummy;
  84979. int n = fts3GetVarint(pReader->pData, &iDummy);
  84980. assert( !dlrAtEnd(pReader) );
  84981. return pReader->nElement-n;
  84982. }
  84983. static void dlrStep(DLReader *pReader){
  84984. assert( !dlrAtEnd(pReader) );
  84985. /* Skip past current doclist element. */
  84986. assert( pReader->nElement<=pReader->nData );
  84987. pReader->pData += pReader->nElement;
  84988. pReader->nData -= pReader->nElement;
  84989. /* If there is more data, read the next doclist element. */
  84990. if( pReader->nData!=0 ){
  84991. sqlite_int64 iDocidDelta;
  84992. int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
  84993. pReader->iDocid += iDocidDelta;
  84994. if( pReader->iType>=DL_POSITIONS ){
  84995. assert( n<pReader->nData );
  84996. while( 1 ){
  84997. n += fts3GetVarint32(pReader->pData+n, &iDummy);
  84998. assert( n<=pReader->nData );
  84999. if( iDummy==POS_END ) break;
  85000. if( iDummy==POS_COLUMN ){
  85001. n += fts3GetVarint32(pReader->pData+n, &iDummy);
  85002. assert( n<pReader->nData );
  85003. }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
  85004. n += fts3GetVarint32(pReader->pData+n, &iDummy);
  85005. n += fts3GetVarint32(pReader->pData+n, &iDummy);
  85006. assert( n<pReader->nData );
  85007. }
  85008. }
  85009. }
  85010. pReader->nElement = n;
  85011. assert( pReader->nElement<=pReader->nData );
  85012. }
  85013. }
  85014. static void dlrInit(DLReader *pReader, DocListType iType,
  85015. const char *pData, int nData){
  85016. assert( pData!=NULL && nData!=0 );
  85017. pReader->iType = iType;
  85018. pReader->pData = pData;
  85019. pReader->nData = nData;
  85020. pReader->nElement = 0;
  85021. pReader->iDocid = 0;
  85022. /* Load the first element's data. There must be a first element. */
  85023. dlrStep(pReader);
  85024. }
  85025. static void dlrDestroy(DLReader *pReader){
  85026. SCRAMBLE(pReader);
  85027. }
  85028. #ifndef NDEBUG
  85029. /* Verify that the doclist can be validly decoded. Also returns the
  85030. ** last docid found because it is convenient in other assertions for
  85031. ** DLWriter.
  85032. */
  85033. static void docListValidate(DocListType iType, const char *pData, int nData,
  85034. sqlite_int64 *pLastDocid){
  85035. sqlite_int64 iPrevDocid = 0;
  85036. assert( nData>0 );
  85037. assert( pData!=0 );
  85038. assert( pData+nData>pData );
  85039. while( nData!=0 ){
  85040. sqlite_int64 iDocidDelta;
  85041. int n = fts3GetVarint(pData, &iDocidDelta);
  85042. iPrevDocid += iDocidDelta;
  85043. if( iType>DL_DOCIDS ){
  85044. int iDummy;
  85045. while( 1 ){
  85046. n += fts3GetVarint32(pData+n, &iDummy);
  85047. if( iDummy==POS_END ) break;
  85048. if( iDummy==POS_COLUMN ){
  85049. n += fts3GetVarint32(pData+n, &iDummy);
  85050. }else if( iType>DL_POSITIONS ){
  85051. n += fts3GetVarint32(pData+n, &iDummy);
  85052. n += fts3GetVarint32(pData+n, &iDummy);
  85053. }
  85054. assert( n<=nData );
  85055. }
  85056. }
  85057. assert( n<=nData );
  85058. pData += n;
  85059. nData -= n;
  85060. }
  85061. if( pLastDocid ) *pLastDocid = iPrevDocid;
  85062. }
  85063. #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
  85064. #else
  85065. #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
  85066. #endif
  85067. /*******************************************************************/
  85068. /* DLWriter is used to write doclist data to a DataBuffer. DLWriter
  85069. ** always appends to the buffer and does not own it.
  85070. **
  85071. ** dlwInit - initialize to write a given type doclistto a buffer.
  85072. ** dlwDestroy - clear the writer's memory. Does not free buffer.
  85073. ** dlwAppend - append raw doclist data to buffer.
  85074. ** dlwCopy - copy next doclist from reader to writer.
  85075. ** dlwAdd - construct doclist element and append to buffer.
  85076. ** Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
  85077. */
  85078. typedef struct DLWriter {
  85079. DocListType iType;
  85080. DataBuffer *b;
  85081. sqlite_int64 iPrevDocid;
  85082. #ifndef NDEBUG
  85083. int has_iPrevDocid;
  85084. #endif
  85085. } DLWriter;
  85086. static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
  85087. pWriter->b = b;
  85088. pWriter->iType = iType;
  85089. pWriter->iPrevDocid = 0;
  85090. #ifndef NDEBUG
  85091. pWriter->has_iPrevDocid = 0;
  85092. #endif
  85093. }
  85094. static void dlwDestroy(DLWriter *pWriter){
  85095. SCRAMBLE(pWriter);
  85096. }
  85097. /* iFirstDocid is the first docid in the doclist in pData. It is
  85098. ** needed because pData may point within a larger doclist, in which
  85099. ** case the first item would be delta-encoded.
  85100. **
  85101. ** iLastDocid is the final docid in the doclist in pData. It is
  85102. ** needed to create the new iPrevDocid for future delta-encoding. The
  85103. ** code could decode the passed doclist to recreate iLastDocid, but
  85104. ** the only current user (docListMerge) already has decoded this
  85105. ** information.
  85106. */
  85107. /* TODO(shess) This has become just a helper for docListMerge.
  85108. ** Consider a refactor to make this cleaner.
  85109. */
  85110. static void dlwAppend(DLWriter *pWriter,
  85111. const char *pData, int nData,
  85112. sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
  85113. sqlite_int64 iDocid = 0;
  85114. char c[VARINT_MAX];
  85115. int nFirstOld, nFirstNew; /* Old and new varint len of first docid. */
  85116. #ifndef NDEBUG
  85117. sqlite_int64 iLastDocidDelta;
  85118. #endif
  85119. /* Recode the initial docid as delta from iPrevDocid. */
  85120. nFirstOld = fts3GetVarint(pData, &iDocid);
  85121. assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
  85122. nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
  85123. /* Verify that the incoming doclist is valid AND that it ends with
  85124. ** the expected docid. This is essential because we'll trust this
  85125. ** docid in future delta-encoding.
  85126. */
  85127. ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
  85128. assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
  85129. /* Append recoded initial docid and everything else. Rest of docids
  85130. ** should have been delta-encoded from previous initial docid.
  85131. */
  85132. if( nFirstOld<nData ){
  85133. dataBufferAppend2(pWriter->b, c, nFirstNew,
  85134. pData+nFirstOld, nData-nFirstOld);
  85135. }else{
  85136. dataBufferAppend(pWriter->b, c, nFirstNew);
  85137. }
  85138. pWriter->iPrevDocid = iLastDocid;
  85139. }
  85140. static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
  85141. dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
  85142. dlrDocid(pReader), dlrDocid(pReader));
  85143. }
  85144. static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
  85145. char c[VARINT_MAX];
  85146. int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
  85147. /* Docids must ascend. */
  85148. assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
  85149. assert( pWriter->iType==DL_DOCIDS );
  85150. dataBufferAppend(pWriter->b, c, n);
  85151. pWriter->iPrevDocid = iDocid;
  85152. #ifndef NDEBUG
  85153. pWriter->has_iPrevDocid = 1;
  85154. #endif
  85155. }
  85156. /*******************************************************************/
  85157. /* PLReader is used to read data from a document's position list. As
  85158. ** the caller steps through the list, data is cached so that varints
  85159. ** only need to be decoded once.
  85160. **
  85161. ** plrInit, plrDestroy - create/destroy a reader.
  85162. ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
  85163. ** plrAtEnd - at end of stream, only call plrDestroy once true.
  85164. ** plrStep - step to the next element.
  85165. */
  85166. typedef struct PLReader {
  85167. /* These refer to the next position's data. nData will reach 0 when
  85168. ** reading the last position, so plrStep() signals EOF by setting
  85169. ** pData to NULL.
  85170. */
  85171. const char *pData;
  85172. int nData;
  85173. DocListType iType;
  85174. int iColumn; /* the last column read */
  85175. int iPosition; /* the last position read */
  85176. int iStartOffset; /* the last start offset read */
  85177. int iEndOffset; /* the last end offset read */
  85178. } PLReader;
  85179. static int plrAtEnd(PLReader *pReader){
  85180. return pReader->pData==NULL;
  85181. }
  85182. static int plrColumn(PLReader *pReader){
  85183. assert( !plrAtEnd(pReader) );
  85184. return pReader->iColumn;
  85185. }
  85186. static int plrPosition(PLReader *pReader){
  85187. assert( !plrAtEnd(pReader) );
  85188. return pReader->iPosition;
  85189. }
  85190. static int plrStartOffset(PLReader *pReader){
  85191. assert( !plrAtEnd(pReader) );
  85192. return pReader->iStartOffset;
  85193. }
  85194. static int plrEndOffset(PLReader *pReader){
  85195. assert( !plrAtEnd(pReader) );
  85196. return pReader->iEndOffset;
  85197. }
  85198. static void plrStep(PLReader *pReader){
  85199. int i, n;
  85200. assert( !plrAtEnd(pReader) );
  85201. if( pReader->nData==0 ){
  85202. pReader->pData = NULL;
  85203. return;
  85204. }
  85205. n = fts3GetVarint32(pReader->pData, &i);
  85206. if( i==POS_COLUMN ){
  85207. n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
  85208. pReader->iPosition = 0;
  85209. pReader->iStartOffset = 0;
  85210. n += fts3GetVarint32(pReader->pData+n, &i);
  85211. }
  85212. /* Should never see adjacent column changes. */
  85213. assert( i!=POS_COLUMN );
  85214. if( i==POS_END ){
  85215. pReader->nData = 0;
  85216. pReader->pData = NULL;
  85217. return;
  85218. }
  85219. pReader->iPosition += i-POS_BASE;
  85220. if( pReader->iType==DL_POSITIONS_OFFSETS ){
  85221. n += fts3GetVarint32(pReader->pData+n, &i);
  85222. pReader->iStartOffset += i;
  85223. n += fts3GetVarint32(pReader->pData+n, &i);
  85224. pReader->iEndOffset = pReader->iStartOffset+i;
  85225. }
  85226. assert( n<=pReader->nData );
  85227. pReader->pData += n;
  85228. pReader->nData -= n;
  85229. }
  85230. static void plrInit(PLReader *pReader, DLReader *pDLReader){
  85231. pReader->pData = dlrPosData(pDLReader);
  85232. pReader->nData = dlrPosDataLen(pDLReader);
  85233. pReader->iType = pDLReader->iType;
  85234. pReader->iColumn = 0;
  85235. pReader->iPosition = 0;
  85236. pReader->iStartOffset = 0;
  85237. pReader->iEndOffset = 0;
  85238. plrStep(pReader);
  85239. }
  85240. static void plrDestroy(PLReader *pReader){
  85241. SCRAMBLE(pReader);
  85242. }
  85243. /*******************************************************************/
  85244. /* PLWriter is used in constructing a document's position list. As a
  85245. ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
  85246. ** PLWriter writes to the associated DLWriter's buffer.
  85247. **
  85248. ** plwInit - init for writing a document's poslist.
  85249. ** plwDestroy - clear a writer.
  85250. ** plwAdd - append position and offset information.
  85251. ** plwCopy - copy next position's data from reader to writer.
  85252. ** plwTerminate - add any necessary doclist terminator.
  85253. **
  85254. ** Calling plwAdd() after plwTerminate() may result in a corrupt
  85255. ** doclist.
  85256. */
  85257. /* TODO(shess) Until we've written the second item, we can cache the
  85258. ** first item's information. Then we'd have three states:
  85259. **
  85260. ** - initialized with docid, no positions.
  85261. ** - docid and one position.
  85262. ** - docid and multiple positions.
  85263. **
  85264. ** Only the last state needs to actually write to dlw->b, which would
  85265. ** be an improvement in the DLCollector case.
  85266. */
  85267. typedef struct PLWriter {
  85268. DLWriter *dlw;
  85269. int iColumn; /* the last column written */
  85270. int iPos; /* the last position written */
  85271. int iOffset; /* the last start offset written */
  85272. } PLWriter;
  85273. /* TODO(shess) In the case where the parent is reading these values
  85274. ** from a PLReader, we could optimize to a copy if that PLReader has
  85275. ** the same type as pWriter.
  85276. */
  85277. static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
  85278. int iStartOffset, int iEndOffset){
  85279. /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
  85280. ** iStartOffsetDelta, and iEndOffsetDelta.
  85281. */
  85282. char c[5*VARINT_MAX];
  85283. int n = 0;
  85284. /* Ban plwAdd() after plwTerminate(). */
  85285. assert( pWriter->iPos!=-1 );
  85286. if( pWriter->dlw->iType==DL_DOCIDS ) return;
  85287. if( iColumn!=pWriter->iColumn ){
  85288. n += fts3PutVarint(c+n, POS_COLUMN);
  85289. n += fts3PutVarint(c+n, iColumn);
  85290. pWriter->iColumn = iColumn;
  85291. pWriter->iPos = 0;
  85292. pWriter->iOffset = 0;
  85293. }
  85294. assert( iPos>=pWriter->iPos );
  85295. n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
  85296. pWriter->iPos = iPos;
  85297. if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
  85298. assert( iStartOffset>=pWriter->iOffset );
  85299. n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
  85300. pWriter->iOffset = iStartOffset;
  85301. assert( iEndOffset>=iStartOffset );
  85302. n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
  85303. }
  85304. dataBufferAppend(pWriter->dlw->b, c, n);
  85305. }
  85306. static void plwCopy(PLWriter *pWriter, PLReader *pReader){
  85307. plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
  85308. plrStartOffset(pReader), plrEndOffset(pReader));
  85309. }
  85310. static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
  85311. char c[VARINT_MAX];
  85312. int n;
  85313. pWriter->dlw = dlw;
  85314. /* Docids must ascend. */
  85315. assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
  85316. n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
  85317. dataBufferAppend(pWriter->dlw->b, c, n);
  85318. pWriter->dlw->iPrevDocid = iDocid;
  85319. #ifndef NDEBUG
  85320. pWriter->dlw->has_iPrevDocid = 1;
  85321. #endif
  85322. pWriter->iColumn = 0;
  85323. pWriter->iPos = 0;
  85324. pWriter->iOffset = 0;
  85325. }
  85326. /* TODO(shess) Should plwDestroy() also terminate the doclist? But
  85327. ** then plwDestroy() would no longer be just a destructor, it would
  85328. ** also be doing work, which isn't consistent with the overall idiom.
  85329. ** Another option would be for plwAdd() to always append any necessary
  85330. ** terminator, so that the output is always correct. But that would
  85331. ** add incremental work to the common case with the only benefit being
  85332. ** API elegance. Punt for now.
  85333. */
  85334. static void plwTerminate(PLWriter *pWriter){
  85335. if( pWriter->dlw->iType>DL_DOCIDS ){
  85336. char c[VARINT_MAX];
  85337. int n = fts3PutVarint(c, POS_END);
  85338. dataBufferAppend(pWriter->dlw->b, c, n);
  85339. }
  85340. #ifndef NDEBUG
  85341. /* Mark as terminated for assert in plwAdd(). */
  85342. pWriter->iPos = -1;
  85343. #endif
  85344. }
  85345. static void plwDestroy(PLWriter *pWriter){
  85346. SCRAMBLE(pWriter);
  85347. }
  85348. /*******************************************************************/
  85349. /* DLCollector wraps PLWriter and DLWriter to provide a
  85350. ** dynamically-allocated doclist area to use during tokenization.
  85351. **
  85352. ** dlcNew - malloc up and initialize a collector.
  85353. ** dlcDelete - destroy a collector and all contained items.
  85354. ** dlcAddPos - append position and offset information.
  85355. ** dlcAddDoclist - add the collected doclist to the given buffer.
  85356. ** dlcNext - terminate the current document and open another.
  85357. */
  85358. typedef struct DLCollector {
  85359. DataBuffer b;
  85360. DLWriter dlw;
  85361. PLWriter plw;
  85362. } DLCollector;
  85363. /* TODO(shess) This could also be done by calling plwTerminate() and
  85364. ** dataBufferAppend(). I tried that, expecting nominal performance
  85365. ** differences, but it seemed to pretty reliably be worth 1% to code
  85366. ** it this way. I suspect it is the incremental malloc overhead (some
  85367. ** percentage of the plwTerminate() calls will cause a realloc), so
  85368. ** this might be worth revisiting if the DataBuffer implementation
  85369. ** changes.
  85370. */
  85371. static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
  85372. if( pCollector->dlw.iType>DL_DOCIDS ){
  85373. char c[VARINT_MAX];
  85374. int n = fts3PutVarint(c, POS_END);
  85375. dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
  85376. }else{
  85377. dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
  85378. }
  85379. }
  85380. static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
  85381. plwTerminate(&pCollector->plw);
  85382. plwDestroy(&pCollector->plw);
  85383. plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
  85384. }
  85385. static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
  85386. int iStartOffset, int iEndOffset){
  85387. plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
  85388. }
  85389. static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
  85390. DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
  85391. dataBufferInit(&pCollector->b, 0);
  85392. dlwInit(&pCollector->dlw, iType, &pCollector->b);
  85393. plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
  85394. return pCollector;
  85395. }
  85396. static void dlcDelete(DLCollector *pCollector){
  85397. plwDestroy(&pCollector->plw);
  85398. dlwDestroy(&pCollector->dlw);
  85399. dataBufferDestroy(&pCollector->b);
  85400. SCRAMBLE(pCollector);
  85401. sqlite3_free(pCollector);
  85402. }
  85403. /* Copy the doclist data of iType in pData/nData into *out, trimming
  85404. ** unnecessary data as we go. Only columns matching iColumn are
  85405. ** copied, all columns copied if iColumn is -1. Elements with no
  85406. ** matching columns are dropped. The output is an iOutType doclist.
  85407. */
  85408. /* NOTE(shess) This code is only valid after all doclists are merged.
  85409. ** If this is run before merges, then doclist items which represent
  85410. ** deletion will be trimmed, and will thus not effect a deletion
  85411. ** during the merge.
  85412. */
  85413. static void docListTrim(DocListType iType, const char *pData, int nData,
  85414. int iColumn, DocListType iOutType, DataBuffer *out){
  85415. DLReader dlReader;
  85416. DLWriter dlWriter;
  85417. assert( iOutType<=iType );
  85418. dlrInit(&dlReader, iType, pData, nData);
  85419. dlwInit(&dlWriter, iOutType, out);
  85420. while( !dlrAtEnd(&dlReader) ){
  85421. PLReader plReader;
  85422. PLWriter plWriter;
  85423. int match = 0;
  85424. plrInit(&plReader, &dlReader);
  85425. while( !plrAtEnd(&plReader) ){
  85426. if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
  85427. if( !match ){
  85428. plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
  85429. match = 1;
  85430. }
  85431. plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
  85432. plrStartOffset(&plReader), plrEndOffset(&plReader));
  85433. }
  85434. plrStep(&plReader);
  85435. }
  85436. if( match ){
  85437. plwTerminate(&plWriter);
  85438. plwDestroy(&plWriter);
  85439. }
  85440. plrDestroy(&plReader);
  85441. dlrStep(&dlReader);
  85442. }
  85443. dlwDestroy(&dlWriter);
  85444. dlrDestroy(&dlReader);
  85445. }
  85446. /* Used by docListMerge() to keep doclists in the ascending order by
  85447. ** docid, then ascending order by age (so the newest comes first).
  85448. */
  85449. typedef struct OrderedDLReader {
  85450. DLReader *pReader;
  85451. /* TODO(shess) If we assume that docListMerge pReaders is ordered by
  85452. ** age (which we do), then we could use pReader comparisons to break
  85453. ** ties.
  85454. */
  85455. int idx;
  85456. } OrderedDLReader;
  85457. /* Order eof to end, then by docid asc, idx desc. */
  85458. static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
  85459. if( dlrAtEnd(r1->pReader) ){
  85460. if( dlrAtEnd(r2->pReader) ) return 0; /* Both atEnd(). */
  85461. return 1; /* Only r1 atEnd(). */
  85462. }
  85463. if( dlrAtEnd(r2->pReader) ) return -1; /* Only r2 atEnd(). */
  85464. if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
  85465. if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
  85466. /* Descending on idx. */
  85467. return r2->idx-r1->idx;
  85468. }
  85469. /* Bubble p[0] to appropriate place in p[1..n-1]. Assumes that
  85470. ** p[1..n-1] is already sorted.
  85471. */
  85472. /* TODO(shess) Is this frequent enough to warrant a binary search?
  85473. ** Before implementing that, instrument the code to check. In most
  85474. ** current usage, I expect that p[0] will be less than p[1] a very
  85475. ** high proportion of the time.
  85476. */
  85477. static void orderedDLReaderReorder(OrderedDLReader *p, int n){
  85478. while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
  85479. OrderedDLReader tmp = p[0];
  85480. p[0] = p[1];
  85481. p[1] = tmp;
  85482. n--;
  85483. p++;
  85484. }
  85485. }
  85486. /* Given an array of doclist readers, merge their doclist elements
  85487. ** into out in sorted order (by docid), dropping elements from older
  85488. ** readers when there is a duplicate docid. pReaders is assumed to be
  85489. ** ordered by age, oldest first.
  85490. */
  85491. /* TODO(shess) nReaders must be <= MERGE_COUNT. This should probably
  85492. ** be fixed.
  85493. */
  85494. static void docListMerge(DataBuffer *out,
  85495. DLReader *pReaders, int nReaders){
  85496. OrderedDLReader readers[MERGE_COUNT];
  85497. DLWriter writer;
  85498. int i, n;
  85499. const char *pStart = 0;
  85500. int nStart = 0;
  85501. sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
  85502. assert( nReaders>0 );
  85503. if( nReaders==1 ){
  85504. dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
  85505. return;
  85506. }
  85507. assert( nReaders<=MERGE_COUNT );
  85508. n = 0;
  85509. for(i=0; i<nReaders; i++){
  85510. assert( pReaders[i].iType==pReaders[0].iType );
  85511. readers[i].pReader = pReaders+i;
  85512. readers[i].idx = i;
  85513. n += dlrAllDataBytes(&pReaders[i]);
  85514. }
  85515. /* Conservatively size output to sum of inputs. Output should end
  85516. ** up strictly smaller than input.
  85517. */
  85518. dataBufferExpand(out, n);
  85519. /* Get the readers into sorted order. */
  85520. while( i-->0 ){
  85521. orderedDLReaderReorder(readers+i, nReaders-i);
  85522. }
  85523. dlwInit(&writer, pReaders[0].iType, out);
  85524. while( !dlrAtEnd(readers[0].pReader) ){
  85525. sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
  85526. /* If this is a continuation of the current buffer to copy, extend
  85527. ** that buffer. memcpy() seems to be more efficient if it has a
  85528. ** lots of data to copy.
  85529. */
  85530. if( dlrDocData(readers[0].pReader)==pStart+nStart ){
  85531. nStart += dlrDocDataBytes(readers[0].pReader);
  85532. }else{
  85533. if( pStart!=0 ){
  85534. dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
  85535. }
  85536. pStart = dlrDocData(readers[0].pReader);
  85537. nStart = dlrDocDataBytes(readers[0].pReader);
  85538. iFirstDocid = iDocid;
  85539. }
  85540. iLastDocid = iDocid;
  85541. dlrStep(readers[0].pReader);
  85542. /* Drop all of the older elements with the same docid. */
  85543. for(i=1; i<nReaders &&
  85544. !dlrAtEnd(readers[i].pReader) &&
  85545. dlrDocid(readers[i].pReader)==iDocid; i++){
  85546. dlrStep(readers[i].pReader);
  85547. }
  85548. /* Get the readers back into order. */
  85549. while( i-->0 ){
  85550. orderedDLReaderReorder(readers+i, nReaders-i);
  85551. }
  85552. }
  85553. /* Copy over any remaining elements. */
  85554. if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
  85555. dlwDestroy(&writer);
  85556. }
  85557. /* Helper function for posListUnion(). Compares the current position
  85558. ** between left and right, returning as standard C idiom of <0 if
  85559. ** left<right, >0 if left>right, and 0 if left==right. "End" always
  85560. ** compares greater.
  85561. */
  85562. static int posListCmp(PLReader *pLeft, PLReader *pRight){
  85563. assert( pLeft->iType==pRight->iType );
  85564. if( pLeft->iType==DL_DOCIDS ) return 0;
  85565. if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
  85566. if( plrAtEnd(pRight) ) return -1;
  85567. if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
  85568. if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
  85569. if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
  85570. if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
  85571. if( pLeft->iType==DL_POSITIONS ) return 0;
  85572. if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
  85573. if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
  85574. if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
  85575. if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
  85576. return 0;
  85577. }
  85578. /* Write the union of position lists in pLeft and pRight to pOut.
  85579. ** "Union" in this case meaning "All unique position tuples". Should
  85580. ** work with any doclist type, though both inputs and the output
  85581. ** should be the same type.
  85582. */
  85583. static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
  85584. PLReader left, right;
  85585. PLWriter writer;
  85586. assert( dlrDocid(pLeft)==dlrDocid(pRight) );
  85587. assert( pLeft->iType==pRight->iType );
  85588. assert( pLeft->iType==pOut->iType );
  85589. plrInit(&left, pLeft);
  85590. plrInit(&right, pRight);
  85591. plwInit(&writer, pOut, dlrDocid(pLeft));
  85592. while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
  85593. int c = posListCmp(&left, &right);
  85594. if( c<0 ){
  85595. plwCopy(&writer, &left);
  85596. plrStep(&left);
  85597. }else if( c>0 ){
  85598. plwCopy(&writer, &right);
  85599. plrStep(&right);
  85600. }else{
  85601. plwCopy(&writer, &left);
  85602. plrStep(&left);
  85603. plrStep(&right);
  85604. }
  85605. }
  85606. plwTerminate(&writer);
  85607. plwDestroy(&writer);
  85608. plrDestroy(&left);
  85609. plrDestroy(&right);
  85610. }
  85611. /* Write the union of doclists in pLeft and pRight to pOut. For
  85612. ** docids in common between the inputs, the union of the position
  85613. ** lists is written. Inputs and outputs are always type DL_DEFAULT.
  85614. */
  85615. static void docListUnion(
  85616. const char *pLeft, int nLeft,
  85617. const char *pRight, int nRight,
  85618. DataBuffer *pOut /* Write the combined doclist here */
  85619. ){
  85620. DLReader left, right;
  85621. DLWriter writer;
  85622. if( nLeft==0 ){
  85623. if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
  85624. return;
  85625. }
  85626. if( nRight==0 ){
  85627. dataBufferAppend(pOut, pLeft, nLeft);
  85628. return;
  85629. }
  85630. dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
  85631. dlrInit(&right, DL_DEFAULT, pRight, nRight);
  85632. dlwInit(&writer, DL_DEFAULT, pOut);
  85633. while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
  85634. if( dlrAtEnd(&right) ){
  85635. dlwCopy(&writer, &left);
  85636. dlrStep(&left);
  85637. }else if( dlrAtEnd(&left) ){
  85638. dlwCopy(&writer, &right);
  85639. dlrStep(&right);
  85640. }else if( dlrDocid(&left)<dlrDocid(&right) ){
  85641. dlwCopy(&writer, &left);
  85642. dlrStep(&left);
  85643. }else if( dlrDocid(&left)>dlrDocid(&right) ){
  85644. dlwCopy(&writer, &right);
  85645. dlrStep(&right);
  85646. }else{
  85647. posListUnion(&left, &right, &writer);
  85648. dlrStep(&left);
  85649. dlrStep(&right);
  85650. }
  85651. }
  85652. dlrDestroy(&left);
  85653. dlrDestroy(&right);
  85654. dlwDestroy(&writer);
  85655. }
  85656. /*
  85657. ** This function is used as part of the implementation of phrase and
  85658. ** NEAR matching.
  85659. **
  85660. ** pLeft and pRight are DLReaders positioned to the same docid in
  85661. ** lists of type DL_POSITION. This function writes an entry to the
  85662. ** DLWriter pOut for each position in pRight that is less than
  85663. ** (nNear+1) greater (but not equal to or smaller) than a position
  85664. ** in pLeft. For example, if nNear is 0, and the positions contained
  85665. ** by pLeft and pRight are:
  85666. **
  85667. ** pLeft: 5 10 15 20
  85668. ** pRight: 6 9 17 21
  85669. **
  85670. ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
  85671. ** then a positionids "6" and "21" are also added to pOut.
  85672. **
  85673. ** If boolean argument isSaveLeft is true, then positionids are copied
  85674. ** from pLeft instead of pRight. In the example above, the positions "5"
  85675. ** and "20" would be added instead of "6" and "21".
  85676. */
  85677. static void posListPhraseMerge(
  85678. DLReader *pLeft,
  85679. DLReader *pRight,
  85680. int nNear,
  85681. int isSaveLeft,
  85682. DLWriter *pOut
  85683. ){
  85684. PLReader left, right;
  85685. PLWriter writer;
  85686. int match = 0;
  85687. assert( dlrDocid(pLeft)==dlrDocid(pRight) );
  85688. assert( pOut->iType!=DL_POSITIONS_OFFSETS );
  85689. plrInit(&left, pLeft);
  85690. plrInit(&right, pRight);
  85691. while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
  85692. if( plrColumn(&left)<plrColumn(&right) ){
  85693. plrStep(&left);
  85694. }else if( plrColumn(&left)>plrColumn(&right) ){
  85695. plrStep(&right);
  85696. }else if( plrPosition(&left)>=plrPosition(&right) ){
  85697. plrStep(&right);
  85698. }else{
  85699. if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
  85700. if( !match ){
  85701. plwInit(&writer, pOut, dlrDocid(pLeft));
  85702. match = 1;
  85703. }
  85704. if( !isSaveLeft ){
  85705. plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
  85706. }else{
  85707. plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
  85708. }
  85709. plrStep(&right);
  85710. }else{
  85711. plrStep(&left);
  85712. }
  85713. }
  85714. }
  85715. if( match ){
  85716. plwTerminate(&writer);
  85717. plwDestroy(&writer);
  85718. }
  85719. plrDestroy(&left);
  85720. plrDestroy(&right);
  85721. }
  85722. /*
  85723. ** Compare the values pointed to by the PLReaders passed as arguments.
  85724. ** Return -1 if the value pointed to by pLeft is considered less than
  85725. ** the value pointed to by pRight, +1 if it is considered greater
  85726. ** than it, or 0 if it is equal. i.e.
  85727. **
  85728. ** (*pLeft - *pRight)
  85729. **
  85730. ** A PLReader that is in the EOF condition is considered greater than
  85731. ** any other. If neither argument is in EOF state, the return value of
  85732. ** plrColumn() is used. If the plrColumn() values are equal, the
  85733. ** comparison is on the basis of plrPosition().
  85734. */
  85735. static int plrCompare(PLReader *pLeft, PLReader *pRight){
  85736. assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
  85737. if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
  85738. return (plrAtEnd(pRight) ? -1 : 1);
  85739. }
  85740. if( plrColumn(pLeft)!=plrColumn(pRight) ){
  85741. return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
  85742. }
  85743. if( plrPosition(pLeft)!=plrPosition(pRight) ){
  85744. return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
  85745. }
  85746. return 0;
  85747. }
  85748. /* We have two doclists with positions: pLeft and pRight. Depending
  85749. ** on the value of the nNear parameter, perform either a phrase
  85750. ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
  85751. ** and write the results into pOut.
  85752. **
  85753. ** A phrase intersection means that two documents only match
  85754. ** if pLeft.iPos+1==pRight.iPos.
  85755. **
  85756. ** A NEAR intersection means that two documents only match if
  85757. ** (abs(pLeft.iPos-pRight.iPos)<nNear).
  85758. **
  85759. ** If a NEAR intersection is requested, then the nPhrase argument should
  85760. ** be passed the number of tokens in the two operands to the NEAR operator
  85761. ** combined. For example:
  85762. **
  85763. ** Query syntax nPhrase
  85764. ** ------------------------------------
  85765. ** "A B C" NEAR "D E" 5
  85766. ** A NEAR B 2
  85767. **
  85768. ** iType controls the type of data written to pOut. If iType is
  85769. ** DL_POSITIONS, the positions are those from pRight.
  85770. */
  85771. static void docListPhraseMerge(
  85772. const char *pLeft, int nLeft,
  85773. const char *pRight, int nRight,
  85774. int nNear, /* 0 for a phrase merge, non-zero for a NEAR merge */
  85775. int nPhrase, /* Number of tokens in left+right operands to NEAR */
  85776. DocListType iType, /* Type of doclist to write to pOut */
  85777. DataBuffer *pOut /* Write the combined doclist here */
  85778. ){
  85779. DLReader left, right;
  85780. DLWriter writer;
  85781. if( nLeft==0 || nRight==0 ) return;
  85782. assert( iType!=DL_POSITIONS_OFFSETS );
  85783. dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
  85784. dlrInit(&right, DL_POSITIONS, pRight, nRight);
  85785. dlwInit(&writer, iType, pOut);
  85786. while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
  85787. if( dlrDocid(&left)<dlrDocid(&right) ){
  85788. dlrStep(&left);
  85789. }else if( dlrDocid(&right)<dlrDocid(&left) ){
  85790. dlrStep(&right);
  85791. }else{
  85792. if( nNear==0 ){
  85793. posListPhraseMerge(&left, &right, 0, 0, &writer);
  85794. }else{
  85795. /* This case occurs when two terms (simple terms or phrases) are
  85796. * connected by a NEAR operator, span (nNear+1). i.e.
  85797. *
  85798. * '"terrible company" NEAR widget'
  85799. */
  85800. DataBuffer one = {0, 0, 0};
  85801. DataBuffer two = {0, 0, 0};
  85802. DLWriter dlwriter2;
  85803. DLReader dr1 = {0, 0, 0, 0, 0};
  85804. DLReader dr2 = {0, 0, 0, 0, 0};
  85805. dlwInit(&dlwriter2, iType, &one);
  85806. posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
  85807. dlwInit(&dlwriter2, iType, &two);
  85808. posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
  85809. if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
  85810. if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
  85811. if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
  85812. PLReader pr1 = {0};
  85813. PLReader pr2 = {0};
  85814. PLWriter plwriter;
  85815. plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
  85816. if( one.nData ) plrInit(&pr1, &dr1);
  85817. if( two.nData ) plrInit(&pr2, &dr2);
  85818. while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
  85819. int iCompare = plrCompare(&pr1, &pr2);
  85820. switch( iCompare ){
  85821. case -1:
  85822. plwCopy(&plwriter, &pr1);
  85823. plrStep(&pr1);
  85824. break;
  85825. case 1:
  85826. plwCopy(&plwriter, &pr2);
  85827. plrStep(&pr2);
  85828. break;
  85829. case 0:
  85830. plwCopy(&plwriter, &pr1);
  85831. plrStep(&pr1);
  85832. plrStep(&pr2);
  85833. break;
  85834. }
  85835. }
  85836. plwTerminate(&plwriter);
  85837. }
  85838. dataBufferDestroy(&one);
  85839. dataBufferDestroy(&two);
  85840. }
  85841. dlrStep(&left);
  85842. dlrStep(&right);
  85843. }
  85844. }
  85845. dlrDestroy(&left);
  85846. dlrDestroy(&right);
  85847. dlwDestroy(&writer);
  85848. }
  85849. /* We have two DL_DOCIDS doclists: pLeft and pRight.
  85850. ** Write the intersection of these two doclists into pOut as a
  85851. ** DL_DOCIDS doclist.
  85852. */
  85853. static void docListAndMerge(
  85854. const char *pLeft, int nLeft,
  85855. const char *pRight, int nRight,
  85856. DataBuffer *pOut /* Write the combined doclist here */
  85857. ){
  85858. DLReader left, right;
  85859. DLWriter writer;
  85860. if( nLeft==0 || nRight==0 ) return;
  85861. dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  85862. dlrInit(&right, DL_DOCIDS, pRight, nRight);
  85863. dlwInit(&writer, DL_DOCIDS, pOut);
  85864. while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
  85865. if( dlrDocid(&left)<dlrDocid(&right) ){
  85866. dlrStep(&left);
  85867. }else if( dlrDocid(&right)<dlrDocid(&left) ){
  85868. dlrStep(&right);
  85869. }else{
  85870. dlwAdd(&writer, dlrDocid(&left));
  85871. dlrStep(&left);
  85872. dlrStep(&right);
  85873. }
  85874. }
  85875. dlrDestroy(&left);
  85876. dlrDestroy(&right);
  85877. dlwDestroy(&writer);
  85878. }
  85879. /* We have two DL_DOCIDS doclists: pLeft and pRight.
  85880. ** Write the union of these two doclists into pOut as a
  85881. ** DL_DOCIDS doclist.
  85882. */
  85883. static void docListOrMerge(
  85884. const char *pLeft, int nLeft,
  85885. const char *pRight, int nRight,
  85886. DataBuffer *pOut /* Write the combined doclist here */
  85887. ){
  85888. DLReader left, right;
  85889. DLWriter writer;
  85890. if( nLeft==0 ){
  85891. if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
  85892. return;
  85893. }
  85894. if( nRight==0 ){
  85895. dataBufferAppend(pOut, pLeft, nLeft);
  85896. return;
  85897. }
  85898. dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  85899. dlrInit(&right, DL_DOCIDS, pRight, nRight);
  85900. dlwInit(&writer, DL_DOCIDS, pOut);
  85901. while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
  85902. if( dlrAtEnd(&right) ){
  85903. dlwAdd(&writer, dlrDocid(&left));
  85904. dlrStep(&left);
  85905. }else if( dlrAtEnd(&left) ){
  85906. dlwAdd(&writer, dlrDocid(&right));
  85907. dlrStep(&right);
  85908. }else if( dlrDocid(&left)<dlrDocid(&right) ){
  85909. dlwAdd(&writer, dlrDocid(&left));
  85910. dlrStep(&left);
  85911. }else if( dlrDocid(&right)<dlrDocid(&left) ){
  85912. dlwAdd(&writer, dlrDocid(&right));
  85913. dlrStep(&right);
  85914. }else{
  85915. dlwAdd(&writer, dlrDocid(&left));
  85916. dlrStep(&left);
  85917. dlrStep(&right);
  85918. }
  85919. }
  85920. dlrDestroy(&left);
  85921. dlrDestroy(&right);
  85922. dlwDestroy(&writer);
  85923. }
  85924. /* We have two DL_DOCIDS doclists: pLeft and pRight.
  85925. ** Write into pOut as DL_DOCIDS doclist containing all documents that
  85926. ** occur in pLeft but not in pRight.
  85927. */
  85928. static void docListExceptMerge(
  85929. const char *pLeft, int nLeft,
  85930. const char *pRight, int nRight,
  85931. DataBuffer *pOut /* Write the combined doclist here */
  85932. ){
  85933. DLReader left, right;
  85934. DLWriter writer;
  85935. if( nLeft==0 ) return;
  85936. if( nRight==0 ){
  85937. dataBufferAppend(pOut, pLeft, nLeft);
  85938. return;
  85939. }
  85940. dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  85941. dlrInit(&right, DL_DOCIDS, pRight, nRight);
  85942. dlwInit(&writer, DL_DOCIDS, pOut);
  85943. while( !dlrAtEnd(&left) ){
  85944. while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
  85945. dlrStep(&right);
  85946. }
  85947. if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
  85948. dlwAdd(&writer, dlrDocid(&left));
  85949. }
  85950. dlrStep(&left);
  85951. }
  85952. dlrDestroy(&left);
  85953. dlrDestroy(&right);
  85954. dlwDestroy(&writer);
  85955. }
  85956. static char *string_dup_n(const char *s, int n){
  85957. char *str = sqlite3_malloc(n + 1);
  85958. memcpy(str, s, n);
  85959. str[n] = '\0';
  85960. return str;
  85961. }
  85962. /* Duplicate a string; the caller must free() the returned string.
  85963. * (We don't use strdup() since it is not part of the standard C library and
  85964. * may not be available everywhere.) */
  85965. static char *string_dup(const char *s){
  85966. return string_dup_n(s, strlen(s));
  85967. }
  85968. /* Format a string, replacing each occurrence of the % character with
  85969. * zDb.zName. This may be more convenient than sqlite_mprintf()
  85970. * when one string is used repeatedly in a format string.
  85971. * The caller must free() the returned string. */
  85972. static char *string_format(const char *zFormat,
  85973. const char *zDb, const char *zName){
  85974. const char *p;
  85975. size_t len = 0;
  85976. size_t nDb = strlen(zDb);
  85977. size_t nName = strlen(zName);
  85978. size_t nFullTableName = nDb+1+nName;
  85979. char *result;
  85980. char *r;
  85981. /* first compute length needed */
  85982. for(p = zFormat ; *p ; ++p){
  85983. len += (*p=='%' ? nFullTableName : 1);
  85984. }
  85985. len += 1; /* for null terminator */
  85986. r = result = sqlite3_malloc(len);
  85987. for(p = zFormat; *p; ++p){
  85988. if( *p=='%' ){
  85989. memcpy(r, zDb, nDb);
  85990. r += nDb;
  85991. *r++ = '.';
  85992. memcpy(r, zName, nName);
  85993. r += nName;
  85994. } else {
  85995. *r++ = *p;
  85996. }
  85997. }
  85998. *r++ = '\0';
  85999. assert( r == result + len );
  86000. return result;
  86001. }
  86002. static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
  86003. const char *zFormat){
  86004. char *zCommand = string_format(zFormat, zDb, zName);
  86005. int rc;
  86006. FTSTRACE(("FTS3 sql: %s\n", zCommand));
  86007. rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
  86008. sqlite3_free(zCommand);
  86009. return rc;
  86010. }
  86011. static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
  86012. sqlite3_stmt **ppStmt, const char *zFormat){
  86013. char *zCommand = string_format(zFormat, zDb, zName);
  86014. int rc;
  86015. FTSTRACE(("FTS3 prepare: %s\n", zCommand));
  86016. rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
  86017. sqlite3_free(zCommand);
  86018. return rc;
  86019. }
  86020. /* end utility functions */
  86021. /* Forward reference */
  86022. typedef struct fulltext_vtab fulltext_vtab;
  86023. /*
  86024. ** An instance of the following structure keeps track of generated
  86025. ** matching-word offset information and snippets.
  86026. */
  86027. typedef struct Snippet {
  86028. int nMatch; /* Total number of matches */
  86029. int nAlloc; /* Space allocated for aMatch[] */
  86030. struct snippetMatch { /* One entry for each matching term */
  86031. char snStatus; /* Status flag for use while constructing snippets */
  86032. short int iCol; /* The column that contains the match */
  86033. short int iTerm; /* The index in Query.pTerms[] of the matching term */
  86034. int iToken; /* The index of the matching document token */
  86035. short int nByte; /* Number of bytes in the term */
  86036. int iStart; /* The offset to the first character of the term */
  86037. } *aMatch; /* Points to space obtained from malloc */
  86038. char *zOffset; /* Text rendering of aMatch[] */
  86039. int nOffset; /* strlen(zOffset) */
  86040. char *zSnippet; /* Snippet text */
  86041. int nSnippet; /* strlen(zSnippet) */
  86042. } Snippet;
  86043. typedef enum QueryType {
  86044. QUERY_GENERIC, /* table scan */
  86045. QUERY_DOCID, /* lookup by docid */
  86046. QUERY_FULLTEXT /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
  86047. } QueryType;
  86048. typedef enum fulltext_statement {
  86049. CONTENT_INSERT_STMT,
  86050. CONTENT_SELECT_STMT,
  86051. CONTENT_UPDATE_STMT,
  86052. CONTENT_DELETE_STMT,
  86053. CONTENT_EXISTS_STMT,
  86054. BLOCK_INSERT_STMT,
  86055. BLOCK_SELECT_STMT,
  86056. BLOCK_DELETE_STMT,
  86057. BLOCK_DELETE_ALL_STMT,
  86058. SEGDIR_MAX_INDEX_STMT,
  86059. SEGDIR_SET_STMT,
  86060. SEGDIR_SELECT_LEVEL_STMT,
  86061. SEGDIR_SPAN_STMT,
  86062. SEGDIR_DELETE_STMT,
  86063. SEGDIR_SELECT_SEGMENT_STMT,
  86064. SEGDIR_SELECT_ALL_STMT,
  86065. SEGDIR_DELETE_ALL_STMT,
  86066. SEGDIR_COUNT_STMT,
  86067. MAX_STMT /* Always at end! */
  86068. } fulltext_statement;
  86069. /* These must exactly match the enum above. */
  86070. /* TODO(shess): Is there some risk that a statement will be used in two
  86071. ** cursors at once, e.g. if a query joins a virtual table to itself?
  86072. ** If so perhaps we should move some of these to the cursor object.
  86073. */
  86074. static const char *const fulltext_zStatement[MAX_STMT] = {
  86075. /* CONTENT_INSERT */ NULL, /* generated in contentInsertStatement() */
  86076. /* CONTENT_SELECT */ NULL, /* generated in contentSelectStatement() */
  86077. /* CONTENT_UPDATE */ NULL, /* generated in contentUpdateStatement() */
  86078. /* CONTENT_DELETE */ "delete from %_content where docid = ?",
  86079. /* CONTENT_EXISTS */ "select docid from %_content limit 1",
  86080. /* BLOCK_INSERT */
  86081. "insert into %_segments (blockid, block) values (null, ?)",
  86082. /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
  86083. /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
  86084. /* BLOCK_DELETE_ALL */ "delete from %_segments",
  86085. /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
  86086. /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
  86087. /* SEGDIR_SELECT_LEVEL */
  86088. "select start_block, leaves_end_block, root from %_segdir "
  86089. " where level = ? order by idx",
  86090. /* SEGDIR_SPAN */
  86091. "select min(start_block), max(end_block) from %_segdir "
  86092. " where level = ? and start_block <> 0",
  86093. /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
  86094. /* NOTE(shess): The first three results of the following two
  86095. ** statements must match.
  86096. */
  86097. /* SEGDIR_SELECT_SEGMENT */
  86098. "select start_block, leaves_end_block, root from %_segdir "
  86099. " where level = ? and idx = ?",
  86100. /* SEGDIR_SELECT_ALL */
  86101. "select start_block, leaves_end_block, root from %_segdir "
  86102. " order by level desc, idx asc",
  86103. /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
  86104. /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
  86105. };
  86106. /*
  86107. ** A connection to a fulltext index is an instance of the following
  86108. ** structure. The xCreate and xConnect methods create an instance
  86109. ** of this structure and xDestroy and xDisconnect free that instance.
  86110. ** All other methods receive a pointer to the structure as one of their
  86111. ** arguments.
  86112. */
  86113. struct fulltext_vtab {
  86114. sqlite3_vtab base; /* Base class used by SQLite core */
  86115. sqlite3 *db; /* The database connection */
  86116. const char *zDb; /* logical database name */
  86117. const char *zName; /* virtual table name */
  86118. int nColumn; /* number of columns in virtual table */
  86119. char **azColumn; /* column names. malloced */
  86120. char **azContentColumn; /* column names in content table; malloced */
  86121. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  86122. /* Precompiled statements which we keep as long as the table is
  86123. ** open.
  86124. */
  86125. sqlite3_stmt *pFulltextStatements[MAX_STMT];
  86126. /* Precompiled statements used for segment merges. We run a
  86127. ** separate select across the leaf level of each tree being merged.
  86128. */
  86129. sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
  86130. /* The statement used to prepare pLeafSelectStmts. */
  86131. #define LEAF_SELECT \
  86132. "select block from %_segments where blockid between ? and ? order by blockid"
  86133. /* These buffer pending index updates during transactions.
  86134. ** nPendingData estimates the memory size of the pending data. It
  86135. ** doesn't include the hash-bucket overhead, nor any malloc
  86136. ** overhead. When nPendingData exceeds kPendingThreshold, the
  86137. ** buffer is flushed even before the transaction closes.
  86138. ** pendingTerms stores the data, and is only valid when nPendingData
  86139. ** is >=0 (nPendingData<0 means pendingTerms has not been
  86140. ** initialized). iPrevDocid is the last docid written, used to make
  86141. ** certain we're inserting in sorted order.
  86142. */
  86143. int nPendingData;
  86144. #define kPendingThreshold (1*1024*1024)
  86145. sqlite_int64 iPrevDocid;
  86146. fts3Hash pendingTerms;
  86147. };
  86148. /*
  86149. ** When the core wants to do a query, it create a cursor using a
  86150. ** call to xOpen. This structure is an instance of a cursor. It
  86151. ** is destroyed by xClose.
  86152. */
  86153. typedef struct fulltext_cursor {
  86154. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  86155. QueryType iCursorType; /* Copy of sqlite3_index_info.idxNum */
  86156. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  86157. int eof; /* True if at End Of Results */
  86158. Fts3Expr *pExpr; /* Parsed MATCH query string */
  86159. Snippet snippet; /* Cached snippet for the current row */
  86160. int iColumn; /* Column being searched */
  86161. DataBuffer result; /* Doclist results from fulltextQuery */
  86162. DLReader reader; /* Result reader if result not empty */
  86163. } fulltext_cursor;
  86164. static fulltext_vtab *cursor_vtab(fulltext_cursor *c){
  86165. return (fulltext_vtab *) c->base.pVtab;
  86166. }
  86167. static const sqlite3_module fts3Module; /* forward declaration */
  86168. /* Return a dynamically generated statement of the form
  86169. * insert into %_content (docid, ...) values (?, ...)
  86170. */
  86171. static const char *contentInsertStatement(fulltext_vtab *v){
  86172. StringBuffer sb;
  86173. int i;
  86174. initStringBuffer(&sb);
  86175. append(&sb, "insert into %_content (docid, ");
  86176. appendList(&sb, v->nColumn, v->azContentColumn);
  86177. append(&sb, ") values (?");
  86178. for(i=0; i<v->nColumn; ++i)
  86179. append(&sb, ", ?");
  86180. append(&sb, ")");
  86181. return stringBufferData(&sb);
  86182. }
  86183. /* Return a dynamically generated statement of the form
  86184. * select <content columns> from %_content where docid = ?
  86185. */
  86186. static const char *contentSelectStatement(fulltext_vtab *v){
  86187. StringBuffer sb;
  86188. initStringBuffer(&sb);
  86189. append(&sb, "SELECT ");
  86190. appendList(&sb, v->nColumn, v->azContentColumn);
  86191. append(&sb, " FROM %_content WHERE docid = ?");
  86192. return stringBufferData(&sb);
  86193. }
  86194. /* Return a dynamically generated statement of the form
  86195. * update %_content set [col_0] = ?, [col_1] = ?, ...
  86196. * where docid = ?
  86197. */
  86198. static const char *contentUpdateStatement(fulltext_vtab *v){
  86199. StringBuffer sb;
  86200. int i;
  86201. initStringBuffer(&sb);
  86202. append(&sb, "update %_content set ");
  86203. for(i=0; i<v->nColumn; ++i) {
  86204. if( i>0 ){
  86205. append(&sb, ", ");
  86206. }
  86207. append(&sb, v->azContentColumn[i]);
  86208. append(&sb, " = ?");
  86209. }
  86210. append(&sb, " where docid = ?");
  86211. return stringBufferData(&sb);
  86212. }
  86213. /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
  86214. ** If the indicated statement has never been prepared, it is prepared
  86215. ** and cached, otherwise the cached version is reset.
  86216. */
  86217. static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
  86218. sqlite3_stmt **ppStmt){
  86219. assert( iStmt<MAX_STMT );
  86220. if( v->pFulltextStatements[iStmt]==NULL ){
  86221. const char *zStmt;
  86222. int rc;
  86223. switch( iStmt ){
  86224. case CONTENT_INSERT_STMT:
  86225. zStmt = contentInsertStatement(v); break;
  86226. case CONTENT_SELECT_STMT:
  86227. zStmt = contentSelectStatement(v); break;
  86228. case CONTENT_UPDATE_STMT:
  86229. zStmt = contentUpdateStatement(v); break;
  86230. default:
  86231. zStmt = fulltext_zStatement[iStmt];
  86232. }
  86233. rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
  86234. zStmt);
  86235. if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
  86236. if( rc!=SQLITE_OK ) return rc;
  86237. } else {
  86238. int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
  86239. if( rc!=SQLITE_OK ) return rc;
  86240. }
  86241. *ppStmt = v->pFulltextStatements[iStmt];
  86242. return SQLITE_OK;
  86243. }
  86244. /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
  86245. ** SQLITE_ROW to SQLITE_ERROR. Useful for statements like UPDATE,
  86246. ** where we expect no results.
  86247. */
  86248. static int sql_single_step(sqlite3_stmt *s){
  86249. int rc = sqlite3_step(s);
  86250. return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
  86251. }
  86252. /* Like sql_get_statement(), but for special replicated LEAF_SELECT
  86253. ** statements. idx -1 is a special case for an uncached version of
  86254. ** the statement (used in the optimize implementation).
  86255. */
  86256. /* TODO(shess) Write version for generic statements and then share
  86257. ** that between the cached-statement functions.
  86258. */
  86259. static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
  86260. sqlite3_stmt **ppStmt){
  86261. assert( idx>=-1 && idx<MERGE_COUNT );
  86262. if( idx==-1 ){
  86263. return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
  86264. }else if( v->pLeafSelectStmts[idx]==NULL ){
  86265. int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
  86266. LEAF_SELECT);
  86267. if( rc!=SQLITE_OK ) return rc;
  86268. }else{
  86269. int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
  86270. if( rc!=SQLITE_OK ) return rc;
  86271. }
  86272. *ppStmt = v->pLeafSelectStmts[idx];
  86273. return SQLITE_OK;
  86274. }
  86275. /* insert into %_content (docid, ...) values ([docid], [pValues])
  86276. ** If the docid contains SQL NULL, then a unique docid will be
  86277. ** generated.
  86278. */
  86279. static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
  86280. sqlite3_value **pValues){
  86281. sqlite3_stmt *s;
  86282. int i;
  86283. int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
  86284. if( rc!=SQLITE_OK ) return rc;
  86285. rc = sqlite3_bind_value(s, 1, docid);
  86286. if( rc!=SQLITE_OK ) return rc;
  86287. for(i=0; i<v->nColumn; ++i){
  86288. rc = sqlite3_bind_value(s, 2+i, pValues[i]);
  86289. if( rc!=SQLITE_OK ) return rc;
  86290. }
  86291. return sql_single_step(s);
  86292. }
  86293. /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
  86294. * where docid = [iDocid] */
  86295. static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
  86296. sqlite_int64 iDocid){
  86297. sqlite3_stmt *s;
  86298. int i;
  86299. int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
  86300. if( rc!=SQLITE_OK ) return rc;
  86301. for(i=0; i<v->nColumn; ++i){
  86302. rc = sqlite3_bind_value(s, 1+i, pValues[i]);
  86303. if( rc!=SQLITE_OK ) return rc;
  86304. }
  86305. rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
  86306. if( rc!=SQLITE_OK ) return rc;
  86307. return sql_single_step(s);
  86308. }
  86309. static void freeStringArray(int nString, const char **pString){
  86310. int i;
  86311. for (i=0 ; i < nString ; ++i) {
  86312. if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
  86313. }
  86314. sqlite3_free((void *) pString);
  86315. }
  86316. /* select * from %_content where docid = [iDocid]
  86317. * The caller must delete the returned array and all strings in it.
  86318. * null fields will be NULL in the returned array.
  86319. *
  86320. * TODO: Perhaps we should return pointer/length strings here for consistency
  86321. * with other code which uses pointer/length. */
  86322. static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
  86323. const char ***pValues){
  86324. sqlite3_stmt *s;
  86325. const char **values;
  86326. int i;
  86327. int rc;
  86328. *pValues = NULL;
  86329. rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
  86330. if( rc!=SQLITE_OK ) return rc;
  86331. rc = sqlite3_bind_int64(s, 1, iDocid);
  86332. if( rc!=SQLITE_OK ) return rc;
  86333. rc = sqlite3_step(s);
  86334. if( rc!=SQLITE_ROW ) return rc;
  86335. values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
  86336. for(i=0; i<v->nColumn; ++i){
  86337. if( sqlite3_column_type(s, i)==SQLITE_NULL ){
  86338. values[i] = NULL;
  86339. }else{
  86340. values[i] = string_dup((char*)sqlite3_column_text(s, i));
  86341. }
  86342. }
  86343. /* We expect only one row. We must execute another sqlite3_step()
  86344. * to complete the iteration; otherwise the table will remain locked. */
  86345. rc = sqlite3_step(s);
  86346. if( rc==SQLITE_DONE ){
  86347. *pValues = values;
  86348. return SQLITE_OK;
  86349. }
  86350. freeStringArray(v->nColumn, values);
  86351. return rc;
  86352. }
  86353. /* delete from %_content where docid = [iDocid ] */
  86354. static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
  86355. sqlite3_stmt *s;
  86356. int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
  86357. if( rc!=SQLITE_OK ) return rc;
  86358. rc = sqlite3_bind_int64(s, 1, iDocid);
  86359. if( rc!=SQLITE_OK ) return rc;
  86360. return sql_single_step(s);
  86361. }
  86362. /* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
  86363. ** no rows exist, and any error in case of failure.
  86364. */
  86365. static int content_exists(fulltext_vtab *v){
  86366. sqlite3_stmt *s;
  86367. int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
  86368. if( rc!=SQLITE_OK ) return rc;
  86369. rc = sqlite3_step(s);
  86370. if( rc!=SQLITE_ROW ) return rc;
  86371. /* We expect only one row. We must execute another sqlite3_step()
  86372. * to complete the iteration; otherwise the table will remain locked. */
  86373. rc = sqlite3_step(s);
  86374. if( rc==SQLITE_DONE ) return SQLITE_ROW;
  86375. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  86376. return rc;
  86377. }
  86378. /* insert into %_segments values ([pData])
  86379. ** returns assigned blockid in *piBlockid
  86380. */
  86381. static int block_insert(fulltext_vtab *v, const char *pData, int nData,
  86382. sqlite_int64 *piBlockid){
  86383. sqlite3_stmt *s;
  86384. int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
  86385. if( rc!=SQLITE_OK ) return rc;
  86386. rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
  86387. if( rc!=SQLITE_OK ) return rc;
  86388. rc = sqlite3_step(s);
  86389. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  86390. if( rc!=SQLITE_DONE ) return rc;
  86391. /* blockid column is an alias for rowid. */
  86392. *piBlockid = sqlite3_last_insert_rowid(v->db);
  86393. return SQLITE_OK;
  86394. }
  86395. /* delete from %_segments
  86396. ** where blockid between [iStartBlockid] and [iEndBlockid]
  86397. **
  86398. ** Deletes the range of blocks, inclusive, used to delete the blocks
  86399. ** which form a segment.
  86400. */
  86401. static int block_delete(fulltext_vtab *v,
  86402. sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
  86403. sqlite3_stmt *s;
  86404. int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
  86405. if( rc!=SQLITE_OK ) return rc;
  86406. rc = sqlite3_bind_int64(s, 1, iStartBlockid);
  86407. if( rc!=SQLITE_OK ) return rc;
  86408. rc = sqlite3_bind_int64(s, 2, iEndBlockid);
  86409. if( rc!=SQLITE_OK ) return rc;
  86410. return sql_single_step(s);
  86411. }
  86412. /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
  86413. ** at iLevel. Returns SQLITE_DONE if there are no segments at
  86414. ** iLevel. Otherwise returns an error.
  86415. */
  86416. static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
  86417. sqlite3_stmt *s;
  86418. int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
  86419. if( rc!=SQLITE_OK ) return rc;
  86420. rc = sqlite3_bind_int(s, 1, iLevel);
  86421. if( rc!=SQLITE_OK ) return rc;
  86422. rc = sqlite3_step(s);
  86423. /* Should always get at least one row due to how max() works. */
  86424. if( rc==SQLITE_DONE ) return SQLITE_DONE;
  86425. if( rc!=SQLITE_ROW ) return rc;
  86426. /* NULL means that there were no inputs to max(). */
  86427. if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
  86428. rc = sqlite3_step(s);
  86429. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  86430. return rc;
  86431. }
  86432. *pidx = sqlite3_column_int(s, 0);
  86433. /* We expect only one row. We must execute another sqlite3_step()
  86434. * to complete the iteration; otherwise the table will remain locked. */
  86435. rc = sqlite3_step(s);
  86436. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  86437. if( rc!=SQLITE_DONE ) return rc;
  86438. return SQLITE_ROW;
  86439. }
  86440. /* insert into %_segdir values (
  86441. ** [iLevel], [idx],
  86442. ** [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
  86443. ** [pRootData]
  86444. ** )
  86445. */
  86446. static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
  86447. sqlite_int64 iStartBlockid,
  86448. sqlite_int64 iLeavesEndBlockid,
  86449. sqlite_int64 iEndBlockid,
  86450. const char *pRootData, int nRootData){
  86451. sqlite3_stmt *s;
  86452. int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
  86453. if( rc!=SQLITE_OK ) return rc;
  86454. rc = sqlite3_bind_int(s, 1, iLevel);
  86455. if( rc!=SQLITE_OK ) return rc;
  86456. rc = sqlite3_bind_int(s, 2, idx);
  86457. if( rc!=SQLITE_OK ) return rc;
  86458. rc = sqlite3_bind_int64(s, 3, iStartBlockid);
  86459. if( rc!=SQLITE_OK ) return rc;
  86460. rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
  86461. if( rc!=SQLITE_OK ) return rc;
  86462. rc = sqlite3_bind_int64(s, 5, iEndBlockid);
  86463. if( rc!=SQLITE_OK ) return rc;
  86464. rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
  86465. if( rc!=SQLITE_OK ) return rc;
  86466. return sql_single_step(s);
  86467. }
  86468. /* Queries %_segdir for the block span of the segments in level
  86469. ** iLevel. Returns SQLITE_DONE if there are no blocks for iLevel,
  86470. ** SQLITE_ROW if there are blocks, else an error.
  86471. */
  86472. static int segdir_span(fulltext_vtab *v, int iLevel,
  86473. sqlite_int64 *piStartBlockid,
  86474. sqlite_int64 *piEndBlockid){
  86475. sqlite3_stmt *s;
  86476. int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
  86477. if( rc!=SQLITE_OK ) return rc;
  86478. rc = sqlite3_bind_int(s, 1, iLevel);
  86479. if( rc!=SQLITE_OK ) return rc;
  86480. rc = sqlite3_step(s);
  86481. if( rc==SQLITE_DONE ) return SQLITE_DONE; /* Should never happen */
  86482. if( rc!=SQLITE_ROW ) return rc;
  86483. /* This happens if all segments at this level are entirely inline. */
  86484. if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
  86485. /* We expect only one row. We must execute another sqlite3_step()
  86486. * to complete the iteration; otherwise the table will remain locked. */
  86487. int rc2 = sqlite3_step(s);
  86488. if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
  86489. return rc2;
  86490. }
  86491. *piStartBlockid = sqlite3_column_int64(s, 0);
  86492. *piEndBlockid = sqlite3_column_int64(s, 1);
  86493. /* We expect only one row. We must execute another sqlite3_step()
  86494. * to complete the iteration; otherwise the table will remain locked. */
  86495. rc = sqlite3_step(s);
  86496. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  86497. if( rc!=SQLITE_DONE ) return rc;
  86498. return SQLITE_ROW;
  86499. }
  86500. /* Delete the segment blocks and segment directory records for all
  86501. ** segments at iLevel.
  86502. */
  86503. static int segdir_delete(fulltext_vtab *v, int iLevel){
  86504. sqlite3_stmt *s;
  86505. sqlite_int64 iStartBlockid, iEndBlockid;
  86506. int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
  86507. if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
  86508. if( rc==SQLITE_ROW ){
  86509. rc = block_delete(v, iStartBlockid, iEndBlockid);
  86510. if( rc!=SQLITE_OK ) return rc;
  86511. }
  86512. /* Delete the segment directory itself. */
  86513. rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
  86514. if( rc!=SQLITE_OK ) return rc;
  86515. rc = sqlite3_bind_int64(s, 1, iLevel);
  86516. if( rc!=SQLITE_OK ) return rc;
  86517. return sql_single_step(s);
  86518. }
  86519. /* Delete entire fts index, SQLITE_OK on success, relevant error on
  86520. ** failure.
  86521. */
  86522. static int segdir_delete_all(fulltext_vtab *v){
  86523. sqlite3_stmt *s;
  86524. int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
  86525. if( rc!=SQLITE_OK ) return rc;
  86526. rc = sql_single_step(s);
  86527. if( rc!=SQLITE_OK ) return rc;
  86528. rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
  86529. if( rc!=SQLITE_OK ) return rc;
  86530. return sql_single_step(s);
  86531. }
  86532. /* Returns SQLITE_OK with *pnSegments set to the number of entries in
  86533. ** %_segdir and *piMaxLevel set to the highest level which has a
  86534. ** segment. Otherwise returns the SQLite error which caused failure.
  86535. */
  86536. static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
  86537. sqlite3_stmt *s;
  86538. int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
  86539. if( rc!=SQLITE_OK ) return rc;
  86540. rc = sqlite3_step(s);
  86541. /* TODO(shess): This case should not be possible? Should stronger
  86542. ** measures be taken if it happens?
  86543. */
  86544. if( rc==SQLITE_DONE ){
  86545. *pnSegments = 0;
  86546. *piMaxLevel = 0;
  86547. return SQLITE_OK;
  86548. }
  86549. if( rc!=SQLITE_ROW ) return rc;
  86550. *pnSegments = sqlite3_column_int(s, 0);
  86551. *piMaxLevel = sqlite3_column_int(s, 1);
  86552. /* We expect only one row. We must execute another sqlite3_step()
  86553. * to complete the iteration; otherwise the table will remain locked. */
  86554. rc = sqlite3_step(s);
  86555. if( rc==SQLITE_DONE ) return SQLITE_OK;
  86556. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  86557. return rc;
  86558. }
  86559. /* TODO(shess) clearPendingTerms() is far down the file because
  86560. ** writeZeroSegment() is far down the file because LeafWriter is far
  86561. ** down the file. Consider refactoring the code to move the non-vtab
  86562. ** code above the vtab code so that we don't need this forward
  86563. ** reference.
  86564. */
  86565. static int clearPendingTerms(fulltext_vtab *v);
  86566. /*
  86567. ** Free the memory used to contain a fulltext_vtab structure.
  86568. */
  86569. static void fulltext_vtab_destroy(fulltext_vtab *v){
  86570. int iStmt, i;
  86571. FTSTRACE(("FTS3 Destroy %p\n", v));
  86572. for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
  86573. if( v->pFulltextStatements[iStmt]!=NULL ){
  86574. sqlite3_finalize(v->pFulltextStatements[iStmt]);
  86575. v->pFulltextStatements[iStmt] = NULL;
  86576. }
  86577. }
  86578. for( i=0; i<MERGE_COUNT; i++ ){
  86579. if( v->pLeafSelectStmts[i]!=NULL ){
  86580. sqlite3_finalize(v->pLeafSelectStmts[i]);
  86581. v->pLeafSelectStmts[i] = NULL;
  86582. }
  86583. }
  86584. if( v->pTokenizer!=NULL ){
  86585. v->pTokenizer->pModule->xDestroy(v->pTokenizer);
  86586. v->pTokenizer = NULL;
  86587. }
  86588. clearPendingTerms(v);
  86589. sqlite3_free(v->azColumn);
  86590. for(i = 0; i < v->nColumn; ++i) {
  86591. sqlite3_free(v->azContentColumn[i]);
  86592. }
  86593. sqlite3_free(v->azContentColumn);
  86594. sqlite3_free(v);
  86595. }
  86596. /*
  86597. ** Token types for parsing the arguments to xConnect or xCreate.
  86598. */
  86599. #define TOKEN_EOF 0 /* End of file */
  86600. #define TOKEN_SPACE 1 /* Any kind of whitespace */
  86601. #define TOKEN_ID 2 /* An identifier */
  86602. #define TOKEN_STRING 3 /* A string literal */
  86603. #define TOKEN_PUNCT 4 /* A single punctuation character */
  86604. /*
  86605. ** If X is a character that can be used in an identifier then
  86606. ** ftsIdChar(X) will be true. Otherwise it is false.
  86607. **
  86608. ** For ASCII, any character with the high-order bit set is
  86609. ** allowed in an identifier. For 7-bit characters,
  86610. ** isFtsIdChar[X] must be 1.
  86611. **
  86612. ** Ticket #1066. the SQL standard does not allow '$' in the
  86613. ** middle of identfiers. But many SQL implementations do.
  86614. ** SQLite will allow '$' in identifiers for compatibility.
  86615. ** But the feature is undocumented.
  86616. */
  86617. static const char isFtsIdChar[] = {
  86618. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  86619. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  86620. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  86621. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  86622. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  86623. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  86624. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  86625. };
  86626. #define ftsIdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
  86627. /*
  86628. ** Return the length of the token that begins at z[0].
  86629. ** Store the token type in *tokenType before returning.
  86630. */
  86631. static int ftsGetToken(const char *z, int *tokenType){
  86632. int i, c;
  86633. switch( *z ){
  86634. case 0: {
  86635. *tokenType = TOKEN_EOF;
  86636. return 0;
  86637. }
  86638. case ' ': case '\t': case '\n': case '\f': case '\r': {
  86639. for(i=1; safe_isspace(z[i]); i++){}
  86640. *tokenType = TOKEN_SPACE;
  86641. return i;
  86642. }
  86643. case '`':
  86644. case '\'':
  86645. case '"': {
  86646. int delim = z[0];
  86647. for(i=1; (c=z[i])!=0; i++){
  86648. if( c==delim ){
  86649. if( z[i+1]==delim ){
  86650. i++;
  86651. }else{
  86652. break;
  86653. }
  86654. }
  86655. }
  86656. *tokenType = TOKEN_STRING;
  86657. return i + (c!=0);
  86658. }
  86659. case '[': {
  86660. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  86661. *tokenType = TOKEN_ID;
  86662. return i;
  86663. }
  86664. default: {
  86665. if( !ftsIdChar(*z) ){
  86666. break;
  86667. }
  86668. for(i=1; ftsIdChar(z[i]); i++){}
  86669. *tokenType = TOKEN_ID;
  86670. return i;
  86671. }
  86672. }
  86673. *tokenType = TOKEN_PUNCT;
  86674. return 1;
  86675. }
  86676. /*
  86677. ** A token extracted from a string is an instance of the following
  86678. ** structure.
  86679. */
  86680. typedef struct FtsToken {
  86681. const char *z; /* Pointer to token text. Not '\000' terminated */
  86682. short int n; /* Length of the token text in bytes. */
  86683. } FtsToken;
  86684. /*
  86685. ** Given a input string (which is really one of the argv[] parameters
  86686. ** passed into xConnect or xCreate) split the string up into tokens.
  86687. ** Return an array of pointers to '\000' terminated strings, one string
  86688. ** for each non-whitespace token.
  86689. **
  86690. ** The returned array is terminated by a single NULL pointer.
  86691. **
  86692. ** Space to hold the returned array is obtained from a single
  86693. ** malloc and should be freed by passing the return value to free().
  86694. ** The individual strings within the token list are all a part of
  86695. ** the single memory allocation and will all be freed at once.
  86696. */
  86697. static char **tokenizeString(const char *z, int *pnToken){
  86698. int nToken = 0;
  86699. FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
  86700. int n = 1;
  86701. int e, i;
  86702. int totalSize = 0;
  86703. char **azToken;
  86704. char *zCopy;
  86705. while( n>0 ){
  86706. n = ftsGetToken(z, &e);
  86707. if( e!=TOKEN_SPACE ){
  86708. aToken[nToken].z = z;
  86709. aToken[nToken].n = n;
  86710. nToken++;
  86711. totalSize += n+1;
  86712. }
  86713. z += n;
  86714. }
  86715. azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
  86716. zCopy = (char*)&azToken[nToken];
  86717. nToken--;
  86718. for(i=0; i<nToken; i++){
  86719. azToken[i] = zCopy;
  86720. n = aToken[i].n;
  86721. memcpy(zCopy, aToken[i].z, n);
  86722. zCopy[n] = 0;
  86723. zCopy += n+1;
  86724. }
  86725. azToken[nToken] = 0;
  86726. sqlite3_free(aToken);
  86727. *pnToken = nToken;
  86728. return azToken;
  86729. }
  86730. /*
  86731. ** Convert an SQL-style quoted string into a normal string by removing
  86732. ** the quote characters. The conversion is done in-place. If the
  86733. ** input does not begin with a quote character, then this routine
  86734. ** is a no-op.
  86735. **
  86736. ** Examples:
  86737. **
  86738. ** "abc" becomes abc
  86739. ** 'xyz' becomes xyz
  86740. ** [pqr] becomes pqr
  86741. ** `mno` becomes mno
  86742. */
  86743. static void dequoteString(char *z){
  86744. int quote;
  86745. int i, j;
  86746. if( z==0 ) return;
  86747. quote = z[0];
  86748. switch( quote ){
  86749. case '\'': break;
  86750. case '"': break;
  86751. case '`': break; /* For MySQL compatibility */
  86752. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  86753. default: return;
  86754. }
  86755. for(i=1, j=0; z[i]; i++){
  86756. if( z[i]==quote ){
  86757. if( z[i+1]==quote ){
  86758. z[j++] = quote;
  86759. i++;
  86760. }else{
  86761. z[j++] = 0;
  86762. break;
  86763. }
  86764. }else{
  86765. z[j++] = z[i];
  86766. }
  86767. }
  86768. }
  86769. /*
  86770. ** The input azIn is a NULL-terminated list of tokens. Remove the first
  86771. ** token and all punctuation tokens. Remove the quotes from
  86772. ** around string literal tokens.
  86773. **
  86774. ** Example:
  86775. **
  86776. ** input: tokenize chinese ( 'simplifed' , 'mixed' )
  86777. ** output: chinese simplifed mixed
  86778. **
  86779. ** Another example:
  86780. **
  86781. ** input: delimiters ( '[' , ']' , '...' )
  86782. ** output: [ ] ...
  86783. */
  86784. static void tokenListToIdList(char **azIn){
  86785. int i, j;
  86786. if( azIn ){
  86787. for(i=0, j=-1; azIn[i]; i++){
  86788. if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
  86789. dequoteString(azIn[i]);
  86790. if( j>=0 ){
  86791. azIn[j] = azIn[i];
  86792. }
  86793. j++;
  86794. }
  86795. }
  86796. azIn[j] = 0;
  86797. }
  86798. }
  86799. /*
  86800. ** Find the first alphanumeric token in the string zIn. Null-terminate
  86801. ** this token. Remove any quotation marks. And return a pointer to
  86802. ** the result.
  86803. */
  86804. static char *firstToken(char *zIn, char **pzTail){
  86805. int n, ttype;
  86806. while(1){
  86807. n = ftsGetToken(zIn, &ttype);
  86808. if( ttype==TOKEN_SPACE ){
  86809. zIn += n;
  86810. }else if( ttype==TOKEN_EOF ){
  86811. *pzTail = zIn;
  86812. return 0;
  86813. }else{
  86814. zIn[n] = 0;
  86815. *pzTail = &zIn[1];
  86816. dequoteString(zIn);
  86817. return zIn;
  86818. }
  86819. }
  86820. /*NOTREACHED*/
  86821. }
  86822. /* Return true if...
  86823. **
  86824. ** * s begins with the string t, ignoring case
  86825. ** * s is longer than t
  86826. ** * The first character of s beyond t is not a alphanumeric
  86827. **
  86828. ** Ignore leading space in *s.
  86829. **
  86830. ** To put it another way, return true if the first token of
  86831. ** s[] is t[].
  86832. */
  86833. static int startsWith(const char *s, const char *t){
  86834. while( safe_isspace(*s) ){ s++; }
  86835. while( *t ){
  86836. if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
  86837. }
  86838. return *s!='_' && !safe_isalnum(*s);
  86839. }
  86840. /*
  86841. ** An instance of this structure defines the "spec" of a
  86842. ** full text index. This structure is populated by parseSpec
  86843. ** and use by fulltextConnect and fulltextCreate.
  86844. */
  86845. typedef struct TableSpec {
  86846. const char *zDb; /* Logical database name */
  86847. const char *zName; /* Name of the full-text index */
  86848. int nColumn; /* Number of columns to be indexed */
  86849. char **azColumn; /* Original names of columns to be indexed */
  86850. char **azContentColumn; /* Column names for %_content */
  86851. char **azTokenizer; /* Name of tokenizer and its arguments */
  86852. } TableSpec;
  86853. /*
  86854. ** Reclaim all of the memory used by a TableSpec
  86855. */
  86856. static void clearTableSpec(TableSpec *p) {
  86857. sqlite3_free(p->azColumn);
  86858. sqlite3_free(p->azContentColumn);
  86859. sqlite3_free(p->azTokenizer);
  86860. }
  86861. /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
  86862. *
  86863. * CREATE VIRTUAL TABLE email
  86864. * USING fts3(subject, body, tokenize mytokenizer(myarg))
  86865. *
  86866. * We return parsed information in a TableSpec structure.
  86867. *
  86868. */
  86869. static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
  86870. char**pzErr){
  86871. int i, n;
  86872. char *z, *zDummy;
  86873. char **azArg;
  86874. const char *zTokenizer = 0; /* argv[] entry describing the tokenizer */
  86875. assert( argc>=3 );
  86876. /* Current interface:
  86877. ** argv[0] - module name
  86878. ** argv[1] - database name
  86879. ** argv[2] - table name
  86880. ** argv[3..] - columns, optionally followed by tokenizer specification
  86881. ** and snippet delimiters specification.
  86882. */
  86883. /* Make a copy of the complete argv[][] array in a single allocation.
  86884. ** The argv[][] array is read-only and transient. We can write to the
  86885. ** copy in order to modify things and the copy is persistent.
  86886. */
  86887. CLEAR(pSpec);
  86888. for(i=n=0; i<argc; i++){
  86889. n += strlen(argv[i]) + 1;
  86890. }
  86891. azArg = sqlite3_malloc( sizeof(char*)*argc + n );
  86892. if( azArg==0 ){
  86893. return SQLITE_NOMEM;
  86894. }
  86895. z = (char*)&azArg[argc];
  86896. for(i=0; i<argc; i++){
  86897. azArg[i] = z;
  86898. strcpy(z, argv[i]);
  86899. z += strlen(z)+1;
  86900. }
  86901. /* Identify the column names and the tokenizer and delimiter arguments
  86902. ** in the argv[][] array.
  86903. */
  86904. pSpec->zDb = azArg[1];
  86905. pSpec->zName = azArg[2];
  86906. pSpec->nColumn = 0;
  86907. pSpec->azColumn = azArg;
  86908. zTokenizer = "tokenize simple";
  86909. for(i=3; i<argc; ++i){
  86910. if( startsWith(azArg[i],"tokenize") ){
  86911. zTokenizer = azArg[i];
  86912. }else{
  86913. z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
  86914. pSpec->nColumn++;
  86915. }
  86916. }
  86917. if( pSpec->nColumn==0 ){
  86918. azArg[0] = "content";
  86919. pSpec->nColumn = 1;
  86920. }
  86921. /*
  86922. ** Construct the list of content column names.
  86923. **
  86924. ** Each content column name will be of the form cNNAAAA
  86925. ** where NN is the column number and AAAA is the sanitized
  86926. ** column name. "sanitized" means that special characters are
  86927. ** converted to "_". The cNN prefix guarantees that all column
  86928. ** names are unique.
  86929. **
  86930. ** The AAAA suffix is not strictly necessary. It is included
  86931. ** for the convenience of people who might examine the generated
  86932. ** %_content table and wonder what the columns are used for.
  86933. */
  86934. pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
  86935. if( pSpec->azContentColumn==0 ){
  86936. clearTableSpec(pSpec);
  86937. return SQLITE_NOMEM;
  86938. }
  86939. for(i=0; i<pSpec->nColumn; i++){
  86940. char *p;
  86941. pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
  86942. for (p = pSpec->azContentColumn[i]; *p ; ++p) {
  86943. if( !safe_isalnum(*p) ) *p = '_';
  86944. }
  86945. }
  86946. /*
  86947. ** Parse the tokenizer specification string.
  86948. */
  86949. pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
  86950. tokenListToIdList(pSpec->azTokenizer);
  86951. return SQLITE_OK;
  86952. }
  86953. /*
  86954. ** Generate a CREATE TABLE statement that describes the schema of
  86955. ** the virtual table. Return a pointer to this schema string.
  86956. **
  86957. ** Space is obtained from sqlite3_mprintf() and should be freed
  86958. ** using sqlite3_free().
  86959. */
  86960. static char *fulltextSchema(
  86961. int nColumn, /* Number of columns */
  86962. const char *const* azColumn, /* List of columns */
  86963. const char *zTableName /* Name of the table */
  86964. ){
  86965. int i;
  86966. char *zSchema, *zNext;
  86967. const char *zSep = "(";
  86968. zSchema = sqlite3_mprintf("CREATE TABLE x");
  86969. for(i=0; i<nColumn; i++){
  86970. zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
  86971. sqlite3_free(zSchema);
  86972. zSchema = zNext;
  86973. zSep = ",";
  86974. }
  86975. zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
  86976. sqlite3_free(zSchema);
  86977. zSchema = zNext;
  86978. zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
  86979. sqlite3_free(zSchema);
  86980. return zNext;
  86981. }
  86982. /*
  86983. ** Build a new sqlite3_vtab structure that will describe the
  86984. ** fulltext index defined by spec.
  86985. */
  86986. static int constructVtab(
  86987. sqlite3 *db, /* The SQLite database connection */
  86988. fts3Hash *pHash, /* Hash table containing tokenizers */
  86989. TableSpec *spec, /* Parsed spec information from parseSpec() */
  86990. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  86991. char **pzErr /* Write any error message here */
  86992. ){
  86993. int rc;
  86994. int n;
  86995. fulltext_vtab *v = 0;
  86996. const sqlite3_tokenizer_module *m = NULL;
  86997. char *schema;
  86998. char const *zTok; /* Name of tokenizer to use for this fts table */
  86999. int nTok; /* Length of zTok, including nul terminator */
  87000. v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
  87001. if( v==0 ) return SQLITE_NOMEM;
  87002. CLEAR(v);
  87003. /* sqlite will initialize v->base */
  87004. v->db = db;
  87005. v->zDb = spec->zDb; /* Freed when azColumn is freed */
  87006. v->zName = spec->zName; /* Freed when azColumn is freed */
  87007. v->nColumn = spec->nColumn;
  87008. v->azContentColumn = spec->azContentColumn;
  87009. spec->azContentColumn = 0;
  87010. v->azColumn = spec->azColumn;
  87011. spec->azColumn = 0;
  87012. if( spec->azTokenizer==0 ){
  87013. return SQLITE_NOMEM;
  87014. }
  87015. zTok = spec->azTokenizer[0];
  87016. if( !zTok ){
  87017. zTok = "simple";
  87018. }
  87019. nTok = strlen(zTok)+1;
  87020. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
  87021. if( !m ){
  87022. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
  87023. rc = SQLITE_ERROR;
  87024. goto err;
  87025. }
  87026. for(n=0; spec->azTokenizer[n]; n++){}
  87027. if( n ){
  87028. rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
  87029. &v->pTokenizer);
  87030. }else{
  87031. rc = m->xCreate(0, 0, &v->pTokenizer);
  87032. }
  87033. if( rc!=SQLITE_OK ) goto err;
  87034. v->pTokenizer->pModule = m;
  87035. /* TODO: verify the existence of backing tables foo_content, foo_term */
  87036. schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
  87037. spec->zName);
  87038. rc = sqlite3_declare_vtab(db, schema);
  87039. sqlite3_free(schema);
  87040. if( rc!=SQLITE_OK ) goto err;
  87041. memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
  87042. /* Indicate that the buffer is not live. */
  87043. v->nPendingData = -1;
  87044. *ppVTab = &v->base;
  87045. FTSTRACE(("FTS3 Connect %p\n", v));
  87046. return rc;
  87047. err:
  87048. fulltext_vtab_destroy(v);
  87049. return rc;
  87050. }
  87051. static int fulltextConnect(
  87052. sqlite3 *db,
  87053. void *pAux,
  87054. int argc, const char *const*argv,
  87055. sqlite3_vtab **ppVTab,
  87056. char **pzErr
  87057. ){
  87058. TableSpec spec;
  87059. int rc = parseSpec(&spec, argc, argv, pzErr);
  87060. if( rc!=SQLITE_OK ) return rc;
  87061. rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
  87062. clearTableSpec(&spec);
  87063. return rc;
  87064. }
  87065. /* The %_content table holds the text of each document, with
  87066. ** the docid column exposed as the SQLite rowid for the table.
  87067. */
  87068. /* TODO(shess) This comment needs elaboration to match the updated
  87069. ** code. Work it into the top-of-file comment at that time.
  87070. */
  87071. static int fulltextCreate(sqlite3 *db, void *pAux,
  87072. int argc, const char * const *argv,
  87073. sqlite3_vtab **ppVTab, char **pzErr){
  87074. int rc;
  87075. TableSpec spec;
  87076. StringBuffer schema;
  87077. FTSTRACE(("FTS3 Create\n"));
  87078. rc = parseSpec(&spec, argc, argv, pzErr);
  87079. if( rc!=SQLITE_OK ) return rc;
  87080. initStringBuffer(&schema);
  87081. append(&schema, "CREATE TABLE %_content(");
  87082. append(&schema, " docid INTEGER PRIMARY KEY,");
  87083. appendList(&schema, spec.nColumn, spec.azContentColumn);
  87084. append(&schema, ")");
  87085. rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
  87086. stringBufferDestroy(&schema);
  87087. if( rc!=SQLITE_OK ) goto out;
  87088. rc = sql_exec(db, spec.zDb, spec.zName,
  87089. "create table %_segments("
  87090. " blockid INTEGER PRIMARY KEY,"
  87091. " block blob"
  87092. ");"
  87093. );
  87094. if( rc!=SQLITE_OK ) goto out;
  87095. rc = sql_exec(db, spec.zDb, spec.zName,
  87096. "create table %_segdir("
  87097. " level integer,"
  87098. " idx integer,"
  87099. " start_block integer,"
  87100. " leaves_end_block integer,"
  87101. " end_block integer,"
  87102. " root blob,"
  87103. " primary key(level, idx)"
  87104. ");");
  87105. if( rc!=SQLITE_OK ) goto out;
  87106. rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
  87107. out:
  87108. clearTableSpec(&spec);
  87109. return rc;
  87110. }
  87111. /* Decide how to handle an SQL query. */
  87112. static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  87113. fulltext_vtab *v = (fulltext_vtab *)pVTab;
  87114. int i;
  87115. FTSTRACE(("FTS3 BestIndex\n"));
  87116. for(i=0; i<pInfo->nConstraint; ++i){
  87117. const struct sqlite3_index_constraint *pConstraint;
  87118. pConstraint = &pInfo->aConstraint[i];
  87119. if( pConstraint->usable ) {
  87120. if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
  87121. pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  87122. pInfo->idxNum = QUERY_DOCID; /* lookup by docid */
  87123. FTSTRACE(("FTS3 QUERY_DOCID\n"));
  87124. } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
  87125. pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  87126. /* full-text search */
  87127. pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
  87128. FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
  87129. } else continue;
  87130. pInfo->aConstraintUsage[i].argvIndex = 1;
  87131. pInfo->aConstraintUsage[i].omit = 1;
  87132. /* An arbitrary value for now.
  87133. * TODO: Perhaps docid matches should be considered cheaper than
  87134. * full-text searches. */
  87135. pInfo->estimatedCost = 1.0;
  87136. return SQLITE_OK;
  87137. }
  87138. }
  87139. pInfo->idxNum = QUERY_GENERIC;
  87140. return SQLITE_OK;
  87141. }
  87142. static int fulltextDisconnect(sqlite3_vtab *pVTab){
  87143. FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
  87144. fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  87145. return SQLITE_OK;
  87146. }
  87147. static int fulltextDestroy(sqlite3_vtab *pVTab){
  87148. fulltext_vtab *v = (fulltext_vtab *)pVTab;
  87149. int rc;
  87150. FTSTRACE(("FTS3 Destroy %p\n", pVTab));
  87151. rc = sql_exec(v->db, v->zDb, v->zName,
  87152. "drop table if exists %_content;"
  87153. "drop table if exists %_segments;"
  87154. "drop table if exists %_segdir;"
  87155. );
  87156. if( rc!=SQLITE_OK ) return rc;
  87157. fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  87158. return SQLITE_OK;
  87159. }
  87160. static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  87161. fulltext_cursor *c;
  87162. c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
  87163. if( c ){
  87164. memset(c, 0, sizeof(fulltext_cursor));
  87165. /* sqlite will initialize c->base */
  87166. *ppCursor = &c->base;
  87167. FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
  87168. return SQLITE_OK;
  87169. }else{
  87170. return SQLITE_NOMEM;
  87171. }
  87172. }
  87173. /* Free all of the dynamically allocated memory held by the
  87174. ** Snippet
  87175. */
  87176. static void snippetClear(Snippet *p){
  87177. sqlite3_free(p->aMatch);
  87178. sqlite3_free(p->zOffset);
  87179. sqlite3_free(p->zSnippet);
  87180. CLEAR(p);
  87181. }
  87182. /*
  87183. ** Append a single entry to the p->aMatch[] log.
  87184. */
  87185. static void snippetAppendMatch(
  87186. Snippet *p, /* Append the entry to this snippet */
  87187. int iCol, int iTerm, /* The column and query term */
  87188. int iToken, /* Matching token in document */
  87189. int iStart, int nByte /* Offset and size of the match */
  87190. ){
  87191. int i;
  87192. struct snippetMatch *pMatch;
  87193. if( p->nMatch+1>=p->nAlloc ){
  87194. p->nAlloc = p->nAlloc*2 + 10;
  87195. p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
  87196. if( p->aMatch==0 ){
  87197. p->nMatch = 0;
  87198. p->nAlloc = 0;
  87199. return;
  87200. }
  87201. }
  87202. i = p->nMatch++;
  87203. pMatch = &p->aMatch[i];
  87204. pMatch->iCol = iCol;
  87205. pMatch->iTerm = iTerm;
  87206. pMatch->iToken = iToken;
  87207. pMatch->iStart = iStart;
  87208. pMatch->nByte = nByte;
  87209. }
  87210. /*
  87211. ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
  87212. */
  87213. #define FTS3_ROTOR_SZ (32)
  87214. #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
  87215. /*
  87216. ** Function to iterate through the tokens of a compiled expression.
  87217. **
  87218. ** Except, skip all tokens on the right-hand side of a NOT operator.
  87219. ** This function is used to find tokens as part of snippet and offset
  87220. ** generation and we do nt want snippets and offsets to report matches
  87221. ** for tokens on the RHS of a NOT.
  87222. */
  87223. static int fts3NextExprToken(Fts3Expr **ppExpr, int *piToken){
  87224. Fts3Expr *p = *ppExpr;
  87225. int iToken = *piToken;
  87226. if( iToken<0 ){
  87227. /* In this case the expression p is the root of an expression tree.
  87228. ** Move to the first token in the expression tree.
  87229. */
  87230. while( p->pLeft ){
  87231. p = p->pLeft;
  87232. }
  87233. iToken = 0;
  87234. }else{
  87235. assert(p && p->eType==FTSQUERY_PHRASE );
  87236. if( iToken<(p->pPhrase->nToken-1) ){
  87237. iToken++;
  87238. }else{
  87239. iToken = 0;
  87240. while( p->pParent && p->pParent->pLeft!=p ){
  87241. assert( p->pParent->pRight==p );
  87242. p = p->pParent;
  87243. }
  87244. p = p->pParent;
  87245. if( p ){
  87246. assert( p->pRight!=0 );
  87247. p = p->pRight;
  87248. while( p->pLeft ){
  87249. p = p->pLeft;
  87250. }
  87251. }
  87252. }
  87253. }
  87254. *ppExpr = p;
  87255. *piToken = iToken;
  87256. return p?1:0;
  87257. }
  87258. /*
  87259. ** Return TRUE if the expression node pExpr is located beneath the
  87260. ** RHS of a NOT operator.
  87261. */
  87262. static int fts3ExprBeneathNot(Fts3Expr *p){
  87263. Fts3Expr *pParent;
  87264. while( p ){
  87265. pParent = p->pParent;
  87266. if( pParent && pParent->eType==FTSQUERY_NOT && pParent->pRight==p ){
  87267. return 1;
  87268. }
  87269. p = pParent;
  87270. }
  87271. return 0;
  87272. }
  87273. /*
  87274. ** Add entries to pSnippet->aMatch[] for every match that occurs against
  87275. ** document zDoc[0..nDoc-1] which is stored in column iColumn.
  87276. */
  87277. static void snippetOffsetsOfColumn(
  87278. fulltext_cursor *pCur, /* The fulltest search cursor */
  87279. Snippet *pSnippet, /* The Snippet object to be filled in */
  87280. int iColumn, /* Index of fulltext table column */
  87281. const char *zDoc, /* Text of the fulltext table column */
  87282. int nDoc /* Length of zDoc in bytes */
  87283. ){
  87284. const sqlite3_tokenizer_module *pTModule; /* The tokenizer module */
  87285. sqlite3_tokenizer *pTokenizer; /* The specific tokenizer */
  87286. sqlite3_tokenizer_cursor *pTCursor; /* Tokenizer cursor */
  87287. fulltext_vtab *pVtab; /* The full text index */
  87288. int nColumn; /* Number of columns in the index */
  87289. int i, j; /* Loop counters */
  87290. int rc; /* Return code */
  87291. unsigned int match, prevMatch; /* Phrase search bitmasks */
  87292. const char *zToken; /* Next token from the tokenizer */
  87293. int nToken; /* Size of zToken */
  87294. int iBegin, iEnd, iPos; /* Offsets of beginning and end */
  87295. /* The following variables keep a circular buffer of the last
  87296. ** few tokens */
  87297. unsigned int iRotor = 0; /* Index of current token */
  87298. int iRotorBegin[FTS3_ROTOR_SZ]; /* Beginning offset of token */
  87299. int iRotorLen[FTS3_ROTOR_SZ]; /* Length of token */
  87300. pVtab = cursor_vtab(pCur);
  87301. nColumn = pVtab->nColumn;
  87302. pTokenizer = pVtab->pTokenizer;
  87303. pTModule = pTokenizer->pModule;
  87304. rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
  87305. if( rc ) return;
  87306. pTCursor->pTokenizer = pTokenizer;
  87307. prevMatch = 0;
  87308. while( !pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos) ){
  87309. Fts3Expr *pIter = pCur->pExpr;
  87310. int iIter = -1;
  87311. iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
  87312. iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
  87313. match = 0;
  87314. for(i=0; i<(FTS3_ROTOR_SZ-1) && fts3NextExprToken(&pIter, &iIter); i++){
  87315. int nPhrase; /* Number of tokens in current phrase */
  87316. struct PhraseToken *pToken; /* Current token */
  87317. int iCol; /* Column index */
  87318. if( fts3ExprBeneathNot(pIter) ) continue;
  87319. nPhrase = pIter->pPhrase->nToken;
  87320. pToken = &pIter->pPhrase->aToken[iIter];
  87321. iCol = pIter->pPhrase->iColumn;
  87322. if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
  87323. if( pToken->n>nToken ) continue;
  87324. if( !pToken->isPrefix && pToken->n<nToken ) continue;
  87325. assert( pToken->n<=nToken );
  87326. if( memcmp(pToken->z, zToken, pToken->n) ) continue;
  87327. if( iIter>0 && (prevMatch & (1<<i))==0 ) continue;
  87328. match |= 1<<i;
  87329. if( i==(FTS3_ROTOR_SZ-2) || nPhrase==iIter+1 ){
  87330. for(j=nPhrase-1; j>=0; j--){
  87331. int k = (iRotor-j) & FTS3_ROTOR_MASK;
  87332. snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
  87333. iRotorBegin[k], iRotorLen[k]);
  87334. }
  87335. }
  87336. }
  87337. prevMatch = match<<1;
  87338. iRotor++;
  87339. }
  87340. pTModule->xClose(pTCursor);
  87341. }
  87342. /*
  87343. ** Remove entries from the pSnippet structure to account for the NEAR
  87344. ** operator. When this is called, pSnippet contains the list of token
  87345. ** offsets produced by treating all NEAR operators as AND operators.
  87346. ** This function removes any entries that should not be present after
  87347. ** accounting for the NEAR restriction. For example, if the queried
  87348. ** document is:
  87349. **
  87350. ** "A B C D E A"
  87351. **
  87352. ** and the query is:
  87353. **
  87354. ** A NEAR/0 E
  87355. **
  87356. ** then when this function is called the Snippet contains token offsets
  87357. ** 0, 4 and 5. This function removes the "0" entry (because the first A
  87358. ** is not near enough to an E).
  87359. **
  87360. ** When this function is called, the value pointed to by parameter piLeft is
  87361. ** the integer id of the left-most token in the expression tree headed by
  87362. ** pExpr. This function increments *piLeft by the total number of tokens
  87363. ** in the expression tree headed by pExpr.
  87364. **
  87365. ** Return 1 if any trimming occurs. Return 0 if no trimming is required.
  87366. */
  87367. static int trimSnippetOffsets(
  87368. Fts3Expr *pExpr, /* The search expression */
  87369. Snippet *pSnippet, /* The set of snippet offsets to be trimmed */
  87370. int *piLeft /* Index of left-most token in pExpr */
  87371. ){
  87372. if( pExpr ){
  87373. if( trimSnippetOffsets(pExpr->pLeft, pSnippet, piLeft) ){
  87374. return 1;
  87375. }
  87376. switch( pExpr->eType ){
  87377. case FTSQUERY_PHRASE:
  87378. *piLeft += pExpr->pPhrase->nToken;
  87379. break;
  87380. case FTSQUERY_NEAR: {
  87381. /* The right-hand-side of a NEAR operator is always a phrase. The
  87382. ** left-hand-side is either a phrase or an expression tree that is
  87383. ** itself headed by a NEAR operator. The following initializations
  87384. ** set local variable iLeft to the token number of the left-most
  87385. ** token in the right-hand phrase, and iRight to the right most
  87386. ** token in the same phrase. For example, if we had:
  87387. **
  87388. ** <col> MATCH '"abc def" NEAR/2 "ghi jkl"'
  87389. **
  87390. ** then iLeft will be set to 2 (token number of ghi) and nToken will
  87391. ** be set to 4.
  87392. */
  87393. Fts3Expr *pLeft = pExpr->pLeft;
  87394. Fts3Expr *pRight = pExpr->pRight;
  87395. int iLeft = *piLeft;
  87396. int nNear = pExpr->nNear;
  87397. int nToken = pRight->pPhrase->nToken;
  87398. int jj, ii;
  87399. if( pLeft->eType==FTSQUERY_NEAR ){
  87400. pLeft = pLeft->pRight;
  87401. }
  87402. assert( pRight->eType==FTSQUERY_PHRASE );
  87403. assert( pLeft->eType==FTSQUERY_PHRASE );
  87404. nToken += pLeft->pPhrase->nToken;
  87405. for(ii=0; ii<pSnippet->nMatch; ii++){
  87406. struct snippetMatch *p = &pSnippet->aMatch[ii];
  87407. if( p->iTerm==iLeft ){
  87408. int isOk = 0;
  87409. /* Snippet ii is an occurence of query term iLeft in the document.
  87410. ** It occurs at position (p->iToken) of the document. We now
  87411. ** search for an instance of token (iLeft-1) somewhere in the
  87412. ** range (p->iToken - nNear)...(p->iToken + nNear + nToken) within
  87413. ** the set of snippetMatch structures. If one is found, proceed.
  87414. ** If one cannot be found, then remove snippets ii..(ii+N-1)
  87415. ** from the matching snippets, where N is the number of tokens
  87416. ** in phrase pRight->pPhrase.
  87417. */
  87418. for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
  87419. struct snippetMatch *p2 = &pSnippet->aMatch[jj];
  87420. if( p2->iTerm==(iLeft-1) ){
  87421. if( p2->iToken>=(p->iToken-nNear-1)
  87422. && p2->iToken<(p->iToken+nNear+nToken)
  87423. ){
  87424. isOk = 1;
  87425. }
  87426. }
  87427. }
  87428. if( !isOk ){
  87429. int kk;
  87430. for(kk=0; kk<pRight->pPhrase->nToken; kk++){
  87431. pSnippet->aMatch[kk+ii].iTerm = -2;
  87432. }
  87433. return 1;
  87434. }
  87435. }
  87436. if( p->iTerm==(iLeft-1) ){
  87437. int isOk = 0;
  87438. for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
  87439. struct snippetMatch *p2 = &pSnippet->aMatch[jj];
  87440. if( p2->iTerm==iLeft ){
  87441. if( p2->iToken<=(p->iToken+nNear+1)
  87442. && p2->iToken>(p->iToken-nNear-nToken)
  87443. ){
  87444. isOk = 1;
  87445. }
  87446. }
  87447. }
  87448. if( !isOk ){
  87449. int kk;
  87450. for(kk=0; kk<pLeft->pPhrase->nToken; kk++){
  87451. pSnippet->aMatch[ii-kk].iTerm = -2;
  87452. }
  87453. return 1;
  87454. }
  87455. }
  87456. }
  87457. break;
  87458. }
  87459. }
  87460. if( trimSnippetOffsets(pExpr->pRight, pSnippet, piLeft) ){
  87461. return 1;
  87462. }
  87463. }
  87464. return 0;
  87465. }
  87466. /*
  87467. ** Compute all offsets for the current row of the query.
  87468. ** If the offsets have already been computed, this routine is a no-op.
  87469. */
  87470. static void snippetAllOffsets(fulltext_cursor *p){
  87471. int nColumn;
  87472. int iColumn, i;
  87473. int iFirst, iLast;
  87474. int iTerm = 0;
  87475. fulltext_vtab *pFts = cursor_vtab(p);
  87476. if( p->snippet.nMatch || p->pExpr==0 ){
  87477. return;
  87478. }
  87479. nColumn = pFts->nColumn;
  87480. iColumn = (p->iCursorType - QUERY_FULLTEXT);
  87481. if( iColumn<0 || iColumn>=nColumn ){
  87482. /* Look for matches over all columns of the full-text index */
  87483. iFirst = 0;
  87484. iLast = nColumn-1;
  87485. }else{
  87486. /* Look for matches in the iColumn-th column of the index only */
  87487. iFirst = iColumn;
  87488. iLast = iColumn;
  87489. }
  87490. for(i=iFirst; i<=iLast; i++){
  87491. const char *zDoc;
  87492. int nDoc;
  87493. zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
  87494. nDoc = sqlite3_column_bytes(p->pStmt, i+1);
  87495. snippetOffsetsOfColumn(p, &p->snippet, i, zDoc, nDoc);
  87496. }
  87497. while( trimSnippetOffsets(p->pExpr, &p->snippet, &iTerm) ){
  87498. iTerm = 0;
  87499. }
  87500. }
  87501. /*
  87502. ** Convert the information in the aMatch[] array of the snippet
  87503. ** into the string zOffset[0..nOffset-1]. This string is used as
  87504. ** the return of the SQL offsets() function.
  87505. */
  87506. static void snippetOffsetText(Snippet *p){
  87507. int i;
  87508. int cnt = 0;
  87509. StringBuffer sb;
  87510. char zBuf[200];
  87511. if( p->zOffset ) return;
  87512. initStringBuffer(&sb);
  87513. for(i=0; i<p->nMatch; i++){
  87514. struct snippetMatch *pMatch = &p->aMatch[i];
  87515. if( pMatch->iTerm>=0 ){
  87516. /* If snippetMatch.iTerm is less than 0, then the match was
  87517. ** discarded as part of processing the NEAR operator (see the
  87518. ** trimSnippetOffsetsForNear() function for details). Ignore
  87519. ** it in this case
  87520. */
  87521. zBuf[0] = ' ';
  87522. sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
  87523. pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
  87524. append(&sb, zBuf);
  87525. cnt++;
  87526. }
  87527. }
  87528. p->zOffset = stringBufferData(&sb);
  87529. p->nOffset = stringBufferLength(&sb);
  87530. }
  87531. /*
  87532. ** zDoc[0..nDoc-1] is phrase of text. aMatch[0..nMatch-1] are a set
  87533. ** of matching words some of which might be in zDoc. zDoc is column
  87534. ** number iCol.
  87535. **
  87536. ** iBreak is suggested spot in zDoc where we could begin or end an
  87537. ** excerpt. Return a value similar to iBreak but possibly adjusted
  87538. ** to be a little left or right so that the break point is better.
  87539. */
  87540. static int wordBoundary(
  87541. int iBreak, /* The suggested break point */
  87542. const char *zDoc, /* Document text */
  87543. int nDoc, /* Number of bytes in zDoc[] */
  87544. struct snippetMatch *aMatch, /* Matching words */
  87545. int nMatch, /* Number of entries in aMatch[] */
  87546. int iCol /* The column number for zDoc[] */
  87547. ){
  87548. int i;
  87549. if( iBreak<=10 ){
  87550. return 0;
  87551. }
  87552. if( iBreak>=nDoc-10 ){
  87553. return nDoc;
  87554. }
  87555. for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
  87556. while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
  87557. if( i<nMatch ){
  87558. if( aMatch[i].iStart<iBreak+10 ){
  87559. return aMatch[i].iStart;
  87560. }
  87561. if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
  87562. return aMatch[i-1].iStart;
  87563. }
  87564. }
  87565. for(i=1; i<=10; i++){
  87566. if( safe_isspace(zDoc[iBreak-i]) ){
  87567. return iBreak - i + 1;
  87568. }
  87569. if( safe_isspace(zDoc[iBreak+i]) ){
  87570. return iBreak + i + 1;
  87571. }
  87572. }
  87573. return iBreak;
  87574. }
  87575. /*
  87576. ** Allowed values for Snippet.aMatch[].snStatus
  87577. */
  87578. #define SNIPPET_IGNORE 0 /* It is ok to omit this match from the snippet */
  87579. #define SNIPPET_DESIRED 1 /* We want to include this match in the snippet */
  87580. /*
  87581. ** Generate the text of a snippet.
  87582. */
  87583. static void snippetText(
  87584. fulltext_cursor *pCursor, /* The cursor we need the snippet for */
  87585. const char *zStartMark, /* Markup to appear before each match */
  87586. const char *zEndMark, /* Markup to appear after each match */
  87587. const char *zEllipsis /* Ellipsis mark */
  87588. ){
  87589. int i, j;
  87590. struct snippetMatch *aMatch;
  87591. int nMatch;
  87592. int nDesired;
  87593. StringBuffer sb;
  87594. int tailCol;
  87595. int tailOffset;
  87596. int iCol;
  87597. int nDoc;
  87598. const char *zDoc;
  87599. int iStart, iEnd;
  87600. int tailEllipsis = 0;
  87601. int iMatch;
  87602. sqlite3_free(pCursor->snippet.zSnippet);
  87603. pCursor->snippet.zSnippet = 0;
  87604. aMatch = pCursor->snippet.aMatch;
  87605. nMatch = pCursor->snippet.nMatch;
  87606. initStringBuffer(&sb);
  87607. for(i=0; i<nMatch; i++){
  87608. aMatch[i].snStatus = SNIPPET_IGNORE;
  87609. }
  87610. nDesired = 0;
  87611. for(i=0; i<FTS3_ROTOR_SZ; i++){
  87612. for(j=0; j<nMatch; j++){
  87613. if( aMatch[j].iTerm==i ){
  87614. aMatch[j].snStatus = SNIPPET_DESIRED;
  87615. nDesired++;
  87616. break;
  87617. }
  87618. }
  87619. }
  87620. iMatch = 0;
  87621. tailCol = -1;
  87622. tailOffset = 0;
  87623. for(i=0; i<nMatch && nDesired>0; i++){
  87624. if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
  87625. nDesired--;
  87626. iCol = aMatch[i].iCol;
  87627. zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
  87628. nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
  87629. iStart = aMatch[i].iStart - 40;
  87630. iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
  87631. if( iStart<=10 ){
  87632. iStart = 0;
  87633. }
  87634. if( iCol==tailCol && iStart<=tailOffset+20 ){
  87635. iStart = tailOffset;
  87636. }
  87637. if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
  87638. trimWhiteSpace(&sb);
  87639. appendWhiteSpace(&sb);
  87640. append(&sb, zEllipsis);
  87641. appendWhiteSpace(&sb);
  87642. }
  87643. iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
  87644. iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
  87645. if( iEnd>=nDoc-10 ){
  87646. iEnd = nDoc;
  87647. tailEllipsis = 0;
  87648. }else{
  87649. tailEllipsis = 1;
  87650. }
  87651. while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
  87652. while( iStart<iEnd ){
  87653. while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
  87654. && aMatch[iMatch].iCol<=iCol ){
  87655. iMatch++;
  87656. }
  87657. if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
  87658. && aMatch[iMatch].iCol==iCol ){
  87659. nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
  87660. iStart = aMatch[iMatch].iStart;
  87661. append(&sb, zStartMark);
  87662. nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
  87663. append(&sb, zEndMark);
  87664. iStart += aMatch[iMatch].nByte;
  87665. for(j=iMatch+1; j<nMatch; j++){
  87666. if( aMatch[j].iTerm==aMatch[iMatch].iTerm
  87667. && aMatch[j].snStatus==SNIPPET_DESIRED ){
  87668. nDesired--;
  87669. aMatch[j].snStatus = SNIPPET_IGNORE;
  87670. }
  87671. }
  87672. }else{
  87673. nappend(&sb, &zDoc[iStart], iEnd - iStart);
  87674. iStart = iEnd;
  87675. }
  87676. }
  87677. tailCol = iCol;
  87678. tailOffset = iEnd;
  87679. }
  87680. trimWhiteSpace(&sb);
  87681. if( tailEllipsis ){
  87682. appendWhiteSpace(&sb);
  87683. append(&sb, zEllipsis);
  87684. }
  87685. pCursor->snippet.zSnippet = stringBufferData(&sb);
  87686. pCursor->snippet.nSnippet = stringBufferLength(&sb);
  87687. }
  87688. /*
  87689. ** Close the cursor. For additional information see the documentation
  87690. ** on the xClose method of the virtual table interface.
  87691. */
  87692. static int fulltextClose(sqlite3_vtab_cursor *pCursor){
  87693. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  87694. FTSTRACE(("FTS3 Close %p\n", c));
  87695. sqlite3_finalize(c->pStmt);
  87696. sqlite3Fts3ExprFree(c->pExpr);
  87697. snippetClear(&c->snippet);
  87698. if( c->result.nData!=0 ){
  87699. dlrDestroy(&c->reader);
  87700. }
  87701. dataBufferDestroy(&c->result);
  87702. sqlite3_free(c);
  87703. return SQLITE_OK;
  87704. }
  87705. static int fulltextNext(sqlite3_vtab_cursor *pCursor){
  87706. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  87707. int rc;
  87708. FTSTRACE(("FTS3 Next %p\n", pCursor));
  87709. snippetClear(&c->snippet);
  87710. if( c->iCursorType < QUERY_FULLTEXT ){
  87711. /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
  87712. rc = sqlite3_step(c->pStmt);
  87713. switch( rc ){
  87714. case SQLITE_ROW:
  87715. c->eof = 0;
  87716. return SQLITE_OK;
  87717. case SQLITE_DONE:
  87718. c->eof = 1;
  87719. return SQLITE_OK;
  87720. default:
  87721. c->eof = 1;
  87722. return rc;
  87723. }
  87724. } else { /* full-text query */
  87725. rc = sqlite3_reset(c->pStmt);
  87726. if( rc!=SQLITE_OK ) return rc;
  87727. if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
  87728. c->eof = 1;
  87729. return SQLITE_OK;
  87730. }
  87731. rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
  87732. dlrStep(&c->reader);
  87733. if( rc!=SQLITE_OK ) return rc;
  87734. /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
  87735. rc = sqlite3_step(c->pStmt);
  87736. if( rc==SQLITE_ROW ){ /* the case we expect */
  87737. c->eof = 0;
  87738. return SQLITE_OK;
  87739. }
  87740. /* an error occurred; abort */
  87741. return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
  87742. }
  87743. }
  87744. /* TODO(shess) If we pushed LeafReader to the top of the file, or to
  87745. ** another file, term_select() could be pushed above
  87746. ** docListOfTerm().
  87747. */
  87748. static int termSelect(fulltext_vtab *v, int iColumn,
  87749. const char *pTerm, int nTerm, int isPrefix,
  87750. DocListType iType, DataBuffer *out);
  87751. /*
  87752. ** Return a DocList corresponding to the phrase *pPhrase.
  87753. **
  87754. ** The resulting DL_DOCIDS doclist is stored in pResult, which is
  87755. ** overwritten.
  87756. */
  87757. static int docListOfPhrase(
  87758. fulltext_vtab *pTab, /* The full text index */
  87759. Fts3Phrase *pPhrase, /* Phrase to return a doclist corresponding to */
  87760. DocListType eListType, /* Either DL_DOCIDS or DL_POSITIONS */
  87761. DataBuffer *pResult /* Write the result here */
  87762. ){
  87763. int ii;
  87764. int rc = SQLITE_OK;
  87765. int iCol = pPhrase->iColumn;
  87766. DocListType eType = eListType;
  87767. assert( eType==DL_POSITIONS || eType==DL_DOCIDS );
  87768. if( pPhrase->nToken>1 ){
  87769. eType = DL_POSITIONS;
  87770. }
  87771. /* This code should never be called with buffered updates. */
  87772. assert( pTab->nPendingData<0 );
  87773. for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
  87774. DataBuffer tmp;
  87775. struct PhraseToken *p = &pPhrase->aToken[ii];
  87776. rc = termSelect(pTab, iCol, p->z, p->n, p->isPrefix, eType, &tmp);
  87777. if( rc==SQLITE_OK ){
  87778. if( ii==0 ){
  87779. *pResult = tmp;
  87780. }else{
  87781. DataBuffer res = *pResult;
  87782. dataBufferInit(pResult, 0);
  87783. if( ii==(pPhrase->nToken-1) ){
  87784. eType = eListType;
  87785. }
  87786. docListPhraseMerge(
  87787. res.pData, res.nData, tmp.pData, tmp.nData, 0, 0, eType, pResult
  87788. );
  87789. dataBufferDestroy(&res);
  87790. dataBufferDestroy(&tmp);
  87791. }
  87792. }
  87793. }
  87794. return rc;
  87795. }
  87796. /*
  87797. ** Evaluate the full-text expression pExpr against fts3 table pTab. Write
  87798. ** the results into pRes.
  87799. */
  87800. static int evalFts3Expr(
  87801. fulltext_vtab *pTab, /* Fts3 Virtual table object */
  87802. Fts3Expr *pExpr, /* Parsed fts3 expression */
  87803. DataBuffer *pRes /* OUT: Write results of the expression here */
  87804. ){
  87805. int rc = SQLITE_OK;
  87806. /* Initialize the output buffer. If this is an empty query (pExpr==0),
  87807. ** this is all that needs to be done. Empty queries produce empty
  87808. ** result sets.
  87809. */
  87810. dataBufferInit(pRes, 0);
  87811. if( pExpr ){
  87812. if( pExpr->eType==FTSQUERY_PHRASE ){
  87813. DocListType eType = DL_DOCIDS;
  87814. if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
  87815. eType = DL_POSITIONS;
  87816. }
  87817. rc = docListOfPhrase(pTab, pExpr->pPhrase, eType, pRes);
  87818. }else{
  87819. DataBuffer lhs;
  87820. DataBuffer rhs;
  87821. dataBufferInit(&rhs, 0);
  87822. if( SQLITE_OK==(rc = evalFts3Expr(pTab, pExpr->pLeft, &lhs))
  87823. && SQLITE_OK==(rc = evalFts3Expr(pTab, pExpr->pRight, &rhs))
  87824. ){
  87825. switch( pExpr->eType ){
  87826. case FTSQUERY_NEAR: {
  87827. int nToken;
  87828. Fts3Expr *pLeft;
  87829. DocListType eType = DL_DOCIDS;
  87830. if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
  87831. eType = DL_POSITIONS;
  87832. }
  87833. pLeft = pExpr->pLeft;
  87834. while( pLeft->eType==FTSQUERY_NEAR ){
  87835. pLeft=pLeft->pRight;
  87836. }
  87837. assert( pExpr->pRight->eType==FTSQUERY_PHRASE );
  87838. assert( pLeft->eType==FTSQUERY_PHRASE );
  87839. nToken = pLeft->pPhrase->nToken + pExpr->pRight->pPhrase->nToken;
  87840. docListPhraseMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData,
  87841. pExpr->nNear+1, nToken, eType, pRes
  87842. );
  87843. break;
  87844. }
  87845. case FTSQUERY_NOT: {
  87846. docListExceptMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData,pRes);
  87847. break;
  87848. }
  87849. case FTSQUERY_AND: {
  87850. docListAndMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData, pRes);
  87851. break;
  87852. }
  87853. case FTSQUERY_OR: {
  87854. docListOrMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData, pRes);
  87855. break;
  87856. }
  87857. }
  87858. }
  87859. dataBufferDestroy(&lhs);
  87860. dataBufferDestroy(&rhs);
  87861. }
  87862. }
  87863. return rc;
  87864. }
  87865. /* TODO(shess) Refactor the code to remove this forward decl. */
  87866. static int flushPendingTerms(fulltext_vtab *v);
  87867. /* Perform a full-text query using the search expression in
  87868. ** zInput[0..nInput-1]. Return a list of matching documents
  87869. ** in pResult.
  87870. **
  87871. ** Queries must match column iColumn. Or if iColumn>=nColumn
  87872. ** they are allowed to match against any column.
  87873. */
  87874. static int fulltextQuery(
  87875. fulltext_vtab *v, /* The full text index */
  87876. int iColumn, /* Match against this column by default */
  87877. const char *zInput, /* The query string */
  87878. int nInput, /* Number of bytes in zInput[] */
  87879. DataBuffer *pResult, /* Write the result doclist here */
  87880. Fts3Expr **ppExpr /* Put parsed query string here */
  87881. ){
  87882. int rc;
  87883. /* TODO(shess) Instead of flushing pendingTerms, we could query for
  87884. ** the relevant term and merge the doclist into what we receive from
  87885. ** the database. Wait and see if this is a common issue, first.
  87886. **
  87887. ** A good reason not to flush is to not generate update-related
  87888. ** error codes from here.
  87889. */
  87890. /* Flush any buffered updates before executing the query. */
  87891. rc = flushPendingTerms(v);
  87892. if( rc!=SQLITE_OK ){
  87893. return rc;
  87894. }
  87895. /* Parse the query passed to the MATCH operator. */
  87896. rc = sqlite3Fts3ExprParse(v->pTokenizer,
  87897. v->azColumn, v->nColumn, iColumn, zInput, nInput, ppExpr
  87898. );
  87899. if( rc!=SQLITE_OK ){
  87900. assert( 0==(*ppExpr) );
  87901. return rc;
  87902. }
  87903. return evalFts3Expr(v, *ppExpr, pResult);
  87904. }
  87905. /*
  87906. ** This is the xFilter interface for the virtual table. See
  87907. ** the virtual table xFilter method documentation for additional
  87908. ** information.
  87909. **
  87910. ** If idxNum==QUERY_GENERIC then do a full table scan against
  87911. ** the %_content table.
  87912. **
  87913. ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
  87914. ** in the %_content table.
  87915. **
  87916. ** If idxNum>=QUERY_FULLTEXT then use the full text index. The
  87917. ** column on the left-hand side of the MATCH operator is column
  87918. ** number idxNum-QUERY_FULLTEXT, 0 indexed. argv[0] is the right-hand
  87919. ** side of the MATCH operator.
  87920. */
  87921. /* TODO(shess) Upgrade the cursor initialization and destruction to
  87922. ** account for fulltextFilter() being called multiple times on the
  87923. ** same cursor. The current solution is very fragile. Apply fix to
  87924. ** fts3 as appropriate.
  87925. */
  87926. static int fulltextFilter(
  87927. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  87928. int idxNum, const char *idxStr, /* Which indexing scheme to use */
  87929. int argc, sqlite3_value **argv /* Arguments for the indexing scheme */
  87930. ){
  87931. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  87932. fulltext_vtab *v = cursor_vtab(c);
  87933. int rc;
  87934. FTSTRACE(("FTS3 Filter %p\n",pCursor));
  87935. /* If the cursor has a statement that was not prepared according to
  87936. ** idxNum, clear it. I believe all calls to fulltextFilter with a
  87937. ** given cursor will have the same idxNum , but in this case it's
  87938. ** easy to be safe.
  87939. */
  87940. if( c->pStmt && c->iCursorType!=idxNum ){
  87941. sqlite3_finalize(c->pStmt);
  87942. c->pStmt = NULL;
  87943. }
  87944. /* Get a fresh statement appropriate to idxNum. */
  87945. /* TODO(shess): Add a prepared-statement cache in the vt structure.
  87946. ** The cache must handle multiple open cursors. Easier to cache the
  87947. ** statement variants at the vt to reduce malloc/realloc/free here.
  87948. ** Or we could have a StringBuffer variant which allowed stack
  87949. ** construction for small values.
  87950. */
  87951. if( !c->pStmt ){
  87952. StringBuffer sb;
  87953. initStringBuffer(&sb);
  87954. append(&sb, "SELECT docid, ");
  87955. appendList(&sb, v->nColumn, v->azContentColumn);
  87956. append(&sb, " FROM %_content");
  87957. if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
  87958. rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt,
  87959. stringBufferData(&sb));
  87960. stringBufferDestroy(&sb);
  87961. if( rc!=SQLITE_OK ) return rc;
  87962. c->iCursorType = idxNum;
  87963. }else{
  87964. sqlite3_reset(c->pStmt);
  87965. assert( c->iCursorType==idxNum );
  87966. }
  87967. switch( idxNum ){
  87968. case QUERY_GENERIC:
  87969. break;
  87970. case QUERY_DOCID:
  87971. rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
  87972. if( rc!=SQLITE_OK ) return rc;
  87973. break;
  87974. default: /* full-text search */
  87975. {
  87976. int iCol = idxNum-QUERY_FULLTEXT;
  87977. const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
  87978. assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
  87979. assert( argc==1 );
  87980. if( c->result.nData!=0 ){
  87981. /* This case happens if the same cursor is used repeatedly. */
  87982. dlrDestroy(&c->reader);
  87983. dataBufferReset(&c->result);
  87984. }else{
  87985. dataBufferInit(&c->result, 0);
  87986. }
  87987. rc = fulltextQuery(v, iCol, zQuery, -1, &c->result, &c->pExpr);
  87988. if( rc!=SQLITE_OK ) return rc;
  87989. if( c->result.nData!=0 ){
  87990. dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
  87991. }
  87992. break;
  87993. }
  87994. }
  87995. return fulltextNext(pCursor);
  87996. }
  87997. /* This is the xEof method of the virtual table. The SQLite core
  87998. ** calls this routine to find out if it has reached the end of
  87999. ** a query's results set.
  88000. */
  88001. static int fulltextEof(sqlite3_vtab_cursor *pCursor){
  88002. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  88003. return c->eof;
  88004. }
  88005. /* This is the xColumn method of the virtual table. The SQLite
  88006. ** core calls this method during a query when it needs the value
  88007. ** of a column from the virtual table. This method needs to use
  88008. ** one of the sqlite3_result_*() routines to store the requested
  88009. ** value back in the pContext.
  88010. */
  88011. static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
  88012. sqlite3_context *pContext, int idxCol){
  88013. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  88014. fulltext_vtab *v = cursor_vtab(c);
  88015. if( idxCol<v->nColumn ){
  88016. sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
  88017. sqlite3_result_value(pContext, pVal);
  88018. }else if( idxCol==v->nColumn ){
  88019. /* The extra column whose name is the same as the table.
  88020. ** Return a blob which is a pointer to the cursor
  88021. */
  88022. sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
  88023. }else if( idxCol==v->nColumn+1 ){
  88024. /* The docid column, which is an alias for rowid. */
  88025. sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
  88026. sqlite3_result_value(pContext, pVal);
  88027. }
  88028. return SQLITE_OK;
  88029. }
  88030. /* This is the xRowid method. The SQLite core calls this routine to
  88031. ** retrieve the rowid for the current row of the result set. fts3
  88032. ** exposes %_content.docid as the rowid for the virtual table. The
  88033. ** rowid should be written to *pRowid.
  88034. */
  88035. static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  88036. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  88037. *pRowid = sqlite3_column_int64(c->pStmt, 0);
  88038. return SQLITE_OK;
  88039. }
  88040. /* Add all terms in [zText] to pendingTerms table. If [iColumn] > 0,
  88041. ** we also store positions and offsets in the hash table using that
  88042. ** column number.
  88043. */
  88044. static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
  88045. const char *zText, int iColumn){
  88046. sqlite3_tokenizer *pTokenizer = v->pTokenizer;
  88047. sqlite3_tokenizer_cursor *pCursor;
  88048. const char *pToken;
  88049. int nTokenBytes;
  88050. int iStartOffset, iEndOffset, iPosition;
  88051. int rc;
  88052. rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
  88053. if( rc!=SQLITE_OK ) return rc;
  88054. pCursor->pTokenizer = pTokenizer;
  88055. while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
  88056. &pToken, &nTokenBytes,
  88057. &iStartOffset, &iEndOffset,
  88058. &iPosition)) ){
  88059. DLCollector *p;
  88060. int nData; /* Size of doclist before our update. */
  88061. /* Positions can't be negative; we use -1 as a terminator
  88062. * internally. Token can't be NULL or empty. */
  88063. if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
  88064. rc = SQLITE_ERROR;
  88065. break;
  88066. }
  88067. p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
  88068. if( p==NULL ){
  88069. nData = 0;
  88070. p = dlcNew(iDocid, DL_DEFAULT);
  88071. fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
  88072. /* Overhead for our hash table entry, the key, and the value. */
  88073. v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
  88074. }else{
  88075. nData = p->b.nData;
  88076. if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
  88077. }
  88078. if( iColumn>=0 ){
  88079. dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
  88080. }
  88081. /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
  88082. v->nPendingData += p->b.nData-nData;
  88083. }
  88084. /* TODO(shess) Check return? Should this be able to cause errors at
  88085. ** this point? Actually, same question about sqlite3_finalize(),
  88086. ** though one could argue that failure there means that the data is
  88087. ** not durable. *ponder*
  88088. */
  88089. pTokenizer->pModule->xClose(pCursor);
  88090. if( SQLITE_DONE == rc ) return SQLITE_OK;
  88091. return rc;
  88092. }
  88093. /* Add doclists for all terms in [pValues] to pendingTerms table. */
  88094. static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
  88095. sqlite3_value **pValues){
  88096. int i;
  88097. for(i = 0; i < v->nColumn ; ++i){
  88098. char *zText = (char*)sqlite3_value_text(pValues[i]);
  88099. int rc = buildTerms(v, iDocid, zText, i);
  88100. if( rc!=SQLITE_OK ) return rc;
  88101. }
  88102. return SQLITE_OK;
  88103. }
  88104. /* Add empty doclists for all terms in the given row's content to
  88105. ** pendingTerms.
  88106. */
  88107. static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
  88108. const char **pValues;
  88109. int i, rc;
  88110. /* TODO(shess) Should we allow such tables at all? */
  88111. if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
  88112. rc = content_select(v, iDocid, &pValues);
  88113. if( rc!=SQLITE_OK ) return rc;
  88114. for(i = 0 ; i < v->nColumn; ++i) {
  88115. rc = buildTerms(v, iDocid, pValues[i], -1);
  88116. if( rc!=SQLITE_OK ) break;
  88117. }
  88118. freeStringArray(v->nColumn, pValues);
  88119. return SQLITE_OK;
  88120. }
  88121. /* TODO(shess) Refactor the code to remove this forward decl. */
  88122. static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
  88123. /* Insert a row into the %_content table; set *piDocid to be the ID of the
  88124. ** new row. Add doclists for terms to pendingTerms.
  88125. */
  88126. static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
  88127. sqlite3_value **pValues, sqlite_int64 *piDocid){
  88128. int rc;
  88129. rc = content_insert(v, pRequestDocid, pValues); /* execute an SQL INSERT */
  88130. if( rc!=SQLITE_OK ) return rc;
  88131. /* docid column is an alias for rowid. */
  88132. *piDocid = sqlite3_last_insert_rowid(v->db);
  88133. rc = initPendingTerms(v, *piDocid);
  88134. if( rc!=SQLITE_OK ) return rc;
  88135. return insertTerms(v, *piDocid, pValues);
  88136. }
  88137. /* Delete a row from the %_content table; add empty doclists for terms
  88138. ** to pendingTerms.
  88139. */
  88140. static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
  88141. int rc = initPendingTerms(v, iRow);
  88142. if( rc!=SQLITE_OK ) return rc;
  88143. rc = deleteTerms(v, iRow);
  88144. if( rc!=SQLITE_OK ) return rc;
  88145. return content_delete(v, iRow); /* execute an SQL DELETE */
  88146. }
  88147. /* Update a row in the %_content table; add delete doclists to
  88148. ** pendingTerms for old terms not in the new data, add insert doclists
  88149. ** to pendingTerms for terms in the new data.
  88150. */
  88151. static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
  88152. sqlite3_value **pValues){
  88153. int rc = initPendingTerms(v, iRow);
  88154. if( rc!=SQLITE_OK ) return rc;
  88155. /* Generate an empty doclist for each term that previously appeared in this
  88156. * row. */
  88157. rc = deleteTerms(v, iRow);
  88158. if( rc!=SQLITE_OK ) return rc;
  88159. rc = content_update(v, pValues, iRow); /* execute an SQL UPDATE */
  88160. if( rc!=SQLITE_OK ) return rc;
  88161. /* Now add positions for terms which appear in the updated row. */
  88162. return insertTerms(v, iRow, pValues);
  88163. }
  88164. /*******************************************************************/
  88165. /* InteriorWriter is used to collect terms and block references into
  88166. ** interior nodes in %_segments. See commentary at top of file for
  88167. ** format.
  88168. */
  88169. /* How large interior nodes can grow. */
  88170. #define INTERIOR_MAX 2048
  88171. /* Minimum number of terms per interior node (except the root). This
  88172. ** prevents large terms from making the tree too skinny - must be >0
  88173. ** so that the tree always makes progress. Note that the min tree
  88174. ** fanout will be INTERIOR_MIN_TERMS+1.
  88175. */
  88176. #define INTERIOR_MIN_TERMS 7
  88177. #if INTERIOR_MIN_TERMS<1
  88178. # error INTERIOR_MIN_TERMS must be greater than 0.
  88179. #endif
  88180. /* ROOT_MAX controls how much data is stored inline in the segment
  88181. ** directory.
  88182. */
  88183. /* TODO(shess) Push ROOT_MAX down to whoever is writing things. It's
  88184. ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
  88185. ** can both see it, but if the caller passed it in, we wouldn't even
  88186. ** need a define.
  88187. */
  88188. #define ROOT_MAX 1024
  88189. #if ROOT_MAX<VARINT_MAX*2
  88190. # error ROOT_MAX must have enough space for a header.
  88191. #endif
  88192. /* InteriorBlock stores a linked-list of interior blocks while a lower
  88193. ** layer is being constructed.
  88194. */
  88195. typedef struct InteriorBlock {
  88196. DataBuffer term; /* Leftmost term in block's subtree. */
  88197. DataBuffer data; /* Accumulated data for the block. */
  88198. struct InteriorBlock *next;
  88199. } InteriorBlock;
  88200. static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
  88201. const char *pTerm, int nTerm){
  88202. InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
  88203. char c[VARINT_MAX+VARINT_MAX];
  88204. int n;
  88205. if( block ){
  88206. memset(block, 0, sizeof(*block));
  88207. dataBufferInit(&block->term, 0);
  88208. dataBufferReplace(&block->term, pTerm, nTerm);
  88209. n = fts3PutVarint(c, iHeight);
  88210. n += fts3PutVarint(c+n, iChildBlock);
  88211. dataBufferInit(&block->data, INTERIOR_MAX);
  88212. dataBufferReplace(&block->data, c, n);
  88213. }
  88214. return block;
  88215. }
  88216. #ifndef NDEBUG
  88217. /* Verify that the data is readable as an interior node. */
  88218. static void interiorBlockValidate(InteriorBlock *pBlock){
  88219. const char *pData = pBlock->data.pData;
  88220. int nData = pBlock->data.nData;
  88221. int n, iDummy;
  88222. sqlite_int64 iBlockid;
  88223. assert( nData>0 );
  88224. assert( pData!=0 );
  88225. assert( pData+nData>pData );
  88226. /* Must lead with height of node as a varint(n), n>0 */
  88227. n = fts3GetVarint32(pData, &iDummy);
  88228. assert( n>0 );
  88229. assert( iDummy>0 );
  88230. assert( n<nData );
  88231. pData += n;
  88232. nData -= n;
  88233. /* Must contain iBlockid. */
  88234. n = fts3GetVarint(pData, &iBlockid);
  88235. assert( n>0 );
  88236. assert( n<=nData );
  88237. pData += n;
  88238. nData -= n;
  88239. /* Zero or more terms of positive length */
  88240. if( nData!=0 ){
  88241. /* First term is not delta-encoded. */
  88242. n = fts3GetVarint32(pData, &iDummy);
  88243. assert( n>0 );
  88244. assert( iDummy>0 );
  88245. assert( n+iDummy>0);
  88246. assert( n+iDummy<=nData );
  88247. pData += n+iDummy;
  88248. nData -= n+iDummy;
  88249. /* Following terms delta-encoded. */
  88250. while( nData!=0 ){
  88251. /* Length of shared prefix. */
  88252. n = fts3GetVarint32(pData, &iDummy);
  88253. assert( n>0 );
  88254. assert( iDummy>=0 );
  88255. assert( n<nData );
  88256. pData += n;
  88257. nData -= n;
  88258. /* Length and data of distinct suffix. */
  88259. n = fts3GetVarint32(pData, &iDummy);
  88260. assert( n>0 );
  88261. assert( iDummy>0 );
  88262. assert( n+iDummy>0);
  88263. assert( n+iDummy<=nData );
  88264. pData += n+iDummy;
  88265. nData -= n+iDummy;
  88266. }
  88267. }
  88268. }
  88269. #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
  88270. #else
  88271. #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
  88272. #endif
  88273. typedef struct InteriorWriter {
  88274. int iHeight; /* from 0 at leaves. */
  88275. InteriorBlock *first, *last;
  88276. struct InteriorWriter *parentWriter;
  88277. DataBuffer term; /* Last term written to block "last". */
  88278. sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
  88279. #ifndef NDEBUG
  88280. sqlite_int64 iLastChildBlock; /* for consistency checks. */
  88281. #endif
  88282. } InteriorWriter;
  88283. /* Initialize an interior node where pTerm[nTerm] marks the leftmost
  88284. ** term in the tree. iChildBlock is the leftmost child block at the
  88285. ** next level down the tree.
  88286. */
  88287. static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
  88288. sqlite_int64 iChildBlock,
  88289. InteriorWriter *pWriter){
  88290. InteriorBlock *block;
  88291. assert( iHeight>0 );
  88292. CLEAR(pWriter);
  88293. pWriter->iHeight = iHeight;
  88294. pWriter->iOpeningChildBlock = iChildBlock;
  88295. #ifndef NDEBUG
  88296. pWriter->iLastChildBlock = iChildBlock;
  88297. #endif
  88298. block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
  88299. pWriter->last = pWriter->first = block;
  88300. ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  88301. dataBufferInit(&pWriter->term, 0);
  88302. }
  88303. /* Append the child node rooted at iChildBlock to the interior node,
  88304. ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
  88305. */
  88306. static void interiorWriterAppend(InteriorWriter *pWriter,
  88307. const char *pTerm, int nTerm,
  88308. sqlite_int64 iChildBlock){
  88309. char c[VARINT_MAX+VARINT_MAX];
  88310. int n, nPrefix = 0;
  88311. ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  88312. /* The first term written into an interior node is actually
  88313. ** associated with the second child added (the first child was added
  88314. ** in interiorWriterInit, or in the if clause at the bottom of this
  88315. ** function). That term gets encoded straight up, with nPrefix left
  88316. ** at 0.
  88317. */
  88318. if( pWriter->term.nData==0 ){
  88319. n = fts3PutVarint(c, nTerm);
  88320. }else{
  88321. while( nPrefix<pWriter->term.nData &&
  88322. pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
  88323. nPrefix++;
  88324. }
  88325. n = fts3PutVarint(c, nPrefix);
  88326. n += fts3PutVarint(c+n, nTerm-nPrefix);
  88327. }
  88328. #ifndef NDEBUG
  88329. pWriter->iLastChildBlock++;
  88330. #endif
  88331. assert( pWriter->iLastChildBlock==iChildBlock );
  88332. /* Overflow to a new block if the new term makes the current block
  88333. ** too big, and the current block already has enough terms.
  88334. */
  88335. if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
  88336. iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
  88337. pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
  88338. pTerm, nTerm);
  88339. pWriter->last = pWriter->last->next;
  88340. pWriter->iOpeningChildBlock = iChildBlock;
  88341. dataBufferReset(&pWriter->term);
  88342. }else{
  88343. dataBufferAppend2(&pWriter->last->data, c, n,
  88344. pTerm+nPrefix, nTerm-nPrefix);
  88345. dataBufferReplace(&pWriter->term, pTerm, nTerm);
  88346. }
  88347. ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  88348. }
  88349. /* Free the space used by pWriter, including the linked-list of
  88350. ** InteriorBlocks, and parentWriter, if present.
  88351. */
  88352. static int interiorWriterDestroy(InteriorWriter *pWriter){
  88353. InteriorBlock *block = pWriter->first;
  88354. while( block!=NULL ){
  88355. InteriorBlock *b = block;
  88356. block = block->next;
  88357. dataBufferDestroy(&b->term);
  88358. dataBufferDestroy(&b->data);
  88359. sqlite3_free(b);
  88360. }
  88361. if( pWriter->parentWriter!=NULL ){
  88362. interiorWriterDestroy(pWriter->parentWriter);
  88363. sqlite3_free(pWriter->parentWriter);
  88364. }
  88365. dataBufferDestroy(&pWriter->term);
  88366. SCRAMBLE(pWriter);
  88367. return SQLITE_OK;
  88368. }
  88369. /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
  88370. ** directly, leaving *piEndBlockid unchanged. Otherwise, flush
  88371. ** pWriter to %_segments, building a new layer of interior nodes, and
  88372. ** recursively ask for their root into.
  88373. */
  88374. static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
  88375. char **ppRootInfo, int *pnRootInfo,
  88376. sqlite_int64 *piEndBlockid){
  88377. InteriorBlock *block = pWriter->first;
  88378. sqlite_int64 iBlockid = 0;
  88379. int rc;
  88380. /* If we can fit the segment inline */
  88381. if( block==pWriter->last && block->data.nData<ROOT_MAX ){
  88382. *ppRootInfo = block->data.pData;
  88383. *pnRootInfo = block->data.nData;
  88384. return SQLITE_OK;
  88385. }
  88386. /* Flush the first block to %_segments, and create a new level of
  88387. ** interior node.
  88388. */
  88389. ASSERT_VALID_INTERIOR_BLOCK(block);
  88390. rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
  88391. if( rc!=SQLITE_OK ) return rc;
  88392. *piEndBlockid = iBlockid;
  88393. pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
  88394. interiorWriterInit(pWriter->iHeight+1,
  88395. block->term.pData, block->term.nData,
  88396. iBlockid, pWriter->parentWriter);
  88397. /* Flush additional blocks and append to the higher interior
  88398. ** node.
  88399. */
  88400. for(block=block->next; block!=NULL; block=block->next){
  88401. ASSERT_VALID_INTERIOR_BLOCK(block);
  88402. rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
  88403. if( rc!=SQLITE_OK ) return rc;
  88404. *piEndBlockid = iBlockid;
  88405. interiorWriterAppend(pWriter->parentWriter,
  88406. block->term.pData, block->term.nData, iBlockid);
  88407. }
  88408. /* Parent node gets the chance to be the root. */
  88409. return interiorWriterRootInfo(v, pWriter->parentWriter,
  88410. ppRootInfo, pnRootInfo, piEndBlockid);
  88411. }
  88412. /****************************************************************/
  88413. /* InteriorReader is used to read off the data from an interior node
  88414. ** (see comment at top of file for the format).
  88415. */
  88416. typedef struct InteriorReader {
  88417. const char *pData;
  88418. int nData;
  88419. DataBuffer term; /* previous term, for decoding term delta. */
  88420. sqlite_int64 iBlockid;
  88421. } InteriorReader;
  88422. static void interiorReaderDestroy(InteriorReader *pReader){
  88423. dataBufferDestroy(&pReader->term);
  88424. SCRAMBLE(pReader);
  88425. }
  88426. /* TODO(shess) The assertions are great, but what if we're in NDEBUG
  88427. ** and the blob is empty or otherwise contains suspect data?
  88428. */
  88429. static void interiorReaderInit(const char *pData, int nData,
  88430. InteriorReader *pReader){
  88431. int n, nTerm;
  88432. /* Require at least the leading flag byte */
  88433. assert( nData>0 );
  88434. assert( pData[0]!='\0' );
  88435. CLEAR(pReader);
  88436. /* Decode the base blockid, and set the cursor to the first term. */
  88437. n = fts3GetVarint(pData+1, &pReader->iBlockid);
  88438. assert( 1+n<=nData );
  88439. pReader->pData = pData+1+n;
  88440. pReader->nData = nData-(1+n);
  88441. /* A single-child interior node (such as when a leaf node was too
  88442. ** large for the segment directory) won't have any terms.
  88443. ** Otherwise, decode the first term.
  88444. */
  88445. if( pReader->nData==0 ){
  88446. dataBufferInit(&pReader->term, 0);
  88447. }else{
  88448. n = fts3GetVarint32(pReader->pData, &nTerm);
  88449. dataBufferInit(&pReader->term, nTerm);
  88450. dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
  88451. assert( n+nTerm<=pReader->nData );
  88452. pReader->pData += n+nTerm;
  88453. pReader->nData -= n+nTerm;
  88454. }
  88455. }
  88456. static int interiorReaderAtEnd(InteriorReader *pReader){
  88457. return pReader->term.nData==0;
  88458. }
  88459. static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
  88460. return pReader->iBlockid;
  88461. }
  88462. static int interiorReaderTermBytes(InteriorReader *pReader){
  88463. assert( !interiorReaderAtEnd(pReader) );
  88464. return pReader->term.nData;
  88465. }
  88466. static const char *interiorReaderTerm(InteriorReader *pReader){
  88467. assert( !interiorReaderAtEnd(pReader) );
  88468. return pReader->term.pData;
  88469. }
  88470. /* Step forward to the next term in the node. */
  88471. static void interiorReaderStep(InteriorReader *pReader){
  88472. assert( !interiorReaderAtEnd(pReader) );
  88473. /* If the last term has been read, signal eof, else construct the
  88474. ** next term.
  88475. */
  88476. if( pReader->nData==0 ){
  88477. dataBufferReset(&pReader->term);
  88478. }else{
  88479. int n, nPrefix, nSuffix;
  88480. n = fts3GetVarint32(pReader->pData, &nPrefix);
  88481. n += fts3GetVarint32(pReader->pData+n, &nSuffix);
  88482. /* Truncate the current term and append suffix data. */
  88483. pReader->term.nData = nPrefix;
  88484. dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
  88485. assert( n+nSuffix<=pReader->nData );
  88486. pReader->pData += n+nSuffix;
  88487. pReader->nData -= n+nSuffix;
  88488. }
  88489. pReader->iBlockid++;
  88490. }
  88491. /* Compare the current term to pTerm[nTerm], returning strcmp-style
  88492. ** results. If isPrefix, equality means equal through nTerm bytes.
  88493. */
  88494. static int interiorReaderTermCmp(InteriorReader *pReader,
  88495. const char *pTerm, int nTerm, int isPrefix){
  88496. const char *pReaderTerm = interiorReaderTerm(pReader);
  88497. int nReaderTerm = interiorReaderTermBytes(pReader);
  88498. int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
  88499. if( n==0 ){
  88500. if( nReaderTerm>0 ) return -1;
  88501. if( nTerm>0 ) return 1;
  88502. return 0;
  88503. }
  88504. c = memcmp(pReaderTerm, pTerm, n);
  88505. if( c!=0 ) return c;
  88506. if( isPrefix && n==nTerm ) return 0;
  88507. return nReaderTerm - nTerm;
  88508. }
  88509. /****************************************************************/
  88510. /* LeafWriter is used to collect terms and associated doclist data
  88511. ** into leaf blocks in %_segments (see top of file for format info).
  88512. ** Expected usage is:
  88513. **
  88514. ** LeafWriter writer;
  88515. ** leafWriterInit(0, 0, &writer);
  88516. ** while( sorted_terms_left_to_process ){
  88517. ** // data is doclist data for that term.
  88518. ** rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
  88519. ** if( rc!=SQLITE_OK ) goto err;
  88520. ** }
  88521. ** rc = leafWriterFinalize(v, &writer);
  88522. **err:
  88523. ** leafWriterDestroy(&writer);
  88524. ** return rc;
  88525. **
  88526. ** leafWriterStep() may write a collected leaf out to %_segments.
  88527. ** leafWriterFinalize() finishes writing any buffered data and stores
  88528. ** a root node in %_segdir. leafWriterDestroy() frees all buffers and
  88529. ** InteriorWriters allocated as part of writing this segment.
  88530. **
  88531. ** TODO(shess) Document leafWriterStepMerge().
  88532. */
  88533. /* Put terms with data this big in their own block. */
  88534. #define STANDALONE_MIN 1024
  88535. /* Keep leaf blocks below this size. */
  88536. #define LEAF_MAX 2048
  88537. typedef struct LeafWriter {
  88538. int iLevel;
  88539. int idx;
  88540. sqlite_int64 iStartBlockid; /* needed to create the root info */
  88541. sqlite_int64 iEndBlockid; /* when we're done writing. */
  88542. DataBuffer term; /* previous encoded term */
  88543. DataBuffer data; /* encoding buffer */
  88544. /* bytes of first term in the current node which distinguishes that
  88545. ** term from the last term of the previous node.
  88546. */
  88547. int nTermDistinct;
  88548. InteriorWriter parentWriter; /* if we overflow */
  88549. int has_parent;
  88550. } LeafWriter;
  88551. static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
  88552. CLEAR(pWriter);
  88553. pWriter->iLevel = iLevel;
  88554. pWriter->idx = idx;
  88555. dataBufferInit(&pWriter->term, 32);
  88556. /* Start out with a reasonably sized block, though it can grow. */
  88557. dataBufferInit(&pWriter->data, LEAF_MAX);
  88558. }
  88559. #ifndef NDEBUG
  88560. /* Verify that the data is readable as a leaf node. */
  88561. static void leafNodeValidate(const char *pData, int nData){
  88562. int n, iDummy;
  88563. if( nData==0 ) return;
  88564. assert( nData>0 );
  88565. assert( pData!=0 );
  88566. assert( pData+nData>pData );
  88567. /* Must lead with a varint(0) */
  88568. n = fts3GetVarint32(pData, &iDummy);
  88569. assert( iDummy==0 );
  88570. assert( n>0 );
  88571. assert( n<nData );
  88572. pData += n;
  88573. nData -= n;
  88574. /* Leading term length and data must fit in buffer. */
  88575. n = fts3GetVarint32(pData, &iDummy);
  88576. assert( n>0 );
  88577. assert( iDummy>0 );
  88578. assert( n+iDummy>0 );
  88579. assert( n+iDummy<nData );
  88580. pData += n+iDummy;
  88581. nData -= n+iDummy;
  88582. /* Leading term's doclist length and data must fit. */
  88583. n = fts3GetVarint32(pData, &iDummy);
  88584. assert( n>0 );
  88585. assert( iDummy>0 );
  88586. assert( n+iDummy>0 );
  88587. assert( n+iDummy<=nData );
  88588. ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
  88589. pData += n+iDummy;
  88590. nData -= n+iDummy;
  88591. /* Verify that trailing terms and doclists also are readable. */
  88592. while( nData!=0 ){
  88593. n = fts3GetVarint32(pData, &iDummy);
  88594. assert( n>0 );
  88595. assert( iDummy>=0 );
  88596. assert( n<nData );
  88597. pData += n;
  88598. nData -= n;
  88599. n = fts3GetVarint32(pData, &iDummy);
  88600. assert( n>0 );
  88601. assert( iDummy>0 );
  88602. assert( n+iDummy>0 );
  88603. assert( n+iDummy<nData );
  88604. pData += n+iDummy;
  88605. nData -= n+iDummy;
  88606. n = fts3GetVarint32(pData, &iDummy);
  88607. assert( n>0 );
  88608. assert( iDummy>0 );
  88609. assert( n+iDummy>0 );
  88610. assert( n+iDummy<=nData );
  88611. ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
  88612. pData += n+iDummy;
  88613. nData -= n+iDummy;
  88614. }
  88615. }
  88616. #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
  88617. #else
  88618. #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
  88619. #endif
  88620. /* Flush the current leaf node to %_segments, and adding the resulting
  88621. ** blockid and the starting term to the interior node which will
  88622. ** contain it.
  88623. */
  88624. static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
  88625. int iData, int nData){
  88626. sqlite_int64 iBlockid = 0;
  88627. const char *pStartingTerm;
  88628. int nStartingTerm, rc, n;
  88629. /* Must have the leading varint(0) flag, plus at least some
  88630. ** valid-looking data.
  88631. */
  88632. assert( nData>2 );
  88633. assert( iData>=0 );
  88634. assert( iData+nData<=pWriter->data.nData );
  88635. ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
  88636. rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
  88637. if( rc!=SQLITE_OK ) return rc;
  88638. assert( iBlockid!=0 );
  88639. /* Reconstruct the first term in the leaf for purposes of building
  88640. ** the interior node.
  88641. */
  88642. n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
  88643. pStartingTerm = pWriter->data.pData+iData+1+n;
  88644. assert( pWriter->data.nData>iData+1+n+nStartingTerm );
  88645. assert( pWriter->nTermDistinct>0 );
  88646. assert( pWriter->nTermDistinct<=nStartingTerm );
  88647. nStartingTerm = pWriter->nTermDistinct;
  88648. if( pWriter->has_parent ){
  88649. interiorWriterAppend(&pWriter->parentWriter,
  88650. pStartingTerm, nStartingTerm, iBlockid);
  88651. }else{
  88652. interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
  88653. &pWriter->parentWriter);
  88654. pWriter->has_parent = 1;
  88655. }
  88656. /* Track the span of this segment's leaf nodes. */
  88657. if( pWriter->iEndBlockid==0 ){
  88658. pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
  88659. }else{
  88660. pWriter->iEndBlockid++;
  88661. assert( iBlockid==pWriter->iEndBlockid );
  88662. }
  88663. return SQLITE_OK;
  88664. }
  88665. static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
  88666. int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
  88667. if( rc!=SQLITE_OK ) return rc;
  88668. /* Re-initialize the output buffer. */
  88669. dataBufferReset(&pWriter->data);
  88670. return SQLITE_OK;
  88671. }
  88672. /* Fetch the root info for the segment. If the entire leaf fits
  88673. ** within ROOT_MAX, then it will be returned directly, otherwise it
  88674. ** will be flushed and the root info will be returned from the
  88675. ** interior node. *piEndBlockid is set to the blockid of the last
  88676. ** interior or leaf node written to disk (0 if none are written at
  88677. ** all).
  88678. */
  88679. static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
  88680. char **ppRootInfo, int *pnRootInfo,
  88681. sqlite_int64 *piEndBlockid){
  88682. /* we can fit the segment entirely inline */
  88683. if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
  88684. *ppRootInfo = pWriter->data.pData;
  88685. *pnRootInfo = pWriter->data.nData;
  88686. *piEndBlockid = 0;
  88687. return SQLITE_OK;
  88688. }
  88689. /* Flush remaining leaf data. */
  88690. if( pWriter->data.nData>0 ){
  88691. int rc = leafWriterFlush(v, pWriter);
  88692. if( rc!=SQLITE_OK ) return rc;
  88693. }
  88694. /* We must have flushed a leaf at some point. */
  88695. assert( pWriter->has_parent );
  88696. /* Tenatively set the end leaf blockid as the end blockid. If the
  88697. ** interior node can be returned inline, this will be the final
  88698. ** blockid, otherwise it will be overwritten by
  88699. ** interiorWriterRootInfo().
  88700. */
  88701. *piEndBlockid = pWriter->iEndBlockid;
  88702. return interiorWriterRootInfo(v, &pWriter->parentWriter,
  88703. ppRootInfo, pnRootInfo, piEndBlockid);
  88704. }
  88705. /* Collect the rootInfo data and store it into the segment directory.
  88706. ** This has the effect of flushing the segment's leaf data to
  88707. ** %_segments, and also flushing any interior nodes to %_segments.
  88708. */
  88709. static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
  88710. sqlite_int64 iEndBlockid;
  88711. char *pRootInfo;
  88712. int rc, nRootInfo;
  88713. rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
  88714. if( rc!=SQLITE_OK ) return rc;
  88715. /* Don't bother storing an entirely empty segment. */
  88716. if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
  88717. return segdir_set(v, pWriter->iLevel, pWriter->idx,
  88718. pWriter->iStartBlockid, pWriter->iEndBlockid,
  88719. iEndBlockid, pRootInfo, nRootInfo);
  88720. }
  88721. static void leafWriterDestroy(LeafWriter *pWriter){
  88722. if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
  88723. dataBufferDestroy(&pWriter->term);
  88724. dataBufferDestroy(&pWriter->data);
  88725. }
  88726. /* Encode a term into the leafWriter, delta-encoding as appropriate.
  88727. ** Returns the length of the new term which distinguishes it from the
  88728. ** previous term, which can be used to set nTermDistinct when a node
  88729. ** boundary is crossed.
  88730. */
  88731. static int leafWriterEncodeTerm(LeafWriter *pWriter,
  88732. const char *pTerm, int nTerm){
  88733. char c[VARINT_MAX+VARINT_MAX];
  88734. int n, nPrefix = 0;
  88735. assert( nTerm>0 );
  88736. while( nPrefix<pWriter->term.nData &&
  88737. pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
  88738. nPrefix++;
  88739. /* Failing this implies that the terms weren't in order. */
  88740. assert( nPrefix<nTerm );
  88741. }
  88742. if( pWriter->data.nData==0 ){
  88743. /* Encode the node header and leading term as:
  88744. ** varint(0)
  88745. ** varint(nTerm)
  88746. ** char pTerm[nTerm]
  88747. */
  88748. n = fts3PutVarint(c, '\0');
  88749. n += fts3PutVarint(c+n, nTerm);
  88750. dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
  88751. }else{
  88752. /* Delta-encode the term as:
  88753. ** varint(nPrefix)
  88754. ** varint(nSuffix)
  88755. ** char pTermSuffix[nSuffix]
  88756. */
  88757. n = fts3PutVarint(c, nPrefix);
  88758. n += fts3PutVarint(c+n, nTerm-nPrefix);
  88759. dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
  88760. }
  88761. dataBufferReplace(&pWriter->term, pTerm, nTerm);
  88762. return nPrefix+1;
  88763. }
  88764. /* Used to avoid a memmove when a large amount of doclist data is in
  88765. ** the buffer. This constructs a node and term header before
  88766. ** iDoclistData and flushes the resulting complete node using
  88767. ** leafWriterInternalFlush().
  88768. */
  88769. static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
  88770. const char *pTerm, int nTerm,
  88771. int iDoclistData){
  88772. char c[VARINT_MAX+VARINT_MAX];
  88773. int iData, n = fts3PutVarint(c, 0);
  88774. n += fts3PutVarint(c+n, nTerm);
  88775. /* There should always be room for the header. Even if pTerm shared
  88776. ** a substantial prefix with the previous term, the entire prefix
  88777. ** could be constructed from earlier data in the doclist, so there
  88778. ** should be room.
  88779. */
  88780. assert( iDoclistData>=n+nTerm );
  88781. iData = iDoclistData-(n+nTerm);
  88782. memcpy(pWriter->data.pData+iData, c, n);
  88783. memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
  88784. return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
  88785. }
  88786. /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
  88787. ** %_segments.
  88788. */
  88789. static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
  88790. const char *pTerm, int nTerm,
  88791. DLReader *pReaders, int nReaders){
  88792. char c[VARINT_MAX+VARINT_MAX];
  88793. int iTermData = pWriter->data.nData, iDoclistData;
  88794. int i, nData, n, nActualData, nActual, rc, nTermDistinct;
  88795. ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
  88796. nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
  88797. /* Remember nTermDistinct if opening a new node. */
  88798. if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
  88799. iDoclistData = pWriter->data.nData;
  88800. /* Estimate the length of the merged doclist so we can leave space
  88801. ** to encode it.
  88802. */
  88803. for(i=0, nData=0; i<nReaders; i++){
  88804. nData += dlrAllDataBytes(&pReaders[i]);
  88805. }
  88806. n = fts3PutVarint(c, nData);
  88807. dataBufferAppend(&pWriter->data, c, n);
  88808. docListMerge(&pWriter->data, pReaders, nReaders);
  88809. ASSERT_VALID_DOCLIST(DL_DEFAULT,
  88810. pWriter->data.pData+iDoclistData+n,
  88811. pWriter->data.nData-iDoclistData-n, NULL);
  88812. /* The actual amount of doclist data at this point could be smaller
  88813. ** than the length we encoded. Additionally, the space required to
  88814. ** encode this length could be smaller. For small doclists, this is
  88815. ** not a big deal, we can just use memmove() to adjust things.
  88816. */
  88817. nActualData = pWriter->data.nData-(iDoclistData+n);
  88818. nActual = fts3PutVarint(c, nActualData);
  88819. assert( nActualData<=nData );
  88820. assert( nActual<=n );
  88821. /* If the new doclist is big enough for force a standalone leaf
  88822. ** node, we can immediately flush it inline without doing the
  88823. ** memmove().
  88824. */
  88825. /* TODO(shess) This test matches leafWriterStep(), which does this
  88826. ** test before it knows the cost to varint-encode the term and
  88827. ** doclist lengths. At some point, change to
  88828. ** pWriter->data.nData-iTermData>STANDALONE_MIN.
  88829. */
  88830. if( nTerm+nActualData>STANDALONE_MIN ){
  88831. /* Push leaf node from before this term. */
  88832. if( iTermData>0 ){
  88833. rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
  88834. if( rc!=SQLITE_OK ) return rc;
  88835. pWriter->nTermDistinct = nTermDistinct;
  88836. }
  88837. /* Fix the encoded doclist length. */
  88838. iDoclistData += n - nActual;
  88839. memcpy(pWriter->data.pData+iDoclistData, c, nActual);
  88840. /* Push the standalone leaf node. */
  88841. rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
  88842. if( rc!=SQLITE_OK ) return rc;
  88843. /* Leave the node empty. */
  88844. dataBufferReset(&pWriter->data);
  88845. return rc;
  88846. }
  88847. /* At this point, we know that the doclist was small, so do the
  88848. ** memmove if indicated.
  88849. */
  88850. if( nActual<n ){
  88851. memmove(pWriter->data.pData+iDoclistData+nActual,
  88852. pWriter->data.pData+iDoclistData+n,
  88853. pWriter->data.nData-(iDoclistData+n));
  88854. pWriter->data.nData -= n-nActual;
  88855. }
  88856. /* Replace written length with actual length. */
  88857. memcpy(pWriter->data.pData+iDoclistData, c, nActual);
  88858. /* If the node is too large, break things up. */
  88859. /* TODO(shess) This test matches leafWriterStep(), which does this
  88860. ** test before it knows the cost to varint-encode the term and
  88861. ** doclist lengths. At some point, change to
  88862. ** pWriter->data.nData>LEAF_MAX.
  88863. */
  88864. if( iTermData+nTerm+nActualData>LEAF_MAX ){
  88865. /* Flush out the leading data as a node */
  88866. rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
  88867. if( rc!=SQLITE_OK ) return rc;
  88868. pWriter->nTermDistinct = nTermDistinct;
  88869. /* Rebuild header using the current term */
  88870. n = fts3PutVarint(pWriter->data.pData, 0);
  88871. n += fts3PutVarint(pWriter->data.pData+n, nTerm);
  88872. memcpy(pWriter->data.pData+n, pTerm, nTerm);
  88873. n += nTerm;
  88874. /* There should always be room, because the previous encoding
  88875. ** included all data necessary to construct the term.
  88876. */
  88877. assert( n<iDoclistData );
  88878. /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
  88879. ** following memcpy() is safe (as opposed to needing a memmove).
  88880. */
  88881. assert( 2*STANDALONE_MIN<=LEAF_MAX );
  88882. assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
  88883. memcpy(pWriter->data.pData+n,
  88884. pWriter->data.pData+iDoclistData,
  88885. pWriter->data.nData-iDoclistData);
  88886. pWriter->data.nData -= iDoclistData-n;
  88887. }
  88888. ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
  88889. return SQLITE_OK;
  88890. }
  88891. /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
  88892. ** %_segments.
  88893. */
  88894. /* TODO(shess) Revise writeZeroSegment() so that doclists are
  88895. ** constructed directly in pWriter->data.
  88896. */
  88897. static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
  88898. const char *pTerm, int nTerm,
  88899. const char *pData, int nData){
  88900. int rc;
  88901. DLReader reader;
  88902. dlrInit(&reader, DL_DEFAULT, pData, nData);
  88903. rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
  88904. dlrDestroy(&reader);
  88905. return rc;
  88906. }
  88907. /****************************************************************/
  88908. /* LeafReader is used to iterate over an individual leaf node. */
  88909. typedef struct LeafReader {
  88910. DataBuffer term; /* copy of current term. */
  88911. const char *pData; /* data for current term. */
  88912. int nData;
  88913. } LeafReader;
  88914. static void leafReaderDestroy(LeafReader *pReader){
  88915. dataBufferDestroy(&pReader->term);
  88916. SCRAMBLE(pReader);
  88917. }
  88918. static int leafReaderAtEnd(LeafReader *pReader){
  88919. return pReader->nData<=0;
  88920. }
  88921. /* Access the current term. */
  88922. static int leafReaderTermBytes(LeafReader *pReader){
  88923. return pReader->term.nData;
  88924. }
  88925. static const char *leafReaderTerm(LeafReader *pReader){
  88926. assert( pReader->term.nData>0 );
  88927. return pReader->term.pData;
  88928. }
  88929. /* Access the doclist data for the current term. */
  88930. static int leafReaderDataBytes(LeafReader *pReader){
  88931. int nData;
  88932. assert( pReader->term.nData>0 );
  88933. fts3GetVarint32(pReader->pData, &nData);
  88934. return nData;
  88935. }
  88936. static const char *leafReaderData(LeafReader *pReader){
  88937. int n, nData;
  88938. assert( pReader->term.nData>0 );
  88939. n = fts3GetVarint32(pReader->pData, &nData);
  88940. return pReader->pData+n;
  88941. }
  88942. static void leafReaderInit(const char *pData, int nData,
  88943. LeafReader *pReader){
  88944. int nTerm, n;
  88945. assert( nData>0 );
  88946. assert( pData[0]=='\0' );
  88947. CLEAR(pReader);
  88948. /* Read the first term, skipping the header byte. */
  88949. n = fts3GetVarint32(pData+1, &nTerm);
  88950. dataBufferInit(&pReader->term, nTerm);
  88951. dataBufferReplace(&pReader->term, pData+1+n, nTerm);
  88952. /* Position after the first term. */
  88953. assert( 1+n+nTerm<nData );
  88954. pReader->pData = pData+1+n+nTerm;
  88955. pReader->nData = nData-1-n-nTerm;
  88956. }
  88957. /* Step the reader forward to the next term. */
  88958. static void leafReaderStep(LeafReader *pReader){
  88959. int n, nData, nPrefix, nSuffix;
  88960. assert( !leafReaderAtEnd(pReader) );
  88961. /* Skip previous entry's data block. */
  88962. n = fts3GetVarint32(pReader->pData, &nData);
  88963. assert( n+nData<=pReader->nData );
  88964. pReader->pData += n+nData;
  88965. pReader->nData -= n+nData;
  88966. if( !leafReaderAtEnd(pReader) ){
  88967. /* Construct the new term using a prefix from the old term plus a
  88968. ** suffix from the leaf data.
  88969. */
  88970. n = fts3GetVarint32(pReader->pData, &nPrefix);
  88971. n += fts3GetVarint32(pReader->pData+n, &nSuffix);
  88972. assert( n+nSuffix<pReader->nData );
  88973. pReader->term.nData = nPrefix;
  88974. dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
  88975. pReader->pData += n+nSuffix;
  88976. pReader->nData -= n+nSuffix;
  88977. }
  88978. }
  88979. /* strcmp-style comparison of pReader's current term against pTerm.
  88980. ** If isPrefix, equality means equal through nTerm bytes.
  88981. */
  88982. static int leafReaderTermCmp(LeafReader *pReader,
  88983. const char *pTerm, int nTerm, int isPrefix){
  88984. int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
  88985. if( n==0 ){
  88986. if( pReader->term.nData>0 ) return -1;
  88987. if(nTerm>0 ) return 1;
  88988. return 0;
  88989. }
  88990. c = memcmp(pReader->term.pData, pTerm, n);
  88991. if( c!=0 ) return c;
  88992. if( isPrefix && n==nTerm ) return 0;
  88993. return pReader->term.nData - nTerm;
  88994. }
  88995. /****************************************************************/
  88996. /* LeavesReader wraps LeafReader to allow iterating over the entire
  88997. ** leaf layer of the tree.
  88998. */
  88999. typedef struct LeavesReader {
  89000. int idx; /* Index within the segment. */
  89001. sqlite3_stmt *pStmt; /* Statement we're streaming leaves from. */
  89002. int eof; /* we've seen SQLITE_DONE from pStmt. */
  89003. LeafReader leafReader; /* reader for the current leaf. */
  89004. DataBuffer rootData; /* root data for inline. */
  89005. } LeavesReader;
  89006. /* Access the current term. */
  89007. static int leavesReaderTermBytes(LeavesReader *pReader){
  89008. assert( !pReader->eof );
  89009. return leafReaderTermBytes(&pReader->leafReader);
  89010. }
  89011. static const char *leavesReaderTerm(LeavesReader *pReader){
  89012. assert( !pReader->eof );
  89013. return leafReaderTerm(&pReader->leafReader);
  89014. }
  89015. /* Access the doclist data for the current term. */
  89016. static int leavesReaderDataBytes(LeavesReader *pReader){
  89017. assert( !pReader->eof );
  89018. return leafReaderDataBytes(&pReader->leafReader);
  89019. }
  89020. static const char *leavesReaderData(LeavesReader *pReader){
  89021. assert( !pReader->eof );
  89022. return leafReaderData(&pReader->leafReader);
  89023. }
  89024. static int leavesReaderAtEnd(LeavesReader *pReader){
  89025. return pReader->eof;
  89026. }
  89027. /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
  89028. ** leaving the statement handle open, which locks the table.
  89029. */
  89030. /* TODO(shess) This "solution" is not satisfactory. Really, there
  89031. ** should be check-in function for all statement handles which
  89032. ** arranges to call sqlite3_reset(). This most likely will require
  89033. ** modification to control flow all over the place, though, so for now
  89034. ** just punt.
  89035. **
  89036. ** Note the the current system assumes that segment merges will run to
  89037. ** completion, which is why this particular probably hasn't arisen in
  89038. ** this case. Probably a brittle assumption.
  89039. */
  89040. static int leavesReaderReset(LeavesReader *pReader){
  89041. return sqlite3_reset(pReader->pStmt);
  89042. }
  89043. static void leavesReaderDestroy(LeavesReader *pReader){
  89044. /* If idx is -1, that means we're using a non-cached statement
  89045. ** handle in the optimize() case, so we need to release it.
  89046. */
  89047. if( pReader->pStmt!=NULL && pReader->idx==-1 ){
  89048. sqlite3_finalize(pReader->pStmt);
  89049. }
  89050. leafReaderDestroy(&pReader->leafReader);
  89051. dataBufferDestroy(&pReader->rootData);
  89052. SCRAMBLE(pReader);
  89053. }
  89054. /* Initialize pReader with the given root data (if iStartBlockid==0
  89055. ** the leaf data was entirely contained in the root), or from the
  89056. ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
  89057. */
  89058. static int leavesReaderInit(fulltext_vtab *v,
  89059. int idx,
  89060. sqlite_int64 iStartBlockid,
  89061. sqlite_int64 iEndBlockid,
  89062. const char *pRootData, int nRootData,
  89063. LeavesReader *pReader){
  89064. CLEAR(pReader);
  89065. pReader->idx = idx;
  89066. dataBufferInit(&pReader->rootData, 0);
  89067. if( iStartBlockid==0 ){
  89068. /* Entire leaf level fit in root data. */
  89069. dataBufferReplace(&pReader->rootData, pRootData, nRootData);
  89070. leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
  89071. &pReader->leafReader);
  89072. }else{
  89073. sqlite3_stmt *s;
  89074. int rc = sql_get_leaf_statement(v, idx, &s);
  89075. if( rc!=SQLITE_OK ) return rc;
  89076. rc = sqlite3_bind_int64(s, 1, iStartBlockid);
  89077. if( rc!=SQLITE_OK ) return rc;
  89078. rc = sqlite3_bind_int64(s, 2, iEndBlockid);
  89079. if( rc!=SQLITE_OK ) return rc;
  89080. rc = sqlite3_step(s);
  89081. if( rc==SQLITE_DONE ){
  89082. pReader->eof = 1;
  89083. return SQLITE_OK;
  89084. }
  89085. if( rc!=SQLITE_ROW ) return rc;
  89086. pReader->pStmt = s;
  89087. leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
  89088. sqlite3_column_bytes(pReader->pStmt, 0),
  89089. &pReader->leafReader);
  89090. }
  89091. return SQLITE_OK;
  89092. }
  89093. /* Step the current leaf forward to the next term. If we reach the
  89094. ** end of the current leaf, step forward to the next leaf block.
  89095. */
  89096. static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
  89097. assert( !leavesReaderAtEnd(pReader) );
  89098. leafReaderStep(&pReader->leafReader);
  89099. if( leafReaderAtEnd(&pReader->leafReader) ){
  89100. int rc;
  89101. if( pReader->rootData.pData ){
  89102. pReader->eof = 1;
  89103. return SQLITE_OK;
  89104. }
  89105. rc = sqlite3_step(pReader->pStmt);
  89106. if( rc!=SQLITE_ROW ){
  89107. pReader->eof = 1;
  89108. return rc==SQLITE_DONE ? SQLITE_OK : rc;
  89109. }
  89110. leafReaderDestroy(&pReader->leafReader);
  89111. leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
  89112. sqlite3_column_bytes(pReader->pStmt, 0),
  89113. &pReader->leafReader);
  89114. }
  89115. return SQLITE_OK;
  89116. }
  89117. /* Order LeavesReaders by their term, ignoring idx. Readers at eof
  89118. ** always sort to the end.
  89119. */
  89120. static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
  89121. if( leavesReaderAtEnd(lr1) ){
  89122. if( leavesReaderAtEnd(lr2) ) return 0;
  89123. return 1;
  89124. }
  89125. if( leavesReaderAtEnd(lr2) ) return -1;
  89126. return leafReaderTermCmp(&lr1->leafReader,
  89127. leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
  89128. 0);
  89129. }
  89130. /* Similar to leavesReaderTermCmp(), with additional ordering by idx
  89131. ** so that older segments sort before newer segments.
  89132. */
  89133. static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
  89134. int c = leavesReaderTermCmp(lr1, lr2);
  89135. if( c!=0 ) return c;
  89136. return lr1->idx-lr2->idx;
  89137. }
  89138. /* Assume that pLr[1]..pLr[nLr] are sorted. Bubble pLr[0] into its
  89139. ** sorted position.
  89140. */
  89141. static void leavesReaderReorder(LeavesReader *pLr, int nLr){
  89142. while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
  89143. LeavesReader tmp = pLr[0];
  89144. pLr[0] = pLr[1];
  89145. pLr[1] = tmp;
  89146. nLr--;
  89147. pLr++;
  89148. }
  89149. }
  89150. /* Initializes pReaders with the segments from level iLevel, returning
  89151. ** the number of segments in *piReaders. Leaves pReaders in sorted
  89152. ** order.
  89153. */
  89154. static int leavesReadersInit(fulltext_vtab *v, int iLevel,
  89155. LeavesReader *pReaders, int *piReaders){
  89156. sqlite3_stmt *s;
  89157. int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
  89158. if( rc!=SQLITE_OK ) return rc;
  89159. rc = sqlite3_bind_int(s, 1, iLevel);
  89160. if( rc!=SQLITE_OK ) return rc;
  89161. i = 0;
  89162. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  89163. sqlite_int64 iStart = sqlite3_column_int64(s, 0);
  89164. sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
  89165. const char *pRootData = sqlite3_column_blob(s, 2);
  89166. int nRootData = sqlite3_column_bytes(s, 2);
  89167. assert( i<MERGE_COUNT );
  89168. rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
  89169. &pReaders[i]);
  89170. if( rc!=SQLITE_OK ) break;
  89171. i++;
  89172. }
  89173. if( rc!=SQLITE_DONE ){
  89174. while( i-->0 ){
  89175. leavesReaderDestroy(&pReaders[i]);
  89176. }
  89177. return rc;
  89178. }
  89179. *piReaders = i;
  89180. /* Leave our results sorted by term, then age. */
  89181. while( i-- ){
  89182. leavesReaderReorder(pReaders+i, *piReaders-i);
  89183. }
  89184. return SQLITE_OK;
  89185. }
  89186. /* Merge doclists from pReaders[nReaders] into a single doclist, which
  89187. ** is written to pWriter. Assumes pReaders is ordered oldest to
  89188. ** newest.
  89189. */
  89190. /* TODO(shess) Consider putting this inline in segmentMerge(). */
  89191. static int leavesReadersMerge(fulltext_vtab *v,
  89192. LeavesReader *pReaders, int nReaders,
  89193. LeafWriter *pWriter){
  89194. DLReader dlReaders[MERGE_COUNT];
  89195. const char *pTerm = leavesReaderTerm(pReaders);
  89196. int i, nTerm = leavesReaderTermBytes(pReaders);
  89197. assert( nReaders<=MERGE_COUNT );
  89198. for(i=0; i<nReaders; i++){
  89199. dlrInit(&dlReaders[i], DL_DEFAULT,
  89200. leavesReaderData(pReaders+i),
  89201. leavesReaderDataBytes(pReaders+i));
  89202. }
  89203. return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
  89204. }
  89205. /* Forward ref due to mutual recursion with segdirNextIndex(). */
  89206. static int segmentMerge(fulltext_vtab *v, int iLevel);
  89207. /* Put the next available index at iLevel into *pidx. If iLevel
  89208. ** already has MERGE_COUNT segments, they are merged to a higher
  89209. ** level to make room.
  89210. */
  89211. static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
  89212. int rc = segdir_max_index(v, iLevel, pidx);
  89213. if( rc==SQLITE_DONE ){ /* No segments at iLevel. */
  89214. *pidx = 0;
  89215. }else if( rc==SQLITE_ROW ){
  89216. if( *pidx==(MERGE_COUNT-1) ){
  89217. rc = segmentMerge(v, iLevel);
  89218. if( rc!=SQLITE_OK ) return rc;
  89219. *pidx = 0;
  89220. }else{
  89221. (*pidx)++;
  89222. }
  89223. }else{
  89224. return rc;
  89225. }
  89226. return SQLITE_OK;
  89227. }
  89228. /* Merge MERGE_COUNT segments at iLevel into a new segment at
  89229. ** iLevel+1. If iLevel+1 is already full of segments, those will be
  89230. ** merged to make room.
  89231. */
  89232. static int segmentMerge(fulltext_vtab *v, int iLevel){
  89233. LeafWriter writer;
  89234. LeavesReader lrs[MERGE_COUNT];
  89235. int i, rc, idx = 0;
  89236. /* Determine the next available segment index at the next level,
  89237. ** merging as necessary.
  89238. */
  89239. rc = segdirNextIndex(v, iLevel+1, &idx);
  89240. if( rc!=SQLITE_OK ) return rc;
  89241. /* TODO(shess) This assumes that we'll always see exactly
  89242. ** MERGE_COUNT segments to merge at a given level. That will be
  89243. ** broken if we allow the developer to request preemptive or
  89244. ** deferred merging.
  89245. */
  89246. memset(&lrs, '\0', sizeof(lrs));
  89247. rc = leavesReadersInit(v, iLevel, lrs, &i);
  89248. if( rc!=SQLITE_OK ) return rc;
  89249. assert( i==MERGE_COUNT );
  89250. leafWriterInit(iLevel+1, idx, &writer);
  89251. /* Since leavesReaderReorder() pushes readers at eof to the end,
  89252. ** when the first reader is empty, all will be empty.
  89253. */
  89254. while( !leavesReaderAtEnd(lrs) ){
  89255. /* Figure out how many readers share their next term. */
  89256. for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
  89257. if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
  89258. }
  89259. rc = leavesReadersMerge(v, lrs, i, &writer);
  89260. if( rc!=SQLITE_OK ) goto err;
  89261. /* Step forward those that were merged. */
  89262. while( i-->0 ){
  89263. rc = leavesReaderStep(v, lrs+i);
  89264. if( rc!=SQLITE_OK ) goto err;
  89265. /* Reorder by term, then by age. */
  89266. leavesReaderReorder(lrs+i, MERGE_COUNT-i);
  89267. }
  89268. }
  89269. for(i=0; i<MERGE_COUNT; i++){
  89270. leavesReaderDestroy(&lrs[i]);
  89271. }
  89272. rc = leafWriterFinalize(v, &writer);
  89273. leafWriterDestroy(&writer);
  89274. if( rc!=SQLITE_OK ) return rc;
  89275. /* Delete the merged segment data. */
  89276. return segdir_delete(v, iLevel);
  89277. err:
  89278. for(i=0; i<MERGE_COUNT; i++){
  89279. leavesReaderDestroy(&lrs[i]);
  89280. }
  89281. leafWriterDestroy(&writer);
  89282. return rc;
  89283. }
  89284. /* Accumulate the union of *acc and *pData into *acc. */
  89285. static void docListAccumulateUnion(DataBuffer *acc,
  89286. const char *pData, int nData) {
  89287. DataBuffer tmp = *acc;
  89288. dataBufferInit(acc, tmp.nData+nData);
  89289. docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
  89290. dataBufferDestroy(&tmp);
  89291. }
  89292. /* TODO(shess) It might be interesting to explore different merge
  89293. ** strategies, here. For instance, since this is a sorted merge, we
  89294. ** could easily merge many doclists in parallel. With some
  89295. ** comprehension of the storage format, we could merge all of the
  89296. ** doclists within a leaf node directly from the leaf node's storage.
  89297. ** It may be worthwhile to merge smaller doclists before larger
  89298. ** doclists, since they can be traversed more quickly - but the
  89299. ** results may have less overlap, making them more expensive in a
  89300. ** different way.
  89301. */
  89302. /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
  89303. ** *out (any doclists with duplicate docids overwrite those in *out).
  89304. ** Internal function for loadSegmentLeaf().
  89305. */
  89306. static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
  89307. const char *pTerm, int nTerm, int isPrefix,
  89308. DataBuffer *out){
  89309. /* doclist data is accumulated into pBuffers similar to how one does
  89310. ** increment in binary arithmetic. If index 0 is empty, the data is
  89311. ** stored there. If there is data there, it is merged and the
  89312. ** results carried into position 1, with further merge-and-carry
  89313. ** until an empty position is found.
  89314. */
  89315. DataBuffer *pBuffers = NULL;
  89316. int nBuffers = 0, nMaxBuffers = 0, rc;
  89317. assert( nTerm>0 );
  89318. for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
  89319. rc=leavesReaderStep(v, pReader)){
  89320. /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
  89321. ** already taken to compare the terms of two LeavesReaders. Think
  89322. ** on a better name. [Meanwhile, break encapsulation rather than
  89323. ** use a confusing name.]
  89324. */
  89325. int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
  89326. if( c>0 ) break; /* Past any possible matches. */
  89327. if( c==0 ){
  89328. const char *pData = leavesReaderData(pReader);
  89329. int iBuffer, nData = leavesReaderDataBytes(pReader);
  89330. /* Find the first empty buffer. */
  89331. for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
  89332. if( 0==pBuffers[iBuffer].nData ) break;
  89333. }
  89334. /* Out of buffers, add an empty one. */
  89335. if( iBuffer==nBuffers ){
  89336. if( nBuffers==nMaxBuffers ){
  89337. DataBuffer *p;
  89338. nMaxBuffers += 20;
  89339. /* Manual realloc so we can handle NULL appropriately. */
  89340. p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
  89341. if( p==NULL ){
  89342. rc = SQLITE_NOMEM;
  89343. break;
  89344. }
  89345. if( nBuffers>0 ){
  89346. assert(pBuffers!=NULL);
  89347. memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
  89348. sqlite3_free(pBuffers);
  89349. }
  89350. pBuffers = p;
  89351. }
  89352. dataBufferInit(&(pBuffers[nBuffers]), 0);
  89353. nBuffers++;
  89354. }
  89355. /* At this point, must have an empty at iBuffer. */
  89356. assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
  89357. /* If empty was first buffer, no need for merge logic. */
  89358. if( iBuffer==0 ){
  89359. dataBufferReplace(&(pBuffers[0]), pData, nData);
  89360. }else{
  89361. /* pAcc is the empty buffer the merged data will end up in. */
  89362. DataBuffer *pAcc = &(pBuffers[iBuffer]);
  89363. DataBuffer *p = &(pBuffers[0]);
  89364. /* Handle position 0 specially to avoid need to prime pAcc
  89365. ** with pData/nData.
  89366. */
  89367. dataBufferSwap(p, pAcc);
  89368. docListAccumulateUnion(pAcc, pData, nData);
  89369. /* Accumulate remaining doclists into pAcc. */
  89370. for(++p; p<pAcc; ++p){
  89371. docListAccumulateUnion(pAcc, p->pData, p->nData);
  89372. /* dataBufferReset() could allow a large doclist to blow up
  89373. ** our memory requirements.
  89374. */
  89375. if( p->nCapacity<1024 ){
  89376. dataBufferReset(p);
  89377. }else{
  89378. dataBufferDestroy(p);
  89379. dataBufferInit(p, 0);
  89380. }
  89381. }
  89382. }
  89383. }
  89384. }
  89385. /* Union all the doclists together into *out. */
  89386. /* TODO(shess) What if *out is big? Sigh. */
  89387. if( rc==SQLITE_OK && nBuffers>0 ){
  89388. int iBuffer;
  89389. for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
  89390. if( pBuffers[iBuffer].nData>0 ){
  89391. if( out->nData==0 ){
  89392. dataBufferSwap(out, &(pBuffers[iBuffer]));
  89393. }else{
  89394. docListAccumulateUnion(out, pBuffers[iBuffer].pData,
  89395. pBuffers[iBuffer].nData);
  89396. }
  89397. }
  89398. }
  89399. }
  89400. while( nBuffers-- ){
  89401. dataBufferDestroy(&(pBuffers[nBuffers]));
  89402. }
  89403. if( pBuffers!=NULL ) sqlite3_free(pBuffers);
  89404. return rc;
  89405. }
  89406. /* Call loadSegmentLeavesInt() with pData/nData as input. */
  89407. static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
  89408. const char *pTerm, int nTerm, int isPrefix,
  89409. DataBuffer *out){
  89410. LeavesReader reader;
  89411. int rc;
  89412. assert( nData>1 );
  89413. assert( *pData=='\0' );
  89414. rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
  89415. if( rc!=SQLITE_OK ) return rc;
  89416. rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
  89417. leavesReaderReset(&reader);
  89418. leavesReaderDestroy(&reader);
  89419. return rc;
  89420. }
  89421. /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
  89422. ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
  89423. ** out.
  89424. */
  89425. static int loadSegmentLeaves(fulltext_vtab *v,
  89426. sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
  89427. const char *pTerm, int nTerm, int isPrefix,
  89428. DataBuffer *out){
  89429. int rc;
  89430. LeavesReader reader;
  89431. assert( iStartLeaf<=iEndLeaf );
  89432. rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
  89433. if( rc!=SQLITE_OK ) return rc;
  89434. rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
  89435. leavesReaderReset(&reader);
  89436. leavesReaderDestroy(&reader);
  89437. return rc;
  89438. }
  89439. /* Taking pData/nData as an interior node, find the sequence of child
  89440. ** nodes which could include pTerm/nTerm/isPrefix. Note that the
  89441. ** interior node terms logically come between the blocks, so there is
  89442. ** one more blockid than there are terms (that block contains terms >=
  89443. ** the last interior-node term).
  89444. */
  89445. /* TODO(shess) The calling code may already know that the end child is
  89446. ** not worth calculating, because the end may be in a later sibling
  89447. ** node. Consider whether breaking symmetry is worthwhile. I suspect
  89448. ** it is not worthwhile.
  89449. */
  89450. static void getChildrenContaining(const char *pData, int nData,
  89451. const char *pTerm, int nTerm, int isPrefix,
  89452. sqlite_int64 *piStartChild,
  89453. sqlite_int64 *piEndChild){
  89454. InteriorReader reader;
  89455. assert( nData>1 );
  89456. assert( *pData!='\0' );
  89457. interiorReaderInit(pData, nData, &reader);
  89458. /* Scan for the first child which could contain pTerm/nTerm. */
  89459. while( !interiorReaderAtEnd(&reader) ){
  89460. if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
  89461. interiorReaderStep(&reader);
  89462. }
  89463. *piStartChild = interiorReaderCurrentBlockid(&reader);
  89464. /* Keep scanning to find a term greater than our term, using prefix
  89465. ** comparison if indicated. If isPrefix is false, this will be the
  89466. ** same blockid as the starting block.
  89467. */
  89468. while( !interiorReaderAtEnd(&reader) ){
  89469. if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
  89470. interiorReaderStep(&reader);
  89471. }
  89472. *piEndChild = interiorReaderCurrentBlockid(&reader);
  89473. interiorReaderDestroy(&reader);
  89474. /* Children must ascend, and if !prefix, both must be the same. */
  89475. assert( *piEndChild>=*piStartChild );
  89476. assert( isPrefix || *piStartChild==*piEndChild );
  89477. }
  89478. /* Read block at iBlockid and pass it with other params to
  89479. ** getChildrenContaining().
  89480. */
  89481. static int loadAndGetChildrenContaining(
  89482. fulltext_vtab *v,
  89483. sqlite_int64 iBlockid,
  89484. const char *pTerm, int nTerm, int isPrefix,
  89485. sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
  89486. ){
  89487. sqlite3_stmt *s = NULL;
  89488. int rc;
  89489. assert( iBlockid!=0 );
  89490. assert( pTerm!=NULL );
  89491. assert( nTerm!=0 ); /* TODO(shess) Why not allow this? */
  89492. assert( piStartChild!=NULL );
  89493. assert( piEndChild!=NULL );
  89494. rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
  89495. if( rc!=SQLITE_OK ) return rc;
  89496. rc = sqlite3_bind_int64(s, 1, iBlockid);
  89497. if( rc!=SQLITE_OK ) return rc;
  89498. rc = sqlite3_step(s);
  89499. if( rc==SQLITE_DONE ) return SQLITE_ERROR;
  89500. if( rc!=SQLITE_ROW ) return rc;
  89501. getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
  89502. pTerm, nTerm, isPrefix, piStartChild, piEndChild);
  89503. /* We expect only one row. We must execute another sqlite3_step()
  89504. * to complete the iteration; otherwise the table will remain
  89505. * locked. */
  89506. rc = sqlite3_step(s);
  89507. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  89508. if( rc!=SQLITE_DONE ) return rc;
  89509. return SQLITE_OK;
  89510. }
  89511. /* Traverse the tree represented by pData[nData] looking for
  89512. ** pTerm[nTerm], placing its doclist into *out. This is internal to
  89513. ** loadSegment() to make error-handling cleaner.
  89514. */
  89515. static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
  89516. sqlite_int64 iLeavesEnd,
  89517. const char *pTerm, int nTerm, int isPrefix,
  89518. DataBuffer *out){
  89519. /* Special case where root is a leaf. */
  89520. if( *pData=='\0' ){
  89521. return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
  89522. }else{
  89523. int rc;
  89524. sqlite_int64 iStartChild, iEndChild;
  89525. /* Process pData as an interior node, then loop down the tree
  89526. ** until we find the set of leaf nodes to scan for the term.
  89527. */
  89528. getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
  89529. &iStartChild, &iEndChild);
  89530. while( iStartChild>iLeavesEnd ){
  89531. sqlite_int64 iNextStart, iNextEnd;
  89532. rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
  89533. &iNextStart, &iNextEnd);
  89534. if( rc!=SQLITE_OK ) return rc;
  89535. /* If we've branched, follow the end branch, too. */
  89536. if( iStartChild!=iEndChild ){
  89537. sqlite_int64 iDummy;
  89538. rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
  89539. &iDummy, &iNextEnd);
  89540. if( rc!=SQLITE_OK ) return rc;
  89541. }
  89542. assert( iNextStart<=iNextEnd );
  89543. iStartChild = iNextStart;
  89544. iEndChild = iNextEnd;
  89545. }
  89546. assert( iStartChild<=iLeavesEnd );
  89547. assert( iEndChild<=iLeavesEnd );
  89548. /* Scan through the leaf segments for doclists. */
  89549. return loadSegmentLeaves(v, iStartChild, iEndChild,
  89550. pTerm, nTerm, isPrefix, out);
  89551. }
  89552. }
  89553. /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
  89554. ** merge its doclist over *out (any duplicate doclists read from the
  89555. ** segment rooted at pData will overwrite those in *out).
  89556. */
  89557. /* TODO(shess) Consider changing this to determine the depth of the
  89558. ** leaves using either the first characters of interior nodes (when
  89559. ** ==1, we're one level above the leaves), or the first character of
  89560. ** the root (which will describe the height of the tree directly).
  89561. ** Either feels somewhat tricky to me.
  89562. */
  89563. /* TODO(shess) The current merge is likely to be slow for large
  89564. ** doclists (though it should process from newest/smallest to
  89565. ** oldest/largest, so it may not be that bad). It might be useful to
  89566. ** modify things to allow for N-way merging. This could either be
  89567. ** within a segment, with pairwise merges across segments, or across
  89568. ** all segments at once.
  89569. */
  89570. static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
  89571. sqlite_int64 iLeavesEnd,
  89572. const char *pTerm, int nTerm, int isPrefix,
  89573. DataBuffer *out){
  89574. DataBuffer result;
  89575. int rc;
  89576. assert( nData>1 );
  89577. /* This code should never be called with buffered updates. */
  89578. assert( v->nPendingData<0 );
  89579. dataBufferInit(&result, 0);
  89580. rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
  89581. pTerm, nTerm, isPrefix, &result);
  89582. if( rc==SQLITE_OK && result.nData>0 ){
  89583. if( out->nData==0 ){
  89584. DataBuffer tmp = *out;
  89585. *out = result;
  89586. result = tmp;
  89587. }else{
  89588. DataBuffer merged;
  89589. DLReader readers[2];
  89590. dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
  89591. dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
  89592. dataBufferInit(&merged, out->nData+result.nData);
  89593. docListMerge(&merged, readers, 2);
  89594. dataBufferDestroy(out);
  89595. *out = merged;
  89596. dlrDestroy(&readers[0]);
  89597. dlrDestroy(&readers[1]);
  89598. }
  89599. }
  89600. dataBufferDestroy(&result);
  89601. return rc;
  89602. }
  89603. /* Scan the database and merge together the posting lists for the term
  89604. ** into *out.
  89605. */
  89606. static int termSelect(
  89607. fulltext_vtab *v,
  89608. int iColumn,
  89609. const char *pTerm, int nTerm, /* Term to query for */
  89610. int isPrefix, /* True for a prefix search */
  89611. DocListType iType,
  89612. DataBuffer *out /* Write results here */
  89613. ){
  89614. DataBuffer doclist;
  89615. sqlite3_stmt *s;
  89616. int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  89617. if( rc!=SQLITE_OK ) return rc;
  89618. /* This code should never be called with buffered updates. */
  89619. assert( v->nPendingData<0 );
  89620. dataBufferInit(&doclist, 0);
  89621. dataBufferInit(out, 0);
  89622. /* Traverse the segments from oldest to newest so that newer doclist
  89623. ** elements for given docids overwrite older elements.
  89624. */
  89625. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  89626. const char *pData = sqlite3_column_blob(s, 2);
  89627. const int nData = sqlite3_column_bytes(s, 2);
  89628. const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
  89629. rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
  89630. &doclist);
  89631. if( rc!=SQLITE_OK ) goto err;
  89632. }
  89633. if( rc==SQLITE_DONE ){
  89634. if( doclist.nData!=0 ){
  89635. /* TODO(shess) The old term_select_all() code applied the column
  89636. ** restrict as we merged segments, leading to smaller buffers.
  89637. ** This is probably worthwhile to bring back, once the new storage
  89638. ** system is checked in.
  89639. */
  89640. if( iColumn==v->nColumn) iColumn = -1;
  89641. docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
  89642. iColumn, iType, out);
  89643. }
  89644. rc = SQLITE_OK;
  89645. }
  89646. err:
  89647. dataBufferDestroy(&doclist);
  89648. return rc;
  89649. }
  89650. /****************************************************************/
  89651. /* Used to hold hashtable data for sorting. */
  89652. typedef struct TermData {
  89653. const char *pTerm;
  89654. int nTerm;
  89655. DLCollector *pCollector;
  89656. } TermData;
  89657. /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
  89658. ** for equal, >0 for greater-than).
  89659. */
  89660. static int termDataCmp(const void *av, const void *bv){
  89661. const TermData *a = (const TermData *)av;
  89662. const TermData *b = (const TermData *)bv;
  89663. int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
  89664. int c = memcmp(a->pTerm, b->pTerm, n);
  89665. if( c!=0 ) return c;
  89666. return a->nTerm-b->nTerm;
  89667. }
  89668. /* Order pTerms data by term, then write a new level 0 segment using
  89669. ** LeafWriter.
  89670. */
  89671. static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
  89672. fts3HashElem *e;
  89673. int idx, rc, i, n;
  89674. TermData *pData;
  89675. LeafWriter writer;
  89676. DataBuffer dl;
  89677. /* Determine the next index at level 0, merging as necessary. */
  89678. rc = segdirNextIndex(v, 0, &idx);
  89679. if( rc!=SQLITE_OK ) return rc;
  89680. n = fts3HashCount(pTerms);
  89681. pData = sqlite3_malloc(n*sizeof(TermData));
  89682. for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
  89683. assert( i<n );
  89684. pData[i].pTerm = fts3HashKey(e);
  89685. pData[i].nTerm = fts3HashKeysize(e);
  89686. pData[i].pCollector = fts3HashData(e);
  89687. }
  89688. assert( i==n );
  89689. /* TODO(shess) Should we allow user-defined collation sequences,
  89690. ** here? I think we only need that once we support prefix searches.
  89691. */
  89692. if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
  89693. /* TODO(shess) Refactor so that we can write directly to the segment
  89694. ** DataBuffer, as happens for segment merges.
  89695. */
  89696. leafWriterInit(0, idx, &writer);
  89697. dataBufferInit(&dl, 0);
  89698. for(i=0; i<n; i++){
  89699. dataBufferReset(&dl);
  89700. dlcAddDoclist(pData[i].pCollector, &dl);
  89701. rc = leafWriterStep(v, &writer,
  89702. pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
  89703. if( rc!=SQLITE_OK ) goto err;
  89704. }
  89705. rc = leafWriterFinalize(v, &writer);
  89706. err:
  89707. dataBufferDestroy(&dl);
  89708. sqlite3_free(pData);
  89709. leafWriterDestroy(&writer);
  89710. return rc;
  89711. }
  89712. /* If pendingTerms has data, free it. */
  89713. static int clearPendingTerms(fulltext_vtab *v){
  89714. if( v->nPendingData>=0 ){
  89715. fts3HashElem *e;
  89716. for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
  89717. dlcDelete(fts3HashData(e));
  89718. }
  89719. fts3HashClear(&v->pendingTerms);
  89720. v->nPendingData = -1;
  89721. }
  89722. return SQLITE_OK;
  89723. }
  89724. /* If pendingTerms has data, flush it to a level-zero segment, and
  89725. ** free it.
  89726. */
  89727. static int flushPendingTerms(fulltext_vtab *v){
  89728. if( v->nPendingData>=0 ){
  89729. int rc = writeZeroSegment(v, &v->pendingTerms);
  89730. if( rc==SQLITE_OK ) clearPendingTerms(v);
  89731. return rc;
  89732. }
  89733. return SQLITE_OK;
  89734. }
  89735. /* If pendingTerms is "too big", or docid is out of order, flush it.
  89736. ** Regardless, be certain that pendingTerms is initialized for use.
  89737. */
  89738. static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
  89739. /* TODO(shess) Explore whether partially flushing the buffer on
  89740. ** forced-flush would provide better performance. I suspect that if
  89741. ** we ordered the doclists by size and flushed the largest until the
  89742. ** buffer was half empty, that would let the less frequent terms
  89743. ** generate longer doclists.
  89744. */
  89745. if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
  89746. int rc = flushPendingTerms(v);
  89747. if( rc!=SQLITE_OK ) return rc;
  89748. }
  89749. if( v->nPendingData<0 ){
  89750. fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
  89751. v->nPendingData = 0;
  89752. }
  89753. v->iPrevDocid = iDocid;
  89754. return SQLITE_OK;
  89755. }
  89756. /* This function implements the xUpdate callback; it is the top-level entry
  89757. * point for inserting, deleting or updating a row in a full-text table. */
  89758. static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
  89759. sqlite_int64 *pRowid){
  89760. fulltext_vtab *v = (fulltext_vtab *) pVtab;
  89761. int rc;
  89762. FTSTRACE(("FTS3 Update %p\n", pVtab));
  89763. if( nArg<2 ){
  89764. rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
  89765. if( rc==SQLITE_OK ){
  89766. /* If we just deleted the last row in the table, clear out the
  89767. ** index data.
  89768. */
  89769. rc = content_exists(v);
  89770. if( rc==SQLITE_ROW ){
  89771. rc = SQLITE_OK;
  89772. }else if( rc==SQLITE_DONE ){
  89773. /* Clear the pending terms so we don't flush a useless level-0
  89774. ** segment when the transaction closes.
  89775. */
  89776. rc = clearPendingTerms(v);
  89777. if( rc==SQLITE_OK ){
  89778. rc = segdir_delete_all(v);
  89779. }
  89780. }
  89781. }
  89782. } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
  89783. /* An update:
  89784. * ppArg[0] = old rowid
  89785. * ppArg[1] = new rowid
  89786. * ppArg[2..2+v->nColumn-1] = values
  89787. * ppArg[2+v->nColumn] = value for magic column (we ignore this)
  89788. * ppArg[2+v->nColumn+1] = value for docid
  89789. */
  89790. sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
  89791. if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
  89792. sqlite3_value_int64(ppArg[1]) != rowid ){
  89793. rc = SQLITE_ERROR; /* we don't allow changing the rowid */
  89794. }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
  89795. sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
  89796. rc = SQLITE_ERROR; /* we don't allow changing the docid */
  89797. }else{
  89798. assert( nArg==2+v->nColumn+2);
  89799. rc = index_update(v, rowid, &ppArg[2]);
  89800. }
  89801. } else {
  89802. /* An insert:
  89803. * ppArg[1] = requested rowid
  89804. * ppArg[2..2+v->nColumn-1] = values
  89805. * ppArg[2+v->nColumn] = value for magic column (we ignore this)
  89806. * ppArg[2+v->nColumn+1] = value for docid
  89807. */
  89808. sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
  89809. assert( nArg==2+v->nColumn+2);
  89810. if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
  89811. SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
  89812. /* TODO(shess) Consider allowing this to work if the values are
  89813. ** identical. I'm inclined to discourage that usage, though,
  89814. ** given that both rowid and docid are special columns. Better
  89815. ** would be to define one or the other as the default winner,
  89816. ** but should it be fts3-centric (docid) or SQLite-centric
  89817. ** (rowid)?
  89818. */
  89819. rc = SQLITE_ERROR;
  89820. }else{
  89821. if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
  89822. pRequestDocid = ppArg[1];
  89823. }
  89824. rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
  89825. }
  89826. }
  89827. return rc;
  89828. }
  89829. static int fulltextSync(sqlite3_vtab *pVtab){
  89830. FTSTRACE(("FTS3 xSync()\n"));
  89831. return flushPendingTerms((fulltext_vtab *)pVtab);
  89832. }
  89833. static int fulltextBegin(sqlite3_vtab *pVtab){
  89834. fulltext_vtab *v = (fulltext_vtab *) pVtab;
  89835. FTSTRACE(("FTS3 xBegin()\n"));
  89836. /* Any buffered updates should have been cleared by the previous
  89837. ** transaction.
  89838. */
  89839. assert( v->nPendingData<0 );
  89840. return clearPendingTerms(v);
  89841. }
  89842. static int fulltextCommit(sqlite3_vtab *pVtab){
  89843. fulltext_vtab *v = (fulltext_vtab *) pVtab;
  89844. FTSTRACE(("FTS3 xCommit()\n"));
  89845. /* Buffered updates should have been cleared by fulltextSync(). */
  89846. assert( v->nPendingData<0 );
  89847. return clearPendingTerms(v);
  89848. }
  89849. static int fulltextRollback(sqlite3_vtab *pVtab){
  89850. FTSTRACE(("FTS3 xRollback()\n"));
  89851. return clearPendingTerms((fulltext_vtab *)pVtab);
  89852. }
  89853. /*
  89854. ** Implementation of the snippet() function for FTS3
  89855. */
  89856. static void snippetFunc(
  89857. sqlite3_context *pContext,
  89858. int argc,
  89859. sqlite3_value **argv
  89860. ){
  89861. fulltext_cursor *pCursor;
  89862. if( argc<1 ) return;
  89863. if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  89864. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  89865. sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
  89866. }else{
  89867. const char *zStart = "<b>";
  89868. const char *zEnd = "</b>";
  89869. const char *zEllipsis = "<b>...</b>";
  89870. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  89871. if( argc>=2 ){
  89872. zStart = (const char*)sqlite3_value_text(argv[1]);
  89873. if( argc>=3 ){
  89874. zEnd = (const char*)sqlite3_value_text(argv[2]);
  89875. if( argc>=4 ){
  89876. zEllipsis = (const char*)sqlite3_value_text(argv[3]);
  89877. }
  89878. }
  89879. }
  89880. snippetAllOffsets(pCursor);
  89881. snippetText(pCursor, zStart, zEnd, zEllipsis);
  89882. sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
  89883. pCursor->snippet.nSnippet, SQLITE_STATIC);
  89884. }
  89885. }
  89886. /*
  89887. ** Implementation of the offsets() function for FTS3
  89888. */
  89889. static void snippetOffsetsFunc(
  89890. sqlite3_context *pContext,
  89891. int argc,
  89892. sqlite3_value **argv
  89893. ){
  89894. fulltext_cursor *pCursor;
  89895. if( argc<1 ) return;
  89896. if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  89897. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  89898. sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
  89899. }else{
  89900. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  89901. snippetAllOffsets(pCursor);
  89902. snippetOffsetText(&pCursor->snippet);
  89903. sqlite3_result_text(pContext,
  89904. pCursor->snippet.zOffset, pCursor->snippet.nOffset,
  89905. SQLITE_STATIC);
  89906. }
  89907. }
  89908. /* OptLeavesReader is nearly identical to LeavesReader, except that
  89909. ** where LeavesReader is geared towards the merging of complete
  89910. ** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
  89911. ** is geared towards implementation of the optimize() function, and
  89912. ** can merge all segments simultaneously. This version may be
  89913. ** somewhat less efficient than LeavesReader because it merges into an
  89914. ** accumulator rather than doing an N-way merge, but since segment
  89915. ** size grows exponentially (so segment count logrithmically) this is
  89916. ** probably not an immediate problem.
  89917. */
  89918. /* TODO(shess): Prove that assertion, or extend the merge code to
  89919. ** merge tree fashion (like the prefix-searching code does).
  89920. */
  89921. /* TODO(shess): OptLeavesReader and LeavesReader could probably be
  89922. ** merged with little or no loss of performance for LeavesReader. The
  89923. ** merged code would need to handle >MERGE_COUNT segments, and would
  89924. ** also need to be able to optionally optimize away deletes.
  89925. */
  89926. typedef struct OptLeavesReader {
  89927. /* Segment number, to order readers by age. */
  89928. int segment;
  89929. LeavesReader reader;
  89930. } OptLeavesReader;
  89931. static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
  89932. return leavesReaderAtEnd(&pReader->reader);
  89933. }
  89934. static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
  89935. return leavesReaderTermBytes(&pReader->reader);
  89936. }
  89937. static const char *optLeavesReaderData(OptLeavesReader *pReader){
  89938. return leavesReaderData(&pReader->reader);
  89939. }
  89940. static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
  89941. return leavesReaderDataBytes(&pReader->reader);
  89942. }
  89943. static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
  89944. return leavesReaderTerm(&pReader->reader);
  89945. }
  89946. static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
  89947. return leavesReaderStep(v, &pReader->reader);
  89948. }
  89949. static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
  89950. return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
  89951. }
  89952. /* Order by term ascending, segment ascending (oldest to newest), with
  89953. ** exhausted readers to the end.
  89954. */
  89955. static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
  89956. int c = optLeavesReaderTermCmp(lr1, lr2);
  89957. if( c!=0 ) return c;
  89958. return lr1->segment-lr2->segment;
  89959. }
  89960. /* Bubble pLr[0] to appropriate place in pLr[1..nLr-1]. Assumes that
  89961. ** pLr[1..nLr-1] is already sorted.
  89962. */
  89963. static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
  89964. while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
  89965. OptLeavesReader tmp = pLr[0];
  89966. pLr[0] = pLr[1];
  89967. pLr[1] = tmp;
  89968. nLr--;
  89969. pLr++;
  89970. }
  89971. }
  89972. /* optimize() helper function. Put the readers in order and iterate
  89973. ** through them, merging doclists for matching terms into pWriter.
  89974. ** Returns SQLITE_OK on success, or the SQLite error code which
  89975. ** prevented success.
  89976. */
  89977. static int optimizeInternal(fulltext_vtab *v,
  89978. OptLeavesReader *readers, int nReaders,
  89979. LeafWriter *pWriter){
  89980. int i, rc = SQLITE_OK;
  89981. DataBuffer doclist, merged, tmp;
  89982. /* Order the readers. */
  89983. i = nReaders;
  89984. while( i-- > 0 ){
  89985. optLeavesReaderReorder(&readers[i], nReaders-i);
  89986. }
  89987. dataBufferInit(&doclist, LEAF_MAX);
  89988. dataBufferInit(&merged, LEAF_MAX);
  89989. /* Exhausted readers bubble to the end, so when the first reader is
  89990. ** at eof, all are at eof.
  89991. */
  89992. while( !optLeavesReaderAtEnd(&readers[0]) ){
  89993. /* Figure out how many readers share the next term. */
  89994. for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
  89995. if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
  89996. }
  89997. /* Special-case for no merge. */
  89998. if( i==1 ){
  89999. /* Trim deletions from the doclist. */
  90000. dataBufferReset(&merged);
  90001. docListTrim(DL_DEFAULT,
  90002. optLeavesReaderData(&readers[0]),
  90003. optLeavesReaderDataBytes(&readers[0]),
  90004. -1, DL_DEFAULT, &merged);
  90005. }else{
  90006. DLReader dlReaders[MERGE_COUNT];
  90007. int iReader, nReaders;
  90008. /* Prime the pipeline with the first reader's doclist. After
  90009. ** one pass index 0 will reference the accumulated doclist.
  90010. */
  90011. dlrInit(&dlReaders[0], DL_DEFAULT,
  90012. optLeavesReaderData(&readers[0]),
  90013. optLeavesReaderDataBytes(&readers[0]));
  90014. iReader = 1;
  90015. assert( iReader<i ); /* Must execute the loop at least once. */
  90016. while( iReader<i ){
  90017. /* Merge 16 inputs per pass. */
  90018. for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
  90019. iReader++, nReaders++ ){
  90020. dlrInit(&dlReaders[nReaders], DL_DEFAULT,
  90021. optLeavesReaderData(&readers[iReader]),
  90022. optLeavesReaderDataBytes(&readers[iReader]));
  90023. }
  90024. /* Merge doclists and swap result into accumulator. */
  90025. dataBufferReset(&merged);
  90026. docListMerge(&merged, dlReaders, nReaders);
  90027. tmp = merged;
  90028. merged = doclist;
  90029. doclist = tmp;
  90030. while( nReaders-- > 0 ){
  90031. dlrDestroy(&dlReaders[nReaders]);
  90032. }
  90033. /* Accumulated doclist to reader 0 for next pass. */
  90034. dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
  90035. }
  90036. /* Destroy reader that was left in the pipeline. */
  90037. dlrDestroy(&dlReaders[0]);
  90038. /* Trim deletions from the doclist. */
  90039. dataBufferReset(&merged);
  90040. docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
  90041. -1, DL_DEFAULT, &merged);
  90042. }
  90043. /* Only pass doclists with hits (skip if all hits deleted). */
  90044. if( merged.nData>0 ){
  90045. rc = leafWriterStep(v, pWriter,
  90046. optLeavesReaderTerm(&readers[0]),
  90047. optLeavesReaderTermBytes(&readers[0]),
  90048. merged.pData, merged.nData);
  90049. if( rc!=SQLITE_OK ) goto err;
  90050. }
  90051. /* Step merged readers to next term and reorder. */
  90052. while( i-- > 0 ){
  90053. rc = optLeavesReaderStep(v, &readers[i]);
  90054. if( rc!=SQLITE_OK ) goto err;
  90055. optLeavesReaderReorder(&readers[i], nReaders-i);
  90056. }
  90057. }
  90058. err:
  90059. dataBufferDestroy(&doclist);
  90060. dataBufferDestroy(&merged);
  90061. return rc;
  90062. }
  90063. /* Implement optimize() function for FTS3. optimize(t) merges all
  90064. ** segments in the fts index into a single segment. 't' is the magic
  90065. ** table-named column.
  90066. */
  90067. static void optimizeFunc(sqlite3_context *pContext,
  90068. int argc, sqlite3_value **argv){
  90069. fulltext_cursor *pCursor;
  90070. if( argc>1 ){
  90071. sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
  90072. }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  90073. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  90074. sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
  90075. }else{
  90076. fulltext_vtab *v;
  90077. int i, rc, iMaxLevel;
  90078. OptLeavesReader *readers;
  90079. int nReaders;
  90080. LeafWriter writer;
  90081. sqlite3_stmt *s;
  90082. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  90083. v = cursor_vtab(pCursor);
  90084. /* Flush any buffered updates before optimizing. */
  90085. rc = flushPendingTerms(v);
  90086. if( rc!=SQLITE_OK ) goto err;
  90087. rc = segdir_count(v, &nReaders, &iMaxLevel);
  90088. if( rc!=SQLITE_OK ) goto err;
  90089. if( nReaders==0 || nReaders==1 ){
  90090. sqlite3_result_text(pContext, "Index already optimal", -1,
  90091. SQLITE_STATIC);
  90092. return;
  90093. }
  90094. rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  90095. if( rc!=SQLITE_OK ) goto err;
  90096. readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
  90097. if( readers==NULL ) goto err;
  90098. /* Note that there will already be a segment at this position
  90099. ** until we call segdir_delete() on iMaxLevel.
  90100. */
  90101. leafWriterInit(iMaxLevel, 0, &writer);
  90102. i = 0;
  90103. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  90104. sqlite_int64 iStart = sqlite3_column_int64(s, 0);
  90105. sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
  90106. const char *pRootData = sqlite3_column_blob(s, 2);
  90107. int nRootData = sqlite3_column_bytes(s, 2);
  90108. assert( i<nReaders );
  90109. rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
  90110. &readers[i].reader);
  90111. if( rc!=SQLITE_OK ) break;
  90112. readers[i].segment = i;
  90113. i++;
  90114. }
  90115. /* If we managed to succesfully read them all, optimize them. */
  90116. if( rc==SQLITE_DONE ){
  90117. assert( i==nReaders );
  90118. rc = optimizeInternal(v, readers, nReaders, &writer);
  90119. }
  90120. while( i-- > 0 ){
  90121. leavesReaderDestroy(&readers[i].reader);
  90122. }
  90123. sqlite3_free(readers);
  90124. /* If we've successfully gotten to here, delete the old segments
  90125. ** and flush the interior structure of the new segment.
  90126. */
  90127. if( rc==SQLITE_OK ){
  90128. for( i=0; i<=iMaxLevel; i++ ){
  90129. rc = segdir_delete(v, i);
  90130. if( rc!=SQLITE_OK ) break;
  90131. }
  90132. if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
  90133. }
  90134. leafWriterDestroy(&writer);
  90135. if( rc!=SQLITE_OK ) goto err;
  90136. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  90137. return;
  90138. /* TODO(shess): Error-handling needs to be improved along the
  90139. ** lines of the dump_ functions.
  90140. */
  90141. err:
  90142. {
  90143. char buf[512];
  90144. sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
  90145. sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
  90146. sqlite3_result_error(pContext, buf, -1);
  90147. }
  90148. }
  90149. }
  90150. #ifdef SQLITE_TEST
  90151. /* Generate an error of the form "<prefix>: <msg>". If msg is NULL,
  90152. ** pull the error from the context's db handle.
  90153. */
  90154. static void generateError(sqlite3_context *pContext,
  90155. const char *prefix, const char *msg){
  90156. char buf[512];
  90157. if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
  90158. sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
  90159. sqlite3_result_error(pContext, buf, -1);
  90160. }
  90161. /* Helper function to collect the set of terms in the segment into
  90162. ** pTerms. The segment is defined by the leaf nodes between
  90163. ** iStartBlockid and iEndBlockid, inclusive, or by the contents of
  90164. ** pRootData if iStartBlockid is 0 (in which case the entire segment
  90165. ** fit in a leaf).
  90166. */
  90167. static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
  90168. fts3Hash *pTerms){
  90169. const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
  90170. const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
  90171. const char *pRootData = sqlite3_column_blob(s, 2);
  90172. const int nRootData = sqlite3_column_bytes(s, 2);
  90173. LeavesReader reader;
  90174. int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
  90175. pRootData, nRootData, &reader);
  90176. if( rc!=SQLITE_OK ) return rc;
  90177. while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
  90178. const char *pTerm = leavesReaderTerm(&reader);
  90179. const int nTerm = leavesReaderTermBytes(&reader);
  90180. void *oldValue = sqlite3Fts3HashFind(pTerms, pTerm, nTerm);
  90181. void *newValue = (void *)((char *)oldValue+1);
  90182. /* From the comment before sqlite3Fts3HashInsert in fts3_hash.c,
  90183. ** the data value passed is returned in case of malloc failure.
  90184. */
  90185. if( newValue==sqlite3Fts3HashInsert(pTerms, pTerm, nTerm, newValue) ){
  90186. rc = SQLITE_NOMEM;
  90187. }else{
  90188. rc = leavesReaderStep(v, &reader);
  90189. }
  90190. }
  90191. leavesReaderDestroy(&reader);
  90192. return rc;
  90193. }
  90194. /* Helper function to build the result string for dump_terms(). */
  90195. static int generateTermsResult(sqlite3_context *pContext, fts3Hash *pTerms){
  90196. int iTerm, nTerms, nResultBytes, iByte;
  90197. char *result;
  90198. TermData *pData;
  90199. fts3HashElem *e;
  90200. /* Iterate pTerms to generate an array of terms in pData for
  90201. ** sorting.
  90202. */
  90203. nTerms = fts3HashCount(pTerms);
  90204. assert( nTerms>0 );
  90205. pData = sqlite3_malloc(nTerms*sizeof(TermData));
  90206. if( pData==NULL ) return SQLITE_NOMEM;
  90207. nResultBytes = 0;
  90208. for(iTerm = 0, e = fts3HashFirst(pTerms); e; iTerm++, e = fts3HashNext(e)){
  90209. nResultBytes += fts3HashKeysize(e)+1; /* Term plus trailing space */
  90210. assert( iTerm<nTerms );
  90211. pData[iTerm].pTerm = fts3HashKey(e);
  90212. pData[iTerm].nTerm = fts3HashKeysize(e);
  90213. pData[iTerm].pCollector = fts3HashData(e); /* unused */
  90214. }
  90215. assert( iTerm==nTerms );
  90216. assert( nResultBytes>0 ); /* nTerms>0, nResultsBytes must be, too. */
  90217. result = sqlite3_malloc(nResultBytes);
  90218. if( result==NULL ){
  90219. sqlite3_free(pData);
  90220. return SQLITE_NOMEM;
  90221. }
  90222. if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);
  90223. /* Read the terms in order to build the result. */
  90224. iByte = 0;
  90225. for(iTerm=0; iTerm<nTerms; ++iTerm){
  90226. memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
  90227. iByte += pData[iTerm].nTerm;
  90228. result[iByte++] = ' ';
  90229. }
  90230. assert( iByte==nResultBytes );
  90231. assert( result[nResultBytes-1]==' ' );
  90232. result[nResultBytes-1] = '\0';
  90233. /* Passes away ownership of result. */
  90234. sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
  90235. sqlite3_free(pData);
  90236. return SQLITE_OK;
  90237. }
  90238. /* Implements dump_terms() for use in inspecting the fts3 index from
  90239. ** tests. TEXT result containing the ordered list of terms joined by
  90240. ** spaces. dump_terms(t, level, idx) dumps the terms for the segment
  90241. ** specified by level, idx (in %_segdir), while dump_terms(t) dumps
  90242. ** all terms in the index. In both cases t is the fts table's magic
  90243. ** table-named column.
  90244. */
  90245. static void dumpTermsFunc(
  90246. sqlite3_context *pContext,
  90247. int argc, sqlite3_value **argv
  90248. ){
  90249. fulltext_cursor *pCursor;
  90250. if( argc!=3 && argc!=1 ){
  90251. generateError(pContext, "dump_terms", "incorrect arguments");
  90252. }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  90253. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  90254. generateError(pContext, "dump_terms", "illegal first argument");
  90255. }else{
  90256. fulltext_vtab *v;
  90257. fts3Hash terms;
  90258. sqlite3_stmt *s = NULL;
  90259. int rc;
  90260. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  90261. v = cursor_vtab(pCursor);
  90262. /* If passed only the cursor column, get all segments. Otherwise
  90263. ** get the segment described by the following two arguments.
  90264. */
  90265. if( argc==1 ){
  90266. rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  90267. }else{
  90268. rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
  90269. if( rc==SQLITE_OK ){
  90270. rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
  90271. if( rc==SQLITE_OK ){
  90272. rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
  90273. }
  90274. }
  90275. }
  90276. if( rc!=SQLITE_OK ){
  90277. generateError(pContext, "dump_terms", NULL);
  90278. return;
  90279. }
  90280. /* Collect the terms for each segment. */
  90281. sqlite3Fts3HashInit(&terms, FTS3_HASH_STRING, 1);
  90282. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  90283. rc = collectSegmentTerms(v, s, &terms);
  90284. if( rc!=SQLITE_OK ) break;
  90285. }
  90286. if( rc!=SQLITE_DONE ){
  90287. sqlite3_reset(s);
  90288. generateError(pContext, "dump_terms", NULL);
  90289. }else{
  90290. const int nTerms = fts3HashCount(&terms);
  90291. if( nTerms>0 ){
  90292. rc = generateTermsResult(pContext, &terms);
  90293. if( rc==SQLITE_NOMEM ){
  90294. generateError(pContext, "dump_terms", "out of memory");
  90295. }else{
  90296. assert( rc==SQLITE_OK );
  90297. }
  90298. }else if( argc==3 ){
  90299. /* The specific segment asked for could not be found. */
  90300. generateError(pContext, "dump_terms", "segment not found");
  90301. }else{
  90302. /* No segments found. */
  90303. /* TODO(shess): It should be impossible to reach this. This
  90304. ** case can only happen for an empty table, in which case
  90305. ** SQLite has no rows to call this function on.
  90306. */
  90307. sqlite3_result_null(pContext);
  90308. }
  90309. }
  90310. sqlite3Fts3HashClear(&terms);
  90311. }
  90312. }
  90313. /* Expand the DL_DEFAULT doclist in pData into a text result in
  90314. ** pContext.
  90315. */
  90316. static void createDoclistResult(sqlite3_context *pContext,
  90317. const char *pData, int nData){
  90318. DataBuffer dump;
  90319. DLReader dlReader;
  90320. assert( pData!=NULL && nData>0 );
  90321. dataBufferInit(&dump, 0);
  90322. dlrInit(&dlReader, DL_DEFAULT, pData, nData);
  90323. for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
  90324. char buf[256];
  90325. PLReader plReader;
  90326. plrInit(&plReader, &dlReader);
  90327. if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
  90328. sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
  90329. dataBufferAppend(&dump, buf, strlen(buf));
  90330. }else{
  90331. int iColumn = plrColumn(&plReader);
  90332. sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
  90333. dlrDocid(&dlReader), iColumn);
  90334. dataBufferAppend(&dump, buf, strlen(buf));
  90335. for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
  90336. if( plrColumn(&plReader)!=iColumn ){
  90337. iColumn = plrColumn(&plReader);
  90338. sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
  90339. assert( dump.nData>0 );
  90340. dump.nData--; /* Overwrite trailing space. */
  90341. assert( dump.pData[dump.nData]==' ');
  90342. dataBufferAppend(&dump, buf, strlen(buf));
  90343. }
  90344. if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
  90345. sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
  90346. plrPosition(&plReader),
  90347. plrStartOffset(&plReader), plrEndOffset(&plReader));
  90348. }else if( DL_DEFAULT==DL_POSITIONS ){
  90349. sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
  90350. }else{
  90351. assert( NULL=="Unhandled DL_DEFAULT value");
  90352. }
  90353. dataBufferAppend(&dump, buf, strlen(buf));
  90354. }
  90355. plrDestroy(&plReader);
  90356. assert( dump.nData>0 );
  90357. dump.nData--; /* Overwrite trailing space. */
  90358. assert( dump.pData[dump.nData]==' ');
  90359. dataBufferAppend(&dump, "]] ", 3);
  90360. }
  90361. }
  90362. dlrDestroy(&dlReader);
  90363. assert( dump.nData>0 );
  90364. dump.nData--; /* Overwrite trailing space. */
  90365. assert( dump.pData[dump.nData]==' ');
  90366. dump.pData[dump.nData] = '\0';
  90367. assert( dump.nData>0 );
  90368. /* Passes ownership of dump's buffer to pContext. */
  90369. sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
  90370. dump.pData = NULL;
  90371. dump.nData = dump.nCapacity = 0;
  90372. }
  90373. /* Implements dump_doclist() for use in inspecting the fts3 index from
  90374. ** tests. TEXT result containing a string representation of the
  90375. ** doclist for the indicated term. dump_doclist(t, term, level, idx)
  90376. ** dumps the doclist for term from the segment specified by level, idx
  90377. ** (in %_segdir), while dump_doclist(t, term) dumps the logical
  90378. ** doclist for the term across all segments. The per-segment doclist
  90379. ** can contain deletions, while the full-index doclist will not
  90380. ** (deletions are omitted).
  90381. **
  90382. ** Result formats differ with the setting of DL_DEFAULTS. Examples:
  90383. **
  90384. ** DL_DOCIDS: [1] [3] [7]
  90385. ** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
  90386. ** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
  90387. **
  90388. ** In each case the number after the outer '[' is the docid. In the
  90389. ** latter two cases, the number before the inner '[' is the column
  90390. ** associated with the values within. For DL_POSITIONS the numbers
  90391. ** within are the positions, for DL_POSITIONS_OFFSETS they are the
  90392. ** position, the start offset, and the end offset.
  90393. */
  90394. static void dumpDoclistFunc(
  90395. sqlite3_context *pContext,
  90396. int argc, sqlite3_value **argv
  90397. ){
  90398. fulltext_cursor *pCursor;
  90399. if( argc!=2 && argc!=4 ){
  90400. generateError(pContext, "dump_doclist", "incorrect arguments");
  90401. }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  90402. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  90403. generateError(pContext, "dump_doclist", "illegal first argument");
  90404. }else if( sqlite3_value_text(argv[1])==NULL ||
  90405. sqlite3_value_text(argv[1])[0]=='\0' ){
  90406. generateError(pContext, "dump_doclist", "empty second argument");
  90407. }else{
  90408. const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
  90409. const int nTerm = strlen(pTerm);
  90410. fulltext_vtab *v;
  90411. int rc;
  90412. DataBuffer doclist;
  90413. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  90414. v = cursor_vtab(pCursor);
  90415. dataBufferInit(&doclist, 0);
  90416. /* termSelect() yields the same logical doclist that queries are
  90417. ** run against.
  90418. */
  90419. if( argc==2 ){
  90420. rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
  90421. }else{
  90422. sqlite3_stmt *s = NULL;
  90423. /* Get our specific segment's information. */
  90424. rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
  90425. if( rc==SQLITE_OK ){
  90426. rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
  90427. if( rc==SQLITE_OK ){
  90428. rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
  90429. }
  90430. }
  90431. if( rc==SQLITE_OK ){
  90432. rc = sqlite3_step(s);
  90433. if( rc==SQLITE_DONE ){
  90434. dataBufferDestroy(&doclist);
  90435. generateError(pContext, "dump_doclist", "segment not found");
  90436. return;
  90437. }
  90438. /* Found a segment, load it into doclist. */
  90439. if( rc==SQLITE_ROW ){
  90440. const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
  90441. const char *pData = sqlite3_column_blob(s, 2);
  90442. const int nData = sqlite3_column_bytes(s, 2);
  90443. /* loadSegment() is used by termSelect() to load each
  90444. ** segment's data.
  90445. */
  90446. rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
  90447. &doclist);
  90448. if( rc==SQLITE_OK ){
  90449. rc = sqlite3_step(s);
  90450. /* Should not have more than one matching segment. */
  90451. if( rc!=SQLITE_DONE ){
  90452. sqlite3_reset(s);
  90453. dataBufferDestroy(&doclist);
  90454. generateError(pContext, "dump_doclist", "invalid segdir");
  90455. return;
  90456. }
  90457. rc = SQLITE_OK;
  90458. }
  90459. }
  90460. }
  90461. sqlite3_reset(s);
  90462. }
  90463. if( rc==SQLITE_OK ){
  90464. if( doclist.nData>0 ){
  90465. createDoclistResult(pContext, doclist.pData, doclist.nData);
  90466. }else{
  90467. /* TODO(shess): This can happen if the term is not present, or
  90468. ** if all instances of the term have been deleted and this is
  90469. ** an all-index dump. It may be interesting to distinguish
  90470. ** these cases.
  90471. */
  90472. sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
  90473. }
  90474. }else if( rc==SQLITE_NOMEM ){
  90475. /* Handle out-of-memory cases specially because if they are
  90476. ** generated in fts3 code they may not be reflected in the db
  90477. ** handle.
  90478. */
  90479. /* TODO(shess): Handle this more comprehensively.
  90480. ** sqlite3ErrStr() has what I need, but is internal.
  90481. */
  90482. generateError(pContext, "dump_doclist", "out of memory");
  90483. }else{
  90484. generateError(pContext, "dump_doclist", NULL);
  90485. }
  90486. dataBufferDestroy(&doclist);
  90487. }
  90488. }
  90489. #endif
  90490. /*
  90491. ** This routine implements the xFindFunction method for the FTS3
  90492. ** virtual table.
  90493. */
  90494. static int fulltextFindFunction(
  90495. sqlite3_vtab *pVtab,
  90496. int nArg,
  90497. const char *zName,
  90498. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  90499. void **ppArg
  90500. ){
  90501. if( strcmp(zName,"snippet")==0 ){
  90502. *pxFunc = snippetFunc;
  90503. return 1;
  90504. }else if( strcmp(zName,"offsets")==0 ){
  90505. *pxFunc = snippetOffsetsFunc;
  90506. return 1;
  90507. }else if( strcmp(zName,"optimize")==0 ){
  90508. *pxFunc = optimizeFunc;
  90509. return 1;
  90510. #ifdef SQLITE_TEST
  90511. /* NOTE(shess): These functions are present only for testing
  90512. ** purposes. No particular effort is made to optimize their
  90513. ** execution or how they build their results.
  90514. */
  90515. }else if( strcmp(zName,"dump_terms")==0 ){
  90516. /* fprintf(stderr, "Found dump_terms\n"); */
  90517. *pxFunc = dumpTermsFunc;
  90518. return 1;
  90519. }else if( strcmp(zName,"dump_doclist")==0 ){
  90520. /* fprintf(stderr, "Found dump_doclist\n"); */
  90521. *pxFunc = dumpDoclistFunc;
  90522. return 1;
  90523. #endif
  90524. }
  90525. return 0;
  90526. }
  90527. /*
  90528. ** Rename an fts3 table.
  90529. */
  90530. static int fulltextRename(
  90531. sqlite3_vtab *pVtab,
  90532. const char *zName
  90533. ){
  90534. fulltext_vtab *p = (fulltext_vtab *)pVtab;
  90535. int rc = SQLITE_NOMEM;
  90536. char *zSql = sqlite3_mprintf(
  90537. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';"
  90538. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
  90539. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';"
  90540. , p->zDb, p->zName, zName
  90541. , p->zDb, p->zName, zName
  90542. , p->zDb, p->zName, zName
  90543. );
  90544. if( zSql ){
  90545. rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
  90546. sqlite3_free(zSql);
  90547. }
  90548. return rc;
  90549. }
  90550. static const sqlite3_module fts3Module = {
  90551. /* iVersion */ 0,
  90552. /* xCreate */ fulltextCreate,
  90553. /* xConnect */ fulltextConnect,
  90554. /* xBestIndex */ fulltextBestIndex,
  90555. /* xDisconnect */ fulltextDisconnect,
  90556. /* xDestroy */ fulltextDestroy,
  90557. /* xOpen */ fulltextOpen,
  90558. /* xClose */ fulltextClose,
  90559. /* xFilter */ fulltextFilter,
  90560. /* xNext */ fulltextNext,
  90561. /* xEof */ fulltextEof,
  90562. /* xColumn */ fulltextColumn,
  90563. /* xRowid */ fulltextRowid,
  90564. /* xUpdate */ fulltextUpdate,
  90565. /* xBegin */ fulltextBegin,
  90566. /* xSync */ fulltextSync,
  90567. /* xCommit */ fulltextCommit,
  90568. /* xRollback */ fulltextRollback,
  90569. /* xFindFunction */ fulltextFindFunction,
  90570. /* xRename */ fulltextRename,
  90571. };
  90572. static void hashDestroy(void *p){
  90573. fts3Hash *pHash = (fts3Hash *)p;
  90574. sqlite3Fts3HashClear(pHash);
  90575. sqlite3_free(pHash);
  90576. }
  90577. /*
  90578. ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
  90579. ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
  90580. ** two forward declarations are for functions declared in these files
  90581. ** used to retrieve the respective implementations.
  90582. **
  90583. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  90584. ** to by the argument to point a the "simple" tokenizer implementation.
  90585. ** Function ...PorterTokenizerModule() sets *pModule to point to the
  90586. ** porter tokenizer/stemmer implementation.
  90587. */
  90588. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  90589. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  90590. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  90591. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
  90592. /*
  90593. ** Initialise the fts3 extension. If this extension is built as part
  90594. ** of the sqlite library, then this function is called directly by
  90595. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  90596. ** function is called by the sqlite3_extension_init() entry point.
  90597. */
  90598. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  90599. int rc = SQLITE_OK;
  90600. fts3Hash *pHash = 0;
  90601. const sqlite3_tokenizer_module *pSimple = 0;
  90602. const sqlite3_tokenizer_module *pPorter = 0;
  90603. const sqlite3_tokenizer_module *pIcu = 0;
  90604. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  90605. sqlite3Fts3PorterTokenizerModule(&pPorter);
  90606. #ifdef SQLITE_ENABLE_ICU
  90607. sqlite3Fts3IcuTokenizerModule(&pIcu);
  90608. #endif
  90609. /* Allocate and initialise the hash-table used to store tokenizers. */
  90610. pHash = sqlite3_malloc(sizeof(fts3Hash));
  90611. if( !pHash ){
  90612. rc = SQLITE_NOMEM;
  90613. }else{
  90614. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  90615. }
  90616. /* Load the built-in tokenizers into the hash table */
  90617. if( rc==SQLITE_OK ){
  90618. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  90619. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  90620. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  90621. ){
  90622. rc = SQLITE_NOMEM;
  90623. }
  90624. }
  90625. #ifdef SQLITE_TEST
  90626. sqlite3Fts3ExprInitTestInterface(db);
  90627. #endif
  90628. /* Create the virtual table wrapper around the hash-table and overload
  90629. ** the two scalar functions. If this is successful, register the
  90630. ** module with sqlite.
  90631. */
  90632. if( SQLITE_OK==rc
  90633. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  90634. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  90635. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
  90636. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
  90637. #ifdef SQLITE_TEST
  90638. && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
  90639. && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
  90640. #endif
  90641. ){
  90642. return sqlite3_create_module_v2(
  90643. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  90644. );
  90645. }
  90646. /* An error has occured. Delete the hash table and return the error code. */
  90647. assert( rc!=SQLITE_OK );
  90648. if( pHash ){
  90649. sqlite3Fts3HashClear(pHash);
  90650. sqlite3_free(pHash);
  90651. }
  90652. return rc;
  90653. }
  90654. #if !SQLITE_CORE
  90655. SQLITE_API int sqlite3_extension_init(
  90656. sqlite3 *db,
  90657. char **pzErrMsg,
  90658. const sqlite3_api_routines *pApi
  90659. ){
  90660. SQLITE_EXTENSION_INIT2(pApi)
  90661. return sqlite3Fts3Init(db);
  90662. }
  90663. #endif
  90664. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  90665. /************** End of fts3.c ************************************************/
  90666. /************** Begin file fts3_expr.c ***************************************/
  90667. /*
  90668. ** 2008 Nov 28
  90669. **
  90670. ** The author disclaims copyright to this source code. In place of
  90671. ** a legal notice, here is a blessing:
  90672. **
  90673. ** May you do good and not evil.
  90674. ** May you find forgiveness for yourself and forgive others.
  90675. ** May you share freely, never taking more than you give.
  90676. **
  90677. ******************************************************************************
  90678. **
  90679. ** This module contains code that implements a parser for fts3 query strings
  90680. ** (the right-hand argument to the MATCH operator). Because the supported
  90681. ** syntax is relatively simple, the whole tokenizer/parser system is
  90682. ** hand-coded. The public interface to this module is declared in source
  90683. ** code file "fts3_expr.h".
  90684. */
  90685. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  90686. /*
  90687. ** By default, this module parses the legacy syntax that has been
  90688. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  90689. ** is defined, then it uses the new syntax. The differences between
  90690. ** the new and the old syntaxes are:
  90691. **
  90692. ** a) The new syntax supports parenthesis. The old does not.
  90693. **
  90694. ** b) The new syntax supports the AND and NOT operators. The old does not.
  90695. **
  90696. ** c) The old syntax supports the "-" token qualifier. This is not
  90697. ** supported by the new syntax (it is replaced by the NOT operator).
  90698. **
  90699. ** d) When using the old syntax, the OR operator has a greater precedence
  90700. ** than an implicit AND. When using the new, both implicity and explicit
  90701. ** AND operators have a higher precedence than OR.
  90702. **
  90703. ** If compiled with SQLITE_TEST defined, then this module exports the
  90704. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  90705. ** to zero causes the module to use the old syntax. If it is set to
  90706. ** non-zero the new syntax is activated. This is so both syntaxes can
  90707. ** be tested using a single build of testfixture.
  90708. */
  90709. #ifdef SQLITE_TEST
  90710. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  90711. #else
  90712. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  90713. # define sqlite3_fts3_enable_parentheses 1
  90714. # else
  90715. # define sqlite3_fts3_enable_parentheses 0
  90716. # endif
  90717. #endif
  90718. /*
  90719. ** Default span for NEAR operators.
  90720. */
  90721. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  90722. typedef struct ParseContext ParseContext;
  90723. struct ParseContext {
  90724. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  90725. const char **azCol; /* Array of column names for fts3 table */
  90726. int nCol; /* Number of entries in azCol[] */
  90727. int iDefaultCol; /* Default column to query */
  90728. sqlite3_context *pCtx; /* Write error message here */
  90729. int nNest; /* Number of nested brackets */
  90730. };
  90731. /*
  90732. ** This function is equivalent to the standard isspace() function.
  90733. **
  90734. ** The standard isspace() can be awkward to use safely, because although it
  90735. ** is defined to accept an argument of type int, its behaviour when passed
  90736. ** an integer that falls outside of the range of the unsigned char type
  90737. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  90738. ** is defined to accept an argument of type char, and always returns 0 for
  90739. ** any values that fall outside of the range of the unsigned char type (i.e.
  90740. ** negative values).
  90741. */
  90742. static int fts3isspace(char c){
  90743. return (c&0x80)==0 ? isspace(c) : 0;
  90744. }
  90745. /*
  90746. ** Extract the next token from buffer z (length n) using the tokenizer
  90747. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  90748. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  90749. ** single token and set *ppExpr to point to it. If the end of the buffer is
  90750. ** reached before a token is found, set *ppExpr to zero. It is the
  90751. ** responsibility of the caller to eventually deallocate the allocated
  90752. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  90753. **
  90754. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  90755. ** fails.
  90756. */
  90757. static int getNextToken(
  90758. ParseContext *pParse, /* fts3 query parse context */
  90759. int iCol, /* Value for Fts3Phrase.iColumn */
  90760. const char *z, int n, /* Input string */
  90761. Fts3Expr **ppExpr, /* OUT: expression */
  90762. int *pnConsumed /* OUT: Number of bytes consumed */
  90763. ){
  90764. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  90765. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  90766. int rc;
  90767. sqlite3_tokenizer_cursor *pCursor;
  90768. Fts3Expr *pRet = 0;
  90769. int nConsumed = 0;
  90770. rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
  90771. if( rc==SQLITE_OK ){
  90772. const char *zToken;
  90773. int nToken, iStart, iEnd, iPosition;
  90774. int nByte; /* total space to allocate */
  90775. pCursor->pTokenizer = pTokenizer;
  90776. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  90777. if( rc==SQLITE_OK ){
  90778. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  90779. pRet = (Fts3Expr *)sqlite3_malloc(nByte);
  90780. if( !pRet ){
  90781. rc = SQLITE_NOMEM;
  90782. }else{
  90783. memset(pRet, 0, nByte);
  90784. pRet->eType = FTSQUERY_PHRASE;
  90785. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  90786. pRet->pPhrase->nToken = 1;
  90787. pRet->pPhrase->iColumn = iCol;
  90788. pRet->pPhrase->aToken[0].n = nToken;
  90789. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  90790. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  90791. if( iEnd<n && z[iEnd]=='*' ){
  90792. pRet->pPhrase->aToken[0].isPrefix = 1;
  90793. iEnd++;
  90794. }
  90795. if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
  90796. pRet->pPhrase->isNot = 1;
  90797. }
  90798. }
  90799. }
  90800. nConsumed = iEnd;
  90801. pModule->xClose(pCursor);
  90802. }
  90803. *pnConsumed = nConsumed;
  90804. *ppExpr = pRet;
  90805. return rc;
  90806. }
  90807. /*
  90808. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  90809. ** then free the old allocation.
  90810. */
  90811. void *fts3ReallocOrFree(void *pOrig, int nNew){
  90812. void *pRet = sqlite3_realloc(pOrig, nNew);
  90813. if( !pRet ){
  90814. sqlite3_free(pOrig);
  90815. }
  90816. return pRet;
  90817. }
  90818. /*
  90819. ** Buffer zInput, length nInput, contains the contents of a quoted string
  90820. ** that appeared as part of an fts3 query expression. Neither quote character
  90821. ** is included in the buffer. This function attempts to tokenize the entire
  90822. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  90823. ** containing the results.
  90824. **
  90825. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  90826. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  90827. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  90828. ** to 0.
  90829. */
  90830. static int getNextString(
  90831. ParseContext *pParse, /* fts3 query parse context */
  90832. const char *zInput, int nInput, /* Input string */
  90833. Fts3Expr **ppExpr /* OUT: expression */
  90834. ){
  90835. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  90836. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  90837. int rc;
  90838. Fts3Expr *p = 0;
  90839. sqlite3_tokenizer_cursor *pCursor = 0;
  90840. char *zTemp = 0;
  90841. int nTemp = 0;
  90842. rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
  90843. if( rc==SQLITE_OK ){
  90844. int ii;
  90845. pCursor->pTokenizer = pTokenizer;
  90846. for(ii=0; rc==SQLITE_OK; ii++){
  90847. const char *zToken;
  90848. int nToken, iBegin, iEnd, iPos;
  90849. rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
  90850. if( rc==SQLITE_OK ){
  90851. int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  90852. p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
  90853. zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
  90854. if( !p || !zTemp ){
  90855. goto no_mem;
  90856. }
  90857. if( ii==0 ){
  90858. memset(p, 0, nByte);
  90859. p->pPhrase = (Fts3Phrase *)&p[1];
  90860. p->eType = FTSQUERY_PHRASE;
  90861. p->pPhrase->iColumn = pParse->iDefaultCol;
  90862. }
  90863. p->pPhrase = (Fts3Phrase *)&p[1];
  90864. p->pPhrase->nToken = ii+1;
  90865. p->pPhrase->aToken[ii].n = nToken;
  90866. memcpy(&zTemp[nTemp], zToken, nToken);
  90867. nTemp += nToken;
  90868. if( iEnd<nInput && zInput[iEnd]=='*' ){
  90869. p->pPhrase->aToken[ii].isPrefix = 1;
  90870. }else{
  90871. p->pPhrase->aToken[ii].isPrefix = 0;
  90872. }
  90873. }
  90874. }
  90875. pModule->xClose(pCursor);
  90876. pCursor = 0;
  90877. }
  90878. if( rc==SQLITE_DONE ){
  90879. int jj;
  90880. char *zNew;
  90881. int nNew = 0;
  90882. int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  90883. nByte += (p->pPhrase->nToken-1) * sizeof(struct PhraseToken);
  90884. p = fts3ReallocOrFree(p, nByte + nTemp);
  90885. if( !p ){
  90886. goto no_mem;
  90887. }
  90888. p->pPhrase = (Fts3Phrase *)&p[1];
  90889. zNew = &(((char *)p)[nByte]);
  90890. memcpy(zNew, zTemp, nTemp);
  90891. for(jj=0; jj<p->pPhrase->nToken; jj++){
  90892. p->pPhrase->aToken[jj].z = &zNew[nNew];
  90893. nNew += p->pPhrase->aToken[jj].n;
  90894. }
  90895. sqlite3_free(zTemp);
  90896. rc = SQLITE_OK;
  90897. }
  90898. *ppExpr = p;
  90899. return rc;
  90900. no_mem:
  90901. if( pCursor ){
  90902. pModule->xClose(pCursor);
  90903. }
  90904. sqlite3_free(zTemp);
  90905. sqlite3_free(p);
  90906. *ppExpr = 0;
  90907. return SQLITE_NOMEM;
  90908. }
  90909. /*
  90910. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  90911. ** call fts3ExprParse(). So this forward declaration is required.
  90912. */
  90913. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  90914. /*
  90915. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  90916. ** structure, or set to 0 if the end of the input buffer is reached.
  90917. **
  90918. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  90919. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  90920. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  90921. */
  90922. static int getNextNode(
  90923. ParseContext *pParse, /* fts3 query parse context */
  90924. const char *z, int n, /* Input string */
  90925. Fts3Expr **ppExpr, /* OUT: expression */
  90926. int *pnConsumed /* OUT: Number of bytes consumed */
  90927. ){
  90928. static const struct Fts3Keyword {
  90929. char z[4]; /* Keyword text */
  90930. unsigned char n; /* Length of the keyword */
  90931. unsigned char parenOnly; /* Only valid in paren mode */
  90932. unsigned char eType; /* Keyword code */
  90933. } aKeyword[] = {
  90934. { "OR" , 2, 0, FTSQUERY_OR },
  90935. { "AND", 3, 1, FTSQUERY_AND },
  90936. { "NOT", 3, 1, FTSQUERY_NOT },
  90937. { "NEAR", 4, 0, FTSQUERY_NEAR }
  90938. };
  90939. int ii;
  90940. int iCol;
  90941. int iColLen;
  90942. int rc;
  90943. Fts3Expr *pRet = 0;
  90944. const char *zInput = z;
  90945. int nInput = n;
  90946. /* Skip over any whitespace before checking for a keyword, an open or
  90947. ** close bracket, or a quoted string.
  90948. */
  90949. while( nInput>0 && fts3isspace(*zInput) ){
  90950. nInput--;
  90951. zInput++;
  90952. }
  90953. if( nInput==0 ){
  90954. return SQLITE_DONE;
  90955. }
  90956. /* See if we are dealing with a keyword. */
  90957. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  90958. const struct Fts3Keyword *pKey = &aKeyword[ii];
  90959. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  90960. continue;
  90961. }
  90962. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  90963. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  90964. int nKey = pKey->n;
  90965. char cNext;
  90966. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  90967. if( pKey->eType==FTSQUERY_NEAR ){
  90968. assert( nKey==4 );
  90969. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  90970. nNear = 0;
  90971. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  90972. nNear = nNear * 10 + (zInput[nKey] - '0');
  90973. }
  90974. }
  90975. }
  90976. /* At this point this is probably a keyword. But for that to be true,
  90977. ** the next byte must contain either whitespace, an open or close
  90978. ** parenthesis, a quote character, or EOF.
  90979. */
  90980. cNext = zInput[nKey];
  90981. if( fts3isspace(cNext)
  90982. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  90983. ){
  90984. pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
  90985. memset(pRet, 0, sizeof(Fts3Expr));
  90986. pRet->eType = pKey->eType;
  90987. pRet->nNear = nNear;
  90988. *ppExpr = pRet;
  90989. *pnConsumed = (zInput - z) + nKey;
  90990. return SQLITE_OK;
  90991. }
  90992. /* Turns out that wasn't a keyword after all. This happens if the
  90993. ** user has supplied a token such as "ORacle". Continue.
  90994. */
  90995. }
  90996. }
  90997. /* Check for an open bracket. */
  90998. if( sqlite3_fts3_enable_parentheses ){
  90999. if( *zInput=='(' ){
  91000. int nConsumed;
  91001. int rc;
  91002. pParse->nNest++;
  91003. rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
  91004. if( rc==SQLITE_OK && !*ppExpr ){
  91005. rc = SQLITE_DONE;
  91006. }
  91007. *pnConsumed = (zInput - z) + 1 + nConsumed;
  91008. return rc;
  91009. }
  91010. /* Check for a close bracket. */
  91011. if( *zInput==')' ){
  91012. pParse->nNest--;
  91013. *pnConsumed = (zInput - z) + 1;
  91014. return SQLITE_DONE;
  91015. }
  91016. }
  91017. /* See if we are dealing with a quoted phrase. If this is the case, then
  91018. ** search for the closing quote and pass the whole string to getNextString()
  91019. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  91020. ** a quote character embedded in a string.
  91021. */
  91022. if( *zInput=='"' ){
  91023. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  91024. *pnConsumed = (zInput - z) + ii + 1;
  91025. if( ii==nInput ){
  91026. return SQLITE_ERROR;
  91027. }
  91028. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  91029. }
  91030. /* If control flows to this point, this must be a regular token, or
  91031. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  91032. ** interface. Before doing so, figure out if there is an explicit
  91033. ** column specifier for the token.
  91034. **
  91035. ** TODO: Strangely, it is not possible to associate a column specifier
  91036. ** with a quoted phrase, only with a single token. Not sure if this was
  91037. ** an implementation artifact or an intentional decision when fts3 was
  91038. ** first implemented. Whichever it was, this module duplicates the
  91039. ** limitation.
  91040. */
  91041. iCol = pParse->iDefaultCol;
  91042. iColLen = 0;
  91043. for(ii=0; ii<pParse->nCol; ii++){
  91044. const char *zStr = pParse->azCol[ii];
  91045. int nStr = strlen(zStr);
  91046. if( nInput>nStr && zInput[nStr]==':' && memcmp(zStr, zInput, nStr)==0 ){
  91047. iCol = ii;
  91048. iColLen = ((zInput - z) + nStr + 1);
  91049. break;
  91050. }
  91051. }
  91052. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  91053. *pnConsumed += iColLen;
  91054. return rc;
  91055. }
  91056. /*
  91057. ** The argument is an Fts3Expr structure for a binary operator (any type
  91058. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  91059. ** precedence of the operator. Lower values have a higher precedence (i.e.
  91060. ** group more tightly). For example, in the C language, the == operator
  91061. ** groups more tightly than ||, and would therefore have a higher precedence.
  91062. **
  91063. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  91064. ** is defined), the order of the operators in precedence from highest to
  91065. ** lowest is:
  91066. **
  91067. ** NEAR
  91068. ** NOT
  91069. ** AND (including implicit ANDs)
  91070. ** OR
  91071. **
  91072. ** Note that when using the old query syntax, the OR operator has a higher
  91073. ** precedence than the AND operator.
  91074. */
  91075. static int opPrecedence(Fts3Expr *p){
  91076. assert( p->eType!=FTSQUERY_PHRASE );
  91077. if( sqlite3_fts3_enable_parentheses ){
  91078. return p->eType;
  91079. }else if( p->eType==FTSQUERY_NEAR ){
  91080. return 1;
  91081. }else if( p->eType==FTSQUERY_OR ){
  91082. return 2;
  91083. }
  91084. assert( p->eType==FTSQUERY_AND );
  91085. return 3;
  91086. }
  91087. /*
  91088. ** Argument ppHead contains a pointer to the current head of a query
  91089. ** expression tree being parsed. pPrev is the expression node most recently
  91090. ** inserted into the tree. This function adds pNew, which is always a binary
  91091. ** operator node, into the expression tree based on the relative precedence
  91092. ** of pNew and the existing nodes of the tree. This may result in the head
  91093. ** of the tree changing, in which case *ppHead is set to the new root node.
  91094. */
  91095. static void insertBinaryOperator(
  91096. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  91097. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  91098. Fts3Expr *pNew /* New binary node to insert into expression tree */
  91099. ){
  91100. Fts3Expr *pSplit = pPrev;
  91101. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  91102. pSplit = pSplit->pParent;
  91103. }
  91104. if( pSplit->pParent ){
  91105. assert( pSplit->pParent->pRight==pSplit );
  91106. pSplit->pParent->pRight = pNew;
  91107. pNew->pParent = pSplit->pParent;
  91108. }else{
  91109. *ppHead = pNew;
  91110. }
  91111. pNew->pLeft = pSplit;
  91112. pSplit->pParent = pNew;
  91113. }
  91114. /*
  91115. ** Parse the fts3 query expression found in buffer z, length n. This function
  91116. ** returns either when the end of the buffer is reached or an unmatched
  91117. ** closing bracket - ')' - is encountered.
  91118. **
  91119. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  91120. ** parsed form of the expression and *pnConsumed is set to the number of
  91121. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  91122. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  91123. */
  91124. static int fts3ExprParse(
  91125. ParseContext *pParse, /* fts3 query parse context */
  91126. const char *z, int n, /* Text of MATCH query */
  91127. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  91128. int *pnConsumed /* OUT: Number of bytes consumed */
  91129. ){
  91130. Fts3Expr *pRet = 0;
  91131. Fts3Expr *pPrev = 0;
  91132. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  91133. int nIn = n;
  91134. const char *zIn = z;
  91135. int rc = SQLITE_OK;
  91136. int isRequirePhrase = 1;
  91137. while( rc==SQLITE_OK ){
  91138. Fts3Expr *p = 0;
  91139. int nByte = 0;
  91140. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  91141. if( rc==SQLITE_OK ){
  91142. int isPhrase;
  91143. if( !sqlite3_fts3_enable_parentheses
  91144. && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
  91145. ){
  91146. /* Create an implicit NOT operator. */
  91147. Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
  91148. if( !pNot ){
  91149. sqlite3Fts3ExprFree(p);
  91150. rc = SQLITE_NOMEM;
  91151. goto exprparse_out;
  91152. }
  91153. memset(pNot, 0, sizeof(Fts3Expr));
  91154. pNot->eType = FTSQUERY_NOT;
  91155. pNot->pRight = p;
  91156. if( pNotBranch ){
  91157. pNotBranch->pLeft = p;
  91158. pNot->pRight = pNotBranch;
  91159. }
  91160. pNotBranch = pNot;
  91161. }else{
  91162. int eType = p->eType;
  91163. assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
  91164. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  91165. /* The isRequirePhrase variable is set to true if a phrase or
  91166. ** an expression contained in parenthesis is required. If a
  91167. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  91168. ** isRequirePhrase is set, this is a syntax error.
  91169. */
  91170. if( !isPhrase && isRequirePhrase ){
  91171. sqlite3Fts3ExprFree(p);
  91172. rc = SQLITE_ERROR;
  91173. goto exprparse_out;
  91174. }
  91175. if( isPhrase && !isRequirePhrase ){
  91176. /* Insert an implicit AND operator. */
  91177. Fts3Expr *pAnd;
  91178. assert( pRet && pPrev );
  91179. pAnd = sqlite3_malloc(sizeof(Fts3Expr));
  91180. if( !pAnd ){
  91181. sqlite3Fts3ExprFree(p);
  91182. rc = SQLITE_NOMEM;
  91183. goto exprparse_out;
  91184. }
  91185. memset(pAnd, 0, sizeof(Fts3Expr));
  91186. pAnd->eType = FTSQUERY_AND;
  91187. insertBinaryOperator(&pRet, pPrev, pAnd);
  91188. pPrev = pAnd;
  91189. }
  91190. /* This test catches attempts to make either operand of a NEAR
  91191. ** operator something other than a phrase. For example, either of
  91192. ** the following:
  91193. **
  91194. ** (bracketed expression) NEAR phrase
  91195. ** phrase NEAR (bracketed expression)
  91196. **
  91197. ** Return an error in either case.
  91198. */
  91199. if( pPrev && (
  91200. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  91201. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  91202. )){
  91203. sqlite3Fts3ExprFree(p);
  91204. rc = SQLITE_ERROR;
  91205. goto exprparse_out;
  91206. }
  91207. if( isPhrase ){
  91208. if( pRet ){
  91209. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  91210. pPrev->pRight = p;
  91211. p->pParent = pPrev;
  91212. }else{
  91213. pRet = p;
  91214. }
  91215. }else{
  91216. insertBinaryOperator(&pRet, pPrev, p);
  91217. }
  91218. isRequirePhrase = !isPhrase;
  91219. }
  91220. assert( nByte>0 );
  91221. }
  91222. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  91223. nIn -= nByte;
  91224. zIn += nByte;
  91225. pPrev = p;
  91226. }
  91227. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  91228. rc = SQLITE_ERROR;
  91229. }
  91230. if( rc==SQLITE_DONE ){
  91231. rc = SQLITE_OK;
  91232. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  91233. if( !pRet ){
  91234. rc = SQLITE_ERROR;
  91235. }else{
  91236. pNotBranch->pLeft = pRet;
  91237. pRet = pNotBranch;
  91238. }
  91239. }
  91240. }
  91241. *pnConsumed = n - nIn;
  91242. exprparse_out:
  91243. if( rc!=SQLITE_OK ){
  91244. sqlite3Fts3ExprFree(pRet);
  91245. sqlite3Fts3ExprFree(pNotBranch);
  91246. pRet = 0;
  91247. }
  91248. *ppExpr = pRet;
  91249. return rc;
  91250. }
  91251. /*
  91252. ** Parameters z and n contain a pointer to and length of a buffer containing
  91253. ** an fts3 query expression, respectively. This function attempts to parse the
  91254. ** query expression and create a tree of Fts3Expr structures representing the
  91255. ** parsed expression. If successful, *ppExpr is set to point to the head
  91256. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  91257. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  91258. ** error) is returned and *ppExpr is set to 0.
  91259. **
  91260. ** If parameter n is a negative number, then z is assumed to point to a
  91261. ** nul-terminated string and the length is determined using strlen().
  91262. **
  91263. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  91264. ** use to normalize query tokens while parsing the expression. The azCol[]
  91265. ** array, which is assumed to contain nCol entries, should contain the names
  91266. ** of each column in the target fts3 table, in order from left to right.
  91267. ** Column names must be nul-terminated strings.
  91268. **
  91269. ** The iDefaultCol parameter should be passed the index of the table column
  91270. ** that appears on the left-hand-side of the MATCH operator (the default
  91271. ** column to match against for tokens for which a column name is not explicitly
  91272. ** specified as part of the query string), or -1 if tokens may by default
  91273. ** match any table column.
  91274. */
  91275. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  91276. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  91277. char **azCol, /* Array of column names for fts3 table */
  91278. int nCol, /* Number of entries in azCol[] */
  91279. int iDefaultCol, /* Default column to query */
  91280. const char *z, int n, /* Text of MATCH query */
  91281. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  91282. ){
  91283. int nParsed;
  91284. int rc;
  91285. ParseContext sParse;
  91286. sParse.pTokenizer = pTokenizer;
  91287. sParse.azCol = (const char **)azCol;
  91288. sParse.nCol = nCol;
  91289. sParse.iDefaultCol = iDefaultCol;
  91290. sParse.nNest = 0;
  91291. if( z==0 ){
  91292. *ppExpr = 0;
  91293. return SQLITE_OK;
  91294. }
  91295. if( n<0 ){
  91296. n = strlen(z);
  91297. }
  91298. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  91299. /* Check for mismatched parenthesis */
  91300. if( rc==SQLITE_OK && sParse.nNest ){
  91301. rc = SQLITE_ERROR;
  91302. sqlite3Fts3ExprFree(*ppExpr);
  91303. *ppExpr = 0;
  91304. }
  91305. return rc;
  91306. }
  91307. /*
  91308. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  91309. */
  91310. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
  91311. if( p ){
  91312. sqlite3Fts3ExprFree(p->pLeft);
  91313. sqlite3Fts3ExprFree(p->pRight);
  91314. sqlite3_free(p);
  91315. }
  91316. }
  91317. /****************************************************************************
  91318. *****************************************************************************
  91319. ** Everything after this point is just test code.
  91320. */
  91321. #ifdef SQLITE_TEST
  91322. /*
  91323. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  91324. */
  91325. static int queryTestTokenizer(
  91326. sqlite3 *db,
  91327. const char *zName,
  91328. const sqlite3_tokenizer_module **pp
  91329. ){
  91330. int rc;
  91331. sqlite3_stmt *pStmt;
  91332. const char zSql[] = "SELECT fts3_tokenizer(?)";
  91333. *pp = 0;
  91334. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  91335. if( rc!=SQLITE_OK ){
  91336. return rc;
  91337. }
  91338. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  91339. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  91340. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  91341. memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  91342. }
  91343. }
  91344. return sqlite3_finalize(pStmt);
  91345. }
  91346. /*
  91347. ** This function is part of the test interface for the query parser. It
  91348. ** writes a text representation of the query expression pExpr into the
  91349. ** buffer pointed to by argument zBuf. It is assumed that zBuf is large
  91350. ** enough to store the required text representation.
  91351. */
  91352. static void exprToString(Fts3Expr *pExpr, char *zBuf){
  91353. switch( pExpr->eType ){
  91354. case FTSQUERY_PHRASE: {
  91355. Fts3Phrase *pPhrase = pExpr->pPhrase;
  91356. int i;
  91357. zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
  91358. for(i=0; i<pPhrase->nToken; i++){
  91359. zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
  91360. zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
  91361. }
  91362. return;
  91363. }
  91364. case FTSQUERY_NEAR:
  91365. zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
  91366. break;
  91367. case FTSQUERY_NOT:
  91368. zBuf += sprintf(zBuf, "NOT ");
  91369. break;
  91370. case FTSQUERY_AND:
  91371. zBuf += sprintf(zBuf, "AND ");
  91372. break;
  91373. case FTSQUERY_OR:
  91374. zBuf += sprintf(zBuf, "OR ");
  91375. break;
  91376. }
  91377. zBuf += sprintf(zBuf, "{");
  91378. exprToString(pExpr->pLeft, zBuf);
  91379. zBuf += strlen(zBuf);
  91380. zBuf += sprintf(zBuf, "} ");
  91381. zBuf += sprintf(zBuf, "{");
  91382. exprToString(pExpr->pRight, zBuf);
  91383. zBuf += strlen(zBuf);
  91384. zBuf += sprintf(zBuf, "}");
  91385. }
  91386. /*
  91387. ** This is the implementation of a scalar SQL function used to test the
  91388. ** expression parser. It should be called as follows:
  91389. **
  91390. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  91391. **
  91392. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  91393. ** to parse the query expression (see README.tokenizers). The second argument
  91394. ** is the query expression to parse. Each subsequent argument is the name
  91395. ** of a column of the fts3 table that the query expression may refer to.
  91396. ** For example:
  91397. **
  91398. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  91399. */
  91400. static void fts3ExprTest(
  91401. sqlite3_context *context,
  91402. int argc,
  91403. sqlite3_value **argv
  91404. ){
  91405. sqlite3_tokenizer_module const *pModule = 0;
  91406. sqlite3_tokenizer *pTokenizer = 0;
  91407. int rc;
  91408. char **azCol = 0;
  91409. const char *zExpr;
  91410. int nExpr;
  91411. int nCol;
  91412. int ii;
  91413. Fts3Expr *pExpr;
  91414. sqlite3 *db = sqlite3_context_db_handle(context);
  91415. if( argc<3 ){
  91416. sqlite3_result_error(context,
  91417. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  91418. );
  91419. return;
  91420. }
  91421. rc = queryTestTokenizer(db,
  91422. (const char *)sqlite3_value_text(argv[0]), &pModule);
  91423. if( rc==SQLITE_NOMEM ){
  91424. sqlite3_result_error_nomem(context);
  91425. goto exprtest_out;
  91426. }else if( !pModule ){
  91427. sqlite3_result_error(context, "No such tokenizer module", -1);
  91428. goto exprtest_out;
  91429. }
  91430. rc = pModule->xCreate(0, 0, &pTokenizer);
  91431. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  91432. if( rc==SQLITE_NOMEM ){
  91433. sqlite3_result_error_nomem(context);
  91434. goto exprtest_out;
  91435. }
  91436. pTokenizer->pModule = pModule;
  91437. zExpr = (const char *)sqlite3_value_text(argv[1]);
  91438. nExpr = sqlite3_value_bytes(argv[1]);
  91439. nCol = argc-2;
  91440. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  91441. if( !azCol ){
  91442. sqlite3_result_error_nomem(context);
  91443. goto exprtest_out;
  91444. }
  91445. for(ii=0; ii<nCol; ii++){
  91446. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  91447. }
  91448. rc = sqlite3Fts3ExprParse(
  91449. pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
  91450. );
  91451. if( rc==SQLITE_NOMEM ){
  91452. sqlite3_result_error_nomem(context);
  91453. goto exprtest_out;
  91454. }else if( rc==SQLITE_OK ){
  91455. char zBuf[4096];
  91456. exprToString(pExpr, zBuf);
  91457. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  91458. sqlite3Fts3ExprFree(pExpr);
  91459. }else{
  91460. sqlite3_result_error(context, "Error parsing expression", -1);
  91461. }
  91462. exprtest_out:
  91463. if( pModule && pTokenizer ){
  91464. rc = pModule->xDestroy(pTokenizer);
  91465. }
  91466. sqlite3_free(azCol);
  91467. }
  91468. /*
  91469. ** Register the query expression parser test function fts3_exprtest()
  91470. ** with database connection db.
  91471. */
  91472. SQLITE_PRIVATE void sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  91473. sqlite3_create_function(
  91474. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  91475. );
  91476. }
  91477. #endif
  91478. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  91479. /************** End of fts3_expr.c *******************************************/
  91480. /************** Begin file fts3_hash.c ***************************************/
  91481. /*
  91482. ** 2001 September 22
  91483. **
  91484. ** The author disclaims copyright to this source code. In place of
  91485. ** a legal notice, here is a blessing:
  91486. **
  91487. ** May you do good and not evil.
  91488. ** May you find forgiveness for yourself and forgive others.
  91489. ** May you share freely, never taking more than you give.
  91490. **
  91491. *************************************************************************
  91492. ** This is the implementation of generic hash-tables used in SQLite.
  91493. ** We've modified it slightly to serve as a standalone hash table
  91494. ** implementation for the full-text indexing module.
  91495. */
  91496. /*
  91497. ** The code in this file is only compiled if:
  91498. **
  91499. ** * The FTS3 module is being built as an extension
  91500. ** (in which case SQLITE_CORE is not defined), or
  91501. **
  91502. ** * The FTS3 module is being built into the core of
  91503. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  91504. */
  91505. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  91506. /*
  91507. ** Malloc and Free functions
  91508. */
  91509. static void *fts3HashMalloc(int n){
  91510. void *p = sqlite3_malloc(n);
  91511. if( p ){
  91512. memset(p, 0, n);
  91513. }
  91514. return p;
  91515. }
  91516. static void fts3HashFree(void *p){
  91517. sqlite3_free(p);
  91518. }
  91519. /* Turn bulk memory into a hash table object by initializing the
  91520. ** fields of the Hash structure.
  91521. **
  91522. ** "pNew" is a pointer to the hash table that is to be initialized.
  91523. ** keyClass is one of the constants
  91524. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  91525. ** determines what kind of key the hash table will use. "copyKey" is
  91526. ** true if the hash table should make its own private copy of keys and
  91527. ** false if it should just use the supplied pointer.
  91528. */
  91529. SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
  91530. assert( pNew!=0 );
  91531. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  91532. pNew->keyClass = keyClass;
  91533. pNew->copyKey = copyKey;
  91534. pNew->first = 0;
  91535. pNew->count = 0;
  91536. pNew->htsize = 0;
  91537. pNew->ht = 0;
  91538. }
  91539. /* Remove all entries from a hash table. Reclaim all memory.
  91540. ** Call this routine to delete a hash table or to reset a hash table
  91541. ** to the empty state.
  91542. */
  91543. SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){
  91544. fts3HashElem *elem; /* For looping over all elements of the table */
  91545. assert( pH!=0 );
  91546. elem = pH->first;
  91547. pH->first = 0;
  91548. fts3HashFree(pH->ht);
  91549. pH->ht = 0;
  91550. pH->htsize = 0;
  91551. while( elem ){
  91552. fts3HashElem *next_elem = elem->next;
  91553. if( pH->copyKey && elem->pKey ){
  91554. fts3HashFree(elem->pKey);
  91555. }
  91556. fts3HashFree(elem);
  91557. elem = next_elem;
  91558. }
  91559. pH->count = 0;
  91560. }
  91561. /*
  91562. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  91563. */
  91564. static int fts3StrHash(const void *pKey, int nKey){
  91565. const char *z = (const char *)pKey;
  91566. int h = 0;
  91567. if( nKey<=0 ) nKey = (int) strlen(z);
  91568. while( nKey > 0 ){
  91569. h = (h<<3) ^ h ^ *z++;
  91570. nKey--;
  91571. }
  91572. return h & 0x7fffffff;
  91573. }
  91574. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  91575. if( n1!=n2 ) return 1;
  91576. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  91577. }
  91578. /*
  91579. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  91580. */
  91581. static int fts3BinHash(const void *pKey, int nKey){
  91582. int h = 0;
  91583. const char *z = (const char *)pKey;
  91584. while( nKey-- > 0 ){
  91585. h = (h<<3) ^ h ^ *(z++);
  91586. }
  91587. return h & 0x7fffffff;
  91588. }
  91589. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  91590. if( n1!=n2 ) return 1;
  91591. return memcmp(pKey1,pKey2,n1);
  91592. }
  91593. /*
  91594. ** Return a pointer to the appropriate hash function given the key class.
  91595. **
  91596. ** The C syntax in this function definition may be unfamilar to some
  91597. ** programmers, so we provide the following additional explanation:
  91598. **
  91599. ** The name of the function is "ftsHashFunction". The function takes a
  91600. ** single parameter "keyClass". The return value of ftsHashFunction()
  91601. ** is a pointer to another function. Specifically, the return value
  91602. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  91603. ** with types "const void*" and "int" and returns an "int".
  91604. */
  91605. static int (*ftsHashFunction(int keyClass))(const void*,int){
  91606. if( keyClass==FTS3_HASH_STRING ){
  91607. return &fts3StrHash;
  91608. }else{
  91609. assert( keyClass==FTS3_HASH_BINARY );
  91610. return &fts3BinHash;
  91611. }
  91612. }
  91613. /*
  91614. ** Return a pointer to the appropriate hash function given the key class.
  91615. **
  91616. ** For help in interpreted the obscure C code in the function definition,
  91617. ** see the header comment on the previous function.
  91618. */
  91619. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  91620. if( keyClass==FTS3_HASH_STRING ){
  91621. return &fts3StrCompare;
  91622. }else{
  91623. assert( keyClass==FTS3_HASH_BINARY );
  91624. return &fts3BinCompare;
  91625. }
  91626. }
  91627. /* Link an element into the hash table
  91628. */
  91629. static void fts3HashInsertElement(
  91630. fts3Hash *pH, /* The complete hash table */
  91631. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  91632. fts3HashElem *pNew /* The element to be inserted */
  91633. ){
  91634. fts3HashElem *pHead; /* First element already in pEntry */
  91635. pHead = pEntry->chain;
  91636. if( pHead ){
  91637. pNew->next = pHead;
  91638. pNew->prev = pHead->prev;
  91639. if( pHead->prev ){ pHead->prev->next = pNew; }
  91640. else { pH->first = pNew; }
  91641. pHead->prev = pNew;
  91642. }else{
  91643. pNew->next = pH->first;
  91644. if( pH->first ){ pH->first->prev = pNew; }
  91645. pNew->prev = 0;
  91646. pH->first = pNew;
  91647. }
  91648. pEntry->count++;
  91649. pEntry->chain = pNew;
  91650. }
  91651. /* Resize the hash table so that it cantains "new_size" buckets.
  91652. ** "new_size" must be a power of 2. The hash table might fail
  91653. ** to resize if sqliteMalloc() fails.
  91654. */
  91655. static void fts3Rehash(fts3Hash *pH, int new_size){
  91656. struct _fts3ht *new_ht; /* The new hash table */
  91657. fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  91658. int (*xHash)(const void*,int); /* The hash function */
  91659. assert( (new_size & (new_size-1))==0 );
  91660. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  91661. if( new_ht==0 ) return;
  91662. fts3HashFree(pH->ht);
  91663. pH->ht = new_ht;
  91664. pH->htsize = new_size;
  91665. xHash = ftsHashFunction(pH->keyClass);
  91666. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  91667. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  91668. next_elem = elem->next;
  91669. fts3HashInsertElement(pH, &new_ht[h], elem);
  91670. }
  91671. }
  91672. /* This function (for internal use only) locates an element in an
  91673. ** hash table that matches the given key. The hash for this key has
  91674. ** already been computed and is passed as the 4th parameter.
  91675. */
  91676. static fts3HashElem *fts3FindElementByHash(
  91677. const fts3Hash *pH, /* The pH to be searched */
  91678. const void *pKey, /* The key we are searching for */
  91679. int nKey,
  91680. int h /* The hash for this key. */
  91681. ){
  91682. fts3HashElem *elem; /* Used to loop thru the element list */
  91683. int count; /* Number of elements left to test */
  91684. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  91685. if( pH->ht ){
  91686. struct _fts3ht *pEntry = &pH->ht[h];
  91687. elem = pEntry->chain;
  91688. count = pEntry->count;
  91689. xCompare = ftsCompareFunction(pH->keyClass);
  91690. while( count-- && elem ){
  91691. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  91692. return elem;
  91693. }
  91694. elem = elem->next;
  91695. }
  91696. }
  91697. return 0;
  91698. }
  91699. /* Remove a single entry from the hash table given a pointer to that
  91700. ** element and a hash on the element's key.
  91701. */
  91702. static void fts3RemoveElementByHash(
  91703. fts3Hash *pH, /* The pH containing "elem" */
  91704. fts3HashElem* elem, /* The element to be removed from the pH */
  91705. int h /* Hash value for the element */
  91706. ){
  91707. struct _fts3ht *pEntry;
  91708. if( elem->prev ){
  91709. elem->prev->next = elem->next;
  91710. }else{
  91711. pH->first = elem->next;
  91712. }
  91713. if( elem->next ){
  91714. elem->next->prev = elem->prev;
  91715. }
  91716. pEntry = &pH->ht[h];
  91717. if( pEntry->chain==elem ){
  91718. pEntry->chain = elem->next;
  91719. }
  91720. pEntry->count--;
  91721. if( pEntry->count<=0 ){
  91722. pEntry->chain = 0;
  91723. }
  91724. if( pH->copyKey && elem->pKey ){
  91725. fts3HashFree(elem->pKey);
  91726. }
  91727. fts3HashFree( elem );
  91728. pH->count--;
  91729. if( pH->count<=0 ){
  91730. assert( pH->first==0 );
  91731. assert( pH->count==0 );
  91732. fts3HashClear(pH);
  91733. }
  91734. }
  91735. /* Attempt to locate an element of the hash table pH with a key
  91736. ** that matches pKey,nKey. Return the data for this element if it is
  91737. ** found, or NULL if there is no match.
  91738. */
  91739. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
  91740. int h; /* A hash on key */
  91741. fts3HashElem *elem; /* The element that matches key */
  91742. int (*xHash)(const void*,int); /* The hash function */
  91743. if( pH==0 || pH->ht==0 ) return 0;
  91744. xHash = ftsHashFunction(pH->keyClass);
  91745. assert( xHash!=0 );
  91746. h = (*xHash)(pKey,nKey);
  91747. assert( (pH->htsize & (pH->htsize-1))==0 );
  91748. elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  91749. return elem ? elem->data : 0;
  91750. }
  91751. /* Insert an element into the hash table pH. The key is pKey,nKey
  91752. ** and the data is "data".
  91753. **
  91754. ** If no element exists with a matching key, then a new
  91755. ** element is created. A copy of the key is made if the copyKey
  91756. ** flag is set. NULL is returned.
  91757. **
  91758. ** If another element already exists with the same key, then the
  91759. ** new data replaces the old data and the old data is returned.
  91760. ** The key is not copied in this instance. If a malloc fails, then
  91761. ** the new data is returned and the hash table is unchanged.
  91762. **
  91763. ** If the "data" parameter to this function is NULL, then the
  91764. ** element corresponding to "key" is removed from the hash table.
  91765. */
  91766. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  91767. fts3Hash *pH, /* The hash table to insert into */
  91768. const void *pKey, /* The key */
  91769. int nKey, /* Number of bytes in the key */
  91770. void *data /* The data */
  91771. ){
  91772. int hraw; /* Raw hash value of the key */
  91773. int h; /* the hash of the key modulo hash table size */
  91774. fts3HashElem *elem; /* Used to loop thru the element list */
  91775. fts3HashElem *new_elem; /* New element added to the pH */
  91776. int (*xHash)(const void*,int); /* The hash function */
  91777. assert( pH!=0 );
  91778. xHash = ftsHashFunction(pH->keyClass);
  91779. assert( xHash!=0 );
  91780. hraw = (*xHash)(pKey, nKey);
  91781. assert( (pH->htsize & (pH->htsize-1))==0 );
  91782. h = hraw & (pH->htsize-1);
  91783. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  91784. if( elem ){
  91785. void *old_data = elem->data;
  91786. if( data==0 ){
  91787. fts3RemoveElementByHash(pH,elem,h);
  91788. }else{
  91789. elem->data = data;
  91790. }
  91791. return old_data;
  91792. }
  91793. if( data==0 ) return 0;
  91794. if( pH->htsize==0 ){
  91795. fts3Rehash(pH,8);
  91796. if( pH->htsize==0 ){
  91797. pH->count = 0;
  91798. return data;
  91799. }
  91800. }
  91801. new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
  91802. if( new_elem==0 ) return data;
  91803. if( pH->copyKey && pKey!=0 ){
  91804. new_elem->pKey = fts3HashMalloc( nKey );
  91805. if( new_elem->pKey==0 ){
  91806. fts3HashFree(new_elem);
  91807. return data;
  91808. }
  91809. memcpy((void*)new_elem->pKey, pKey, nKey);
  91810. }else{
  91811. new_elem->pKey = (void*)pKey;
  91812. }
  91813. new_elem->nKey = nKey;
  91814. pH->count++;
  91815. if( pH->count > pH->htsize ){
  91816. fts3Rehash(pH,pH->htsize*2);
  91817. }
  91818. assert( pH->htsize>0 );
  91819. assert( (pH->htsize & (pH->htsize-1))==0 );
  91820. h = hraw & (pH->htsize-1);
  91821. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  91822. new_elem->data = data;
  91823. return 0;
  91824. }
  91825. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  91826. /************** End of fts3_hash.c *******************************************/
  91827. /************** Begin file fts3_porter.c *************************************/
  91828. /*
  91829. ** 2006 September 30
  91830. **
  91831. ** The author disclaims copyright to this source code. In place of
  91832. ** a legal notice, here is a blessing:
  91833. **
  91834. ** May you do good and not evil.
  91835. ** May you find forgiveness for yourself and forgive others.
  91836. ** May you share freely, never taking more than you give.
  91837. **
  91838. *************************************************************************
  91839. ** Implementation of the full-text-search tokenizer that implements
  91840. ** a Porter stemmer.
  91841. */
  91842. /*
  91843. ** The code in this file is only compiled if:
  91844. **
  91845. ** * The FTS3 module is being built as an extension
  91846. ** (in which case SQLITE_CORE is not defined), or
  91847. **
  91848. ** * The FTS3 module is being built into the core of
  91849. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  91850. */
  91851. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  91852. /*
  91853. ** Class derived from sqlite3_tokenizer
  91854. */
  91855. typedef struct porter_tokenizer {
  91856. sqlite3_tokenizer base; /* Base class */
  91857. } porter_tokenizer;
  91858. /*
  91859. ** Class derived from sqlit3_tokenizer_cursor
  91860. */
  91861. typedef struct porter_tokenizer_cursor {
  91862. sqlite3_tokenizer_cursor base;
  91863. const char *zInput; /* input we are tokenizing */
  91864. int nInput; /* size of the input */
  91865. int iOffset; /* current position in zInput */
  91866. int iToken; /* index of next token to be returned */
  91867. char *zToken; /* storage for current token */
  91868. int nAllocated; /* space allocated to zToken buffer */
  91869. } porter_tokenizer_cursor;
  91870. /* Forward declaration */
  91871. static const sqlite3_tokenizer_module porterTokenizerModule;
  91872. /*
  91873. ** Create a new tokenizer instance.
  91874. */
  91875. static int porterCreate(
  91876. int argc, const char * const *argv,
  91877. sqlite3_tokenizer **ppTokenizer
  91878. ){
  91879. porter_tokenizer *t;
  91880. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  91881. if( t==NULL ) return SQLITE_NOMEM;
  91882. memset(t, 0, sizeof(*t));
  91883. *ppTokenizer = &t->base;
  91884. return SQLITE_OK;
  91885. }
  91886. /*
  91887. ** Destroy a tokenizer
  91888. */
  91889. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  91890. sqlite3_free(pTokenizer);
  91891. return SQLITE_OK;
  91892. }
  91893. /*
  91894. ** Prepare to begin tokenizing a particular string. The input
  91895. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  91896. ** used to incrementally tokenize this string is returned in
  91897. ** *ppCursor.
  91898. */
  91899. static int porterOpen(
  91900. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  91901. const char *zInput, int nInput, /* String to be tokenized */
  91902. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  91903. ){
  91904. porter_tokenizer_cursor *c;
  91905. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  91906. if( c==NULL ) return SQLITE_NOMEM;
  91907. c->zInput = zInput;
  91908. if( zInput==0 ){
  91909. c->nInput = 0;
  91910. }else if( nInput<0 ){
  91911. c->nInput = (int)strlen(zInput);
  91912. }else{
  91913. c->nInput = nInput;
  91914. }
  91915. c->iOffset = 0; /* start tokenizing at the beginning */
  91916. c->iToken = 0;
  91917. c->zToken = NULL; /* no space allocated, yet. */
  91918. c->nAllocated = 0;
  91919. *ppCursor = &c->base;
  91920. return SQLITE_OK;
  91921. }
  91922. /*
  91923. ** Close a tokenization cursor previously opened by a call to
  91924. ** porterOpen() above.
  91925. */
  91926. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  91927. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  91928. sqlite3_free(c->zToken);
  91929. sqlite3_free(c);
  91930. return SQLITE_OK;
  91931. }
  91932. /*
  91933. ** Vowel or consonant
  91934. */
  91935. static const char cType[] = {
  91936. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  91937. 1, 1, 1, 2, 1
  91938. };
  91939. /*
  91940. ** isConsonant() and isVowel() determine if their first character in
  91941. ** the string they point to is a consonant or a vowel, according
  91942. ** to Porter ruls.
  91943. **
  91944. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  91945. ** 'Y' is a consonant unless it follows another consonant,
  91946. ** in which case it is a vowel.
  91947. **
  91948. ** In these routine, the letters are in reverse order. So the 'y' rule
  91949. ** is that 'y' is a consonant unless it is followed by another
  91950. ** consonent.
  91951. */
  91952. static int isVowel(const char*);
  91953. static int isConsonant(const char *z){
  91954. int j;
  91955. char x = *z;
  91956. if( x==0 ) return 0;
  91957. assert( x>='a' && x<='z' );
  91958. j = cType[x-'a'];
  91959. if( j<2 ) return j;
  91960. return z[1]==0 || isVowel(z + 1);
  91961. }
  91962. static int isVowel(const char *z){
  91963. int j;
  91964. char x = *z;
  91965. if( x==0 ) return 0;
  91966. assert( x>='a' && x<='z' );
  91967. j = cType[x-'a'];
  91968. if( j<2 ) return 1-j;
  91969. return isConsonant(z + 1);
  91970. }
  91971. /*
  91972. ** Let any sequence of one or more vowels be represented by V and let
  91973. ** C be sequence of one or more consonants. Then every word can be
  91974. ** represented as:
  91975. **
  91976. ** [C] (VC){m} [V]
  91977. **
  91978. ** In prose: A word is an optional consonant followed by zero or
  91979. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  91980. ** number of vowel consonant pairs. This routine computes the value
  91981. ** of m for the first i bytes of a word.
  91982. **
  91983. ** Return true if the m-value for z is 1 or more. In other words,
  91984. ** return true if z contains at least one vowel that is followed
  91985. ** by a consonant.
  91986. **
  91987. ** In this routine z[] is in reverse order. So we are really looking
  91988. ** for an instance of of a consonant followed by a vowel.
  91989. */
  91990. static int m_gt_0(const char *z){
  91991. while( isVowel(z) ){ z++; }
  91992. if( *z==0 ) return 0;
  91993. while( isConsonant(z) ){ z++; }
  91994. return *z!=0;
  91995. }
  91996. /* Like mgt0 above except we are looking for a value of m which is
  91997. ** exactly 1
  91998. */
  91999. static int m_eq_1(const char *z){
  92000. while( isVowel(z) ){ z++; }
  92001. if( *z==0 ) return 0;
  92002. while( isConsonant(z) ){ z++; }
  92003. if( *z==0 ) return 0;
  92004. while( isVowel(z) ){ z++; }
  92005. if( *z==0 ) return 1;
  92006. while( isConsonant(z) ){ z++; }
  92007. return *z==0;
  92008. }
  92009. /* Like mgt0 above except we are looking for a value of m>1 instead
  92010. ** or m>0
  92011. */
  92012. static int m_gt_1(const char *z){
  92013. while( isVowel(z) ){ z++; }
  92014. if( *z==0 ) return 0;
  92015. while( isConsonant(z) ){ z++; }
  92016. if( *z==0 ) return 0;
  92017. while( isVowel(z) ){ z++; }
  92018. if( *z==0 ) return 0;
  92019. while( isConsonant(z) ){ z++; }
  92020. return *z!=0;
  92021. }
  92022. /*
  92023. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  92024. */
  92025. static int hasVowel(const char *z){
  92026. while( isConsonant(z) ){ z++; }
  92027. return *z!=0;
  92028. }
  92029. /*
  92030. ** Return TRUE if the word ends in a double consonant.
  92031. **
  92032. ** The text is reversed here. So we are really looking at
  92033. ** the first two characters of z[].
  92034. */
  92035. static int doubleConsonant(const char *z){
  92036. return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
  92037. }
  92038. /*
  92039. ** Return TRUE if the word ends with three letters which
  92040. ** are consonant-vowel-consonent and where the final consonant
  92041. ** is not 'w', 'x', or 'y'.
  92042. **
  92043. ** The word is reversed here. So we are really checking the
  92044. ** first three letters and the first one cannot be in [wxy].
  92045. */
  92046. static int star_oh(const char *z){
  92047. return
  92048. z[0]!=0 && isConsonant(z) &&
  92049. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  92050. z[1]!=0 && isVowel(z+1) &&
  92051. z[2]!=0 && isConsonant(z+2);
  92052. }
  92053. /*
  92054. ** If the word ends with zFrom and xCond() is true for the stem
  92055. ** of the word that preceeds the zFrom ending, then change the
  92056. ** ending to zTo.
  92057. **
  92058. ** The input word *pz and zFrom are both in reverse order. zTo
  92059. ** is in normal order.
  92060. **
  92061. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  92062. ** match. Not that TRUE is returned even if xCond() fails and
  92063. ** no substitution occurs.
  92064. */
  92065. static int stem(
  92066. char **pz, /* The word being stemmed (Reversed) */
  92067. const char *zFrom, /* If the ending matches this... (Reversed) */
  92068. const char *zTo, /* ... change the ending to this (not reversed) */
  92069. int (*xCond)(const char*) /* Condition that must be true */
  92070. ){
  92071. char *z = *pz;
  92072. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  92073. if( *zFrom!=0 ) return 0;
  92074. if( xCond && !xCond(z) ) return 1;
  92075. while( *zTo ){
  92076. *(--z) = *(zTo++);
  92077. }
  92078. *pz = z;
  92079. return 1;
  92080. }
  92081. /*
  92082. ** This is the fallback stemmer used when the porter stemmer is
  92083. ** inappropriate. The input word is copied into the output with
  92084. ** US-ASCII case folding. If the input word is too long (more
  92085. ** than 20 bytes if it contains no digits or more than 6 bytes if
  92086. ** it contains digits) then word is truncated to 20 or 6 bytes
  92087. ** by taking 10 or 3 bytes from the beginning and end.
  92088. */
  92089. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  92090. int i, mx, j;
  92091. int hasDigit = 0;
  92092. for(i=0; i<nIn; i++){
  92093. int c = zIn[i];
  92094. if( c>='A' && c<='Z' ){
  92095. zOut[i] = c - 'A' + 'a';
  92096. }else{
  92097. if( c>='0' && c<='9' ) hasDigit = 1;
  92098. zOut[i] = c;
  92099. }
  92100. }
  92101. mx = hasDigit ? 3 : 10;
  92102. if( nIn>mx*2 ){
  92103. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  92104. zOut[j] = zOut[i];
  92105. }
  92106. i = j;
  92107. }
  92108. zOut[i] = 0;
  92109. *pnOut = i;
  92110. }
  92111. /*
  92112. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  92113. ** zOut is at least big enough to hold nIn bytes. Write the actual
  92114. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  92115. **
  92116. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  92117. ** are converted to lower case. Upper-case UTF characters are
  92118. ** unchanged.
  92119. **
  92120. ** Words that are longer than about 20 bytes are stemmed by retaining
  92121. ** a few bytes from the beginning and the end of the word. If the
  92122. ** word contains digits, 3 bytes are taken from the beginning and
  92123. ** 3 bytes from the end. For long words without digits, 10 bytes
  92124. ** are taken from each end. US-ASCII case folding still applies.
  92125. **
  92126. ** If the input word contains not digits but does characters not
  92127. ** in [a-zA-Z] then no stemming is attempted and this routine just
  92128. ** copies the input into the input into the output with US-ASCII
  92129. ** case folding.
  92130. **
  92131. ** Stemming never increases the length of the word. So there is
  92132. ** no chance of overflowing the zOut buffer.
  92133. */
  92134. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  92135. int i, j, c;
  92136. char zReverse[28];
  92137. char *z, *z2;
  92138. if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
  92139. /* The word is too big or too small for the porter stemmer.
  92140. ** Fallback to the copy stemmer */
  92141. copy_stemmer(zIn, nIn, zOut, pnOut);
  92142. return;
  92143. }
  92144. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  92145. c = zIn[i];
  92146. if( c>='A' && c<='Z' ){
  92147. zReverse[j] = c + 'a' - 'A';
  92148. }else if( c>='a' && c<='z' ){
  92149. zReverse[j] = c;
  92150. }else{
  92151. /* The use of a character not in [a-zA-Z] means that we fallback
  92152. ** to the copy stemmer */
  92153. copy_stemmer(zIn, nIn, zOut, pnOut);
  92154. return;
  92155. }
  92156. }
  92157. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  92158. z = &zReverse[j+1];
  92159. /* Step 1a */
  92160. if( z[0]=='s' ){
  92161. if(
  92162. !stem(&z, "sess", "ss", 0) &&
  92163. !stem(&z, "sei", "i", 0) &&
  92164. !stem(&z, "ss", "ss", 0)
  92165. ){
  92166. z++;
  92167. }
  92168. }
  92169. /* Step 1b */
  92170. z2 = z;
  92171. if( stem(&z, "dee", "ee", m_gt_0) ){
  92172. /* Do nothing. The work was all in the test */
  92173. }else if(
  92174. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  92175. && z!=z2
  92176. ){
  92177. if( stem(&z, "ta", "ate", 0) ||
  92178. stem(&z, "lb", "ble", 0) ||
  92179. stem(&z, "zi", "ize", 0) ){
  92180. /* Do nothing. The work was all in the test */
  92181. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  92182. z++;
  92183. }else if( m_eq_1(z) && star_oh(z) ){
  92184. *(--z) = 'e';
  92185. }
  92186. }
  92187. /* Step 1c */
  92188. if( z[0]=='y' && hasVowel(z+1) ){
  92189. z[0] = 'i';
  92190. }
  92191. /* Step 2 */
  92192. switch( z[1] ){
  92193. case 'a':
  92194. stem(&z, "lanoita", "ate", m_gt_0) ||
  92195. stem(&z, "lanoit", "tion", m_gt_0);
  92196. break;
  92197. case 'c':
  92198. stem(&z, "icne", "ence", m_gt_0) ||
  92199. stem(&z, "icna", "ance", m_gt_0);
  92200. break;
  92201. case 'e':
  92202. stem(&z, "rezi", "ize", m_gt_0);
  92203. break;
  92204. case 'g':
  92205. stem(&z, "igol", "log", m_gt_0);
  92206. break;
  92207. case 'l':
  92208. stem(&z, "ilb", "ble", m_gt_0) ||
  92209. stem(&z, "illa", "al", m_gt_0) ||
  92210. stem(&z, "iltne", "ent", m_gt_0) ||
  92211. stem(&z, "ile", "e", m_gt_0) ||
  92212. stem(&z, "ilsuo", "ous", m_gt_0);
  92213. break;
  92214. case 'o':
  92215. stem(&z, "noitazi", "ize", m_gt_0) ||
  92216. stem(&z, "noita", "ate", m_gt_0) ||
  92217. stem(&z, "rota", "ate", m_gt_0);
  92218. break;
  92219. case 's':
  92220. stem(&z, "msila", "al", m_gt_0) ||
  92221. stem(&z, "ssenevi", "ive", m_gt_0) ||
  92222. stem(&z, "ssenluf", "ful", m_gt_0) ||
  92223. stem(&z, "ssensuo", "ous", m_gt_0);
  92224. break;
  92225. case 't':
  92226. stem(&z, "itila", "al", m_gt_0) ||
  92227. stem(&z, "itivi", "ive", m_gt_0) ||
  92228. stem(&z, "itilib", "ble", m_gt_0);
  92229. break;
  92230. }
  92231. /* Step 3 */
  92232. switch( z[0] ){
  92233. case 'e':
  92234. stem(&z, "etaci", "ic", m_gt_0) ||
  92235. stem(&z, "evita", "", m_gt_0) ||
  92236. stem(&z, "ezila", "al", m_gt_0);
  92237. break;
  92238. case 'i':
  92239. stem(&z, "itici", "ic", m_gt_0);
  92240. break;
  92241. case 'l':
  92242. stem(&z, "laci", "ic", m_gt_0) ||
  92243. stem(&z, "luf", "", m_gt_0);
  92244. break;
  92245. case 's':
  92246. stem(&z, "ssen", "", m_gt_0);
  92247. break;
  92248. }
  92249. /* Step 4 */
  92250. switch( z[1] ){
  92251. case 'a':
  92252. if( z[0]=='l' && m_gt_1(z+2) ){
  92253. z += 2;
  92254. }
  92255. break;
  92256. case 'c':
  92257. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  92258. z += 4;
  92259. }
  92260. break;
  92261. case 'e':
  92262. if( z[0]=='r' && m_gt_1(z+2) ){
  92263. z += 2;
  92264. }
  92265. break;
  92266. case 'i':
  92267. if( z[0]=='c' && m_gt_1(z+2) ){
  92268. z += 2;
  92269. }
  92270. break;
  92271. case 'l':
  92272. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  92273. z += 4;
  92274. }
  92275. break;
  92276. case 'n':
  92277. if( z[0]=='t' ){
  92278. if( z[2]=='a' ){
  92279. if( m_gt_1(z+3) ){
  92280. z += 3;
  92281. }
  92282. }else if( z[2]=='e' ){
  92283. stem(&z, "tneme", "", m_gt_1) ||
  92284. stem(&z, "tnem", "", m_gt_1) ||
  92285. stem(&z, "tne", "", m_gt_1);
  92286. }
  92287. }
  92288. break;
  92289. case 'o':
  92290. if( z[0]=='u' ){
  92291. if( m_gt_1(z+2) ){
  92292. z += 2;
  92293. }
  92294. }else if( z[3]=='s' || z[3]=='t' ){
  92295. stem(&z, "noi", "", m_gt_1);
  92296. }
  92297. break;
  92298. case 's':
  92299. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  92300. z += 3;
  92301. }
  92302. break;
  92303. case 't':
  92304. stem(&z, "eta", "", m_gt_1) ||
  92305. stem(&z, "iti", "", m_gt_1);
  92306. break;
  92307. case 'u':
  92308. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  92309. z += 3;
  92310. }
  92311. break;
  92312. case 'v':
  92313. case 'z':
  92314. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  92315. z += 3;
  92316. }
  92317. break;
  92318. }
  92319. /* Step 5a */
  92320. if( z[0]=='e' ){
  92321. if( m_gt_1(z+1) ){
  92322. z++;
  92323. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  92324. z++;
  92325. }
  92326. }
  92327. /* Step 5b */
  92328. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  92329. z++;
  92330. }
  92331. /* z[] is now the stemmed word in reverse order. Flip it back
  92332. ** around into forward order and return.
  92333. */
  92334. *pnOut = i = strlen(z);
  92335. zOut[i] = 0;
  92336. while( *z ){
  92337. zOut[--i] = *(z++);
  92338. }
  92339. }
  92340. /*
  92341. ** Characters that can be part of a token. We assume any character
  92342. ** whose value is greater than 0x80 (any UTF character) can be
  92343. ** part of a token. In other words, delimiters all must have
  92344. ** values of 0x7f or lower.
  92345. */
  92346. static const char porterIdChar[] = {
  92347. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  92348. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  92349. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  92350. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  92351. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  92352. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  92353. };
  92354. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  92355. /*
  92356. ** Extract the next token from a tokenization cursor. The cursor must
  92357. ** have been opened by a prior call to porterOpen().
  92358. */
  92359. static int porterNext(
  92360. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  92361. const char **pzToken, /* OUT: *pzToken is the token text */
  92362. int *pnBytes, /* OUT: Number of bytes in token */
  92363. int *piStartOffset, /* OUT: Starting offset of token */
  92364. int *piEndOffset, /* OUT: Ending offset of token */
  92365. int *piPosition /* OUT: Position integer of token */
  92366. ){
  92367. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  92368. const char *z = c->zInput;
  92369. while( c->iOffset<c->nInput ){
  92370. int iStartOffset, ch;
  92371. /* Scan past delimiter characters */
  92372. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  92373. c->iOffset++;
  92374. }
  92375. /* Count non-delimiter characters. */
  92376. iStartOffset = c->iOffset;
  92377. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  92378. c->iOffset++;
  92379. }
  92380. if( c->iOffset>iStartOffset ){
  92381. int n = c->iOffset-iStartOffset;
  92382. if( n>c->nAllocated ){
  92383. c->nAllocated = n+20;
  92384. c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
  92385. if( c->zToken==NULL ) return SQLITE_NOMEM;
  92386. }
  92387. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  92388. *pzToken = c->zToken;
  92389. *piStartOffset = iStartOffset;
  92390. *piEndOffset = c->iOffset;
  92391. *piPosition = c->iToken++;
  92392. return SQLITE_OK;
  92393. }
  92394. }
  92395. return SQLITE_DONE;
  92396. }
  92397. /*
  92398. ** The set of routines that implement the porter-stemmer tokenizer
  92399. */
  92400. static const sqlite3_tokenizer_module porterTokenizerModule = {
  92401. 0,
  92402. porterCreate,
  92403. porterDestroy,
  92404. porterOpen,
  92405. porterClose,
  92406. porterNext,
  92407. };
  92408. /*
  92409. ** Allocate a new porter tokenizer. Return a pointer to the new
  92410. ** tokenizer in *ppModule
  92411. */
  92412. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  92413. sqlite3_tokenizer_module const**ppModule
  92414. ){
  92415. *ppModule = &porterTokenizerModule;
  92416. }
  92417. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  92418. /************** End of fts3_porter.c *****************************************/
  92419. /************** Begin file fts3_tokenizer.c **********************************/
  92420. /*
  92421. ** 2007 June 22
  92422. **
  92423. ** The author disclaims copyright to this source code. In place of
  92424. ** a legal notice, here is a blessing:
  92425. **
  92426. ** May you do good and not evil.
  92427. ** May you find forgiveness for yourself and forgive others.
  92428. ** May you share freely, never taking more than you give.
  92429. **
  92430. ******************************************************************************
  92431. **
  92432. ** This is part of an SQLite module implementing full-text search.
  92433. ** This particular file implements the generic tokenizer interface.
  92434. */
  92435. /*
  92436. ** The code in this file is only compiled if:
  92437. **
  92438. ** * The FTS3 module is being built as an extension
  92439. ** (in which case SQLITE_CORE is not defined), or
  92440. **
  92441. ** * The FTS3 module is being built into the core of
  92442. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  92443. */
  92444. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  92445. #ifndef SQLITE_CORE
  92446. SQLITE_EXTENSION_INIT1
  92447. #endif
  92448. /*
  92449. ** Implementation of the SQL scalar function for accessing the underlying
  92450. ** hash table. This function may be called as follows:
  92451. **
  92452. ** SELECT <function-name>(<key-name>);
  92453. ** SELECT <function-name>(<key-name>, <pointer>);
  92454. **
  92455. ** where <function-name> is the name passed as the second argument
  92456. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  92457. **
  92458. ** If the <pointer> argument is specified, it must be a blob value
  92459. ** containing a pointer to be stored as the hash data corresponding
  92460. ** to the string <key-name>. If <pointer> is not specified, then
  92461. ** the string <key-name> must already exist in the has table. Otherwise,
  92462. ** an error is returned.
  92463. **
  92464. ** Whether or not the <pointer> argument is specified, the value returned
  92465. ** is a blob containing the pointer stored as the hash data corresponding
  92466. ** to string <key-name> (after the hash-table is updated, if applicable).
  92467. */
  92468. static void scalarFunc(
  92469. sqlite3_context *context,
  92470. int argc,
  92471. sqlite3_value **argv
  92472. ){
  92473. fts3Hash *pHash;
  92474. void *pPtr = 0;
  92475. const unsigned char *zName;
  92476. int nName;
  92477. assert( argc==1 || argc==2 );
  92478. pHash = (fts3Hash *)sqlite3_user_data(context);
  92479. zName = sqlite3_value_text(argv[0]);
  92480. nName = sqlite3_value_bytes(argv[0])+1;
  92481. if( argc==2 ){
  92482. void *pOld;
  92483. int n = sqlite3_value_bytes(argv[1]);
  92484. if( n!=sizeof(pPtr) ){
  92485. sqlite3_result_error(context, "argument type mismatch", -1);
  92486. return;
  92487. }
  92488. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  92489. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  92490. if( pOld==pPtr ){
  92491. sqlite3_result_error(context, "out of memory", -1);
  92492. return;
  92493. }
  92494. }else{
  92495. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  92496. if( !pPtr ){
  92497. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  92498. sqlite3_result_error(context, zErr, -1);
  92499. sqlite3_free(zErr);
  92500. return;
  92501. }
  92502. }
  92503. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  92504. }
  92505. #ifdef SQLITE_TEST
  92506. /*
  92507. ** Implementation of a special SQL scalar function for testing tokenizers
  92508. ** designed to be used in concert with the Tcl testing framework. This
  92509. ** function must be called with two arguments:
  92510. **
  92511. ** SELECT <function-name>(<key-name>, <input-string>);
  92512. ** SELECT <function-name>(<key-name>, <pointer>);
  92513. **
  92514. ** where <function-name> is the name passed as the second argument
  92515. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  92516. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  92517. **
  92518. ** The return value is a string that may be interpreted as a Tcl
  92519. ** list. For each token in the <input-string>, three elements are
  92520. ** added to the returned list. The first is the token position, the
  92521. ** second is the token text (folded, stemmed, etc.) and the third is the
  92522. ** substring of <input-string> associated with the token. For example,
  92523. ** using the built-in "simple" tokenizer:
  92524. **
  92525. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  92526. **
  92527. ** will return the string:
  92528. **
  92529. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  92530. **
  92531. */
  92532. static void testFunc(
  92533. sqlite3_context *context,
  92534. int argc,
  92535. sqlite3_value **argv
  92536. ){
  92537. fts3Hash *pHash;
  92538. sqlite3_tokenizer_module *p;
  92539. sqlite3_tokenizer *pTokenizer = 0;
  92540. sqlite3_tokenizer_cursor *pCsr = 0;
  92541. const char *zErr = 0;
  92542. const char *zName;
  92543. int nName;
  92544. const char *zInput;
  92545. int nInput;
  92546. const char *zArg = 0;
  92547. const char *zToken;
  92548. int nToken;
  92549. int iStart;
  92550. int iEnd;
  92551. int iPos;
  92552. Tcl_Obj *pRet;
  92553. assert( argc==2 || argc==3 );
  92554. nName = sqlite3_value_bytes(argv[0]);
  92555. zName = (const char *)sqlite3_value_text(argv[0]);
  92556. nInput = sqlite3_value_bytes(argv[argc-1]);
  92557. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  92558. if( argc==3 ){
  92559. zArg = (const char *)sqlite3_value_text(argv[1]);
  92560. }
  92561. pHash = (fts3Hash *)sqlite3_user_data(context);
  92562. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  92563. if( !p ){
  92564. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  92565. sqlite3_result_error(context, zErr, -1);
  92566. sqlite3_free(zErr);
  92567. return;
  92568. }
  92569. pRet = Tcl_NewObj();
  92570. Tcl_IncrRefCount(pRet);
  92571. if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
  92572. zErr = "error in xCreate()";
  92573. goto finish;
  92574. }
  92575. pTokenizer->pModule = p;
  92576. if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
  92577. zErr = "error in xOpen()";
  92578. goto finish;
  92579. }
  92580. pCsr->pTokenizer = pTokenizer;
  92581. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  92582. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  92583. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  92584. zToken = &zInput[iStart];
  92585. nToken = iEnd-iStart;
  92586. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  92587. }
  92588. if( SQLITE_OK!=p->xClose(pCsr) ){
  92589. zErr = "error in xClose()";
  92590. goto finish;
  92591. }
  92592. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  92593. zErr = "error in xDestroy()";
  92594. goto finish;
  92595. }
  92596. finish:
  92597. if( zErr ){
  92598. sqlite3_result_error(context, zErr, -1);
  92599. }else{
  92600. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  92601. }
  92602. Tcl_DecrRefCount(pRet);
  92603. }
  92604. static
  92605. int registerTokenizer(
  92606. sqlite3 *db,
  92607. char *zName,
  92608. const sqlite3_tokenizer_module *p
  92609. ){
  92610. int rc;
  92611. sqlite3_stmt *pStmt;
  92612. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  92613. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  92614. if( rc!=SQLITE_OK ){
  92615. return rc;
  92616. }
  92617. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  92618. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  92619. sqlite3_step(pStmt);
  92620. return sqlite3_finalize(pStmt);
  92621. }
  92622. static
  92623. int queryTokenizer(
  92624. sqlite3 *db,
  92625. char *zName,
  92626. const sqlite3_tokenizer_module **pp
  92627. ){
  92628. int rc;
  92629. sqlite3_stmt *pStmt;
  92630. const char zSql[] = "SELECT fts3_tokenizer(?)";
  92631. *pp = 0;
  92632. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  92633. if( rc!=SQLITE_OK ){
  92634. return rc;
  92635. }
  92636. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  92637. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  92638. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  92639. memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  92640. }
  92641. }
  92642. return sqlite3_finalize(pStmt);
  92643. }
  92644. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  92645. /*
  92646. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  92647. ** This function is used for testing only, it is not included in the
  92648. ** build unless SQLITE_TEST is defined.
  92649. **
  92650. ** The purpose of this is to test that the fts3_tokenizer() function
  92651. ** can be used as designed by the C-code in the queryTokenizer and
  92652. ** registerTokenizer() functions above. These two functions are repeated
  92653. ** in the README.tokenizer file as an example, so it is important to
  92654. ** test them.
  92655. **
  92656. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  92657. ** function with no arguments. An assert() will fail if a problem is
  92658. ** detected. i.e.:
  92659. **
  92660. ** SELECT fts3_tokenizer_internal_test();
  92661. **
  92662. */
  92663. static void intTestFunc(
  92664. sqlite3_context *context,
  92665. int argc,
  92666. sqlite3_value **argv
  92667. ){
  92668. int rc;
  92669. const sqlite3_tokenizer_module *p1;
  92670. const sqlite3_tokenizer_module *p2;
  92671. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  92672. /* Test the query function */
  92673. sqlite3Fts3SimpleTokenizerModule(&p1);
  92674. rc = queryTokenizer(db, "simple", &p2);
  92675. assert( rc==SQLITE_OK );
  92676. assert( p1==p2 );
  92677. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  92678. assert( rc==SQLITE_ERROR );
  92679. assert( p2==0 );
  92680. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  92681. /* Test the storage function */
  92682. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  92683. assert( rc==SQLITE_OK );
  92684. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  92685. assert( rc==SQLITE_OK );
  92686. assert( p2==p1 );
  92687. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  92688. }
  92689. #endif
  92690. /*
  92691. ** Set up SQL objects in database db used to access the contents of
  92692. ** the hash table pointed to by argument pHash. The hash table must
  92693. ** been initialised to use string keys, and to take a private copy
  92694. ** of the key when a value is inserted. i.e. by a call similar to:
  92695. **
  92696. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  92697. **
  92698. ** This function adds a scalar function (see header comment above
  92699. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  92700. ** defined at compilation time, a temporary virtual table (see header
  92701. ** comment above struct HashTableVtab) to the database schema. Both
  92702. ** provide read/write access to the contents of *pHash.
  92703. **
  92704. ** The third argument to this function, zName, is used as the name
  92705. ** of both the scalar and, if created, the virtual table.
  92706. */
  92707. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  92708. sqlite3 *db,
  92709. fts3Hash *pHash,
  92710. const char *zName
  92711. ){
  92712. int rc = SQLITE_OK;
  92713. void *p = (void *)pHash;
  92714. const int any = SQLITE_ANY;
  92715. char *zTest = 0;
  92716. char *zTest2 = 0;
  92717. #ifdef SQLITE_TEST
  92718. void *pdb = (void *)db;
  92719. zTest = sqlite3_mprintf("%s_test", zName);
  92720. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  92721. if( !zTest || !zTest2 ){
  92722. rc = SQLITE_NOMEM;
  92723. }
  92724. #endif
  92725. if( rc!=SQLITE_OK
  92726. || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
  92727. || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
  92728. #ifdef SQLITE_TEST
  92729. || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
  92730. || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
  92731. || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
  92732. #endif
  92733. );
  92734. sqlite3_free(zTest);
  92735. sqlite3_free(zTest2);
  92736. return rc;
  92737. }
  92738. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  92739. /************** End of fts3_tokenizer.c **************************************/
  92740. /************** Begin file fts3_tokenizer1.c *********************************/
  92741. /*
  92742. ** 2006 Oct 10
  92743. **
  92744. ** The author disclaims copyright to this source code. In place of
  92745. ** a legal notice, here is a blessing:
  92746. **
  92747. ** May you do good and not evil.
  92748. ** May you find forgiveness for yourself and forgive others.
  92749. ** May you share freely, never taking more than you give.
  92750. **
  92751. ******************************************************************************
  92752. **
  92753. ** Implementation of the "simple" full-text-search tokenizer.
  92754. */
  92755. /*
  92756. ** The code in this file is only compiled if:
  92757. **
  92758. ** * The FTS3 module is being built as an extension
  92759. ** (in which case SQLITE_CORE is not defined), or
  92760. **
  92761. ** * The FTS3 module is being built into the core of
  92762. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  92763. */
  92764. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  92765. typedef struct simple_tokenizer {
  92766. sqlite3_tokenizer base;
  92767. char delim[128]; /* flag ASCII delimiters */
  92768. } simple_tokenizer;
  92769. typedef struct simple_tokenizer_cursor {
  92770. sqlite3_tokenizer_cursor base;
  92771. const char *pInput; /* input we are tokenizing */
  92772. int nBytes; /* size of the input */
  92773. int iOffset; /* current position in pInput */
  92774. int iToken; /* index of next token to be returned */
  92775. char *pToken; /* storage for current token */
  92776. int nTokenAllocated; /* space allocated to zToken buffer */
  92777. } simple_tokenizer_cursor;
  92778. /* Forward declaration */
  92779. static const sqlite3_tokenizer_module simpleTokenizerModule;
  92780. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  92781. return c<0x80 && t->delim[c];
  92782. }
  92783. /*
  92784. ** Create a new tokenizer instance.
  92785. */
  92786. static int simpleCreate(
  92787. int argc, const char * const *argv,
  92788. sqlite3_tokenizer **ppTokenizer
  92789. ){
  92790. simple_tokenizer *t;
  92791. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  92792. if( t==NULL ) return SQLITE_NOMEM;
  92793. memset(t, 0, sizeof(*t));
  92794. /* TODO(shess) Delimiters need to remain the same from run to run,
  92795. ** else we need to reindex. One solution would be a meta-table to
  92796. ** track such information in the database, then we'd only want this
  92797. ** information on the initial create.
  92798. */
  92799. if( argc>1 ){
  92800. int i, n = strlen(argv[1]);
  92801. for(i=0; i<n; i++){
  92802. unsigned char ch = argv[1][i];
  92803. /* We explicitly don't support UTF-8 delimiters for now. */
  92804. if( ch>=0x80 ){
  92805. sqlite3_free(t);
  92806. return SQLITE_ERROR;
  92807. }
  92808. t->delim[ch] = 1;
  92809. }
  92810. } else {
  92811. /* Mark non-alphanumeric ASCII characters as delimiters */
  92812. int i;
  92813. for(i=1; i<0x80; i++){
  92814. t->delim[i] = !isalnum(i);
  92815. }
  92816. }
  92817. *ppTokenizer = &t->base;
  92818. return SQLITE_OK;
  92819. }
  92820. /*
  92821. ** Destroy a tokenizer
  92822. */
  92823. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  92824. sqlite3_free(pTokenizer);
  92825. return SQLITE_OK;
  92826. }
  92827. /*
  92828. ** Prepare to begin tokenizing a particular string. The input
  92829. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  92830. ** used to incrementally tokenize this string is returned in
  92831. ** *ppCursor.
  92832. */
  92833. static int simpleOpen(
  92834. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  92835. const char *pInput, int nBytes, /* String to be tokenized */
  92836. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  92837. ){
  92838. simple_tokenizer_cursor *c;
  92839. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  92840. if( c==NULL ) return SQLITE_NOMEM;
  92841. c->pInput = pInput;
  92842. if( pInput==0 ){
  92843. c->nBytes = 0;
  92844. }else if( nBytes<0 ){
  92845. c->nBytes = (int)strlen(pInput);
  92846. }else{
  92847. c->nBytes = nBytes;
  92848. }
  92849. c->iOffset = 0; /* start tokenizing at the beginning */
  92850. c->iToken = 0;
  92851. c->pToken = NULL; /* no space allocated, yet. */
  92852. c->nTokenAllocated = 0;
  92853. *ppCursor = &c->base;
  92854. return SQLITE_OK;
  92855. }
  92856. /*
  92857. ** Close a tokenization cursor previously opened by a call to
  92858. ** simpleOpen() above.
  92859. */
  92860. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  92861. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  92862. sqlite3_free(c->pToken);
  92863. sqlite3_free(c);
  92864. return SQLITE_OK;
  92865. }
  92866. /*
  92867. ** Extract the next token from a tokenization cursor. The cursor must
  92868. ** have been opened by a prior call to simpleOpen().
  92869. */
  92870. static int simpleNext(
  92871. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  92872. const char **ppToken, /* OUT: *ppToken is the token text */
  92873. int *pnBytes, /* OUT: Number of bytes in token */
  92874. int *piStartOffset, /* OUT: Starting offset of token */
  92875. int *piEndOffset, /* OUT: Ending offset of token */
  92876. int *piPosition /* OUT: Position integer of token */
  92877. ){
  92878. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  92879. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  92880. unsigned char *p = (unsigned char *)c->pInput;
  92881. while( c->iOffset<c->nBytes ){
  92882. int iStartOffset;
  92883. /* Scan past delimiter characters */
  92884. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  92885. c->iOffset++;
  92886. }
  92887. /* Count non-delimiter characters. */
  92888. iStartOffset = c->iOffset;
  92889. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  92890. c->iOffset++;
  92891. }
  92892. if( c->iOffset>iStartOffset ){
  92893. int i, n = c->iOffset-iStartOffset;
  92894. if( n>c->nTokenAllocated ){
  92895. c->nTokenAllocated = n+20;
  92896. c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  92897. if( c->pToken==NULL ) return SQLITE_NOMEM;
  92898. }
  92899. for(i=0; i<n; i++){
  92900. /* TODO(shess) This needs expansion to handle UTF-8
  92901. ** case-insensitivity.
  92902. */
  92903. unsigned char ch = p[iStartOffset+i];
  92904. c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
  92905. }
  92906. *ppToken = c->pToken;
  92907. *pnBytes = n;
  92908. *piStartOffset = iStartOffset;
  92909. *piEndOffset = c->iOffset;
  92910. *piPosition = c->iToken++;
  92911. return SQLITE_OK;
  92912. }
  92913. }
  92914. return SQLITE_DONE;
  92915. }
  92916. /*
  92917. ** The set of routines that implement the simple tokenizer
  92918. */
  92919. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  92920. 0,
  92921. simpleCreate,
  92922. simpleDestroy,
  92923. simpleOpen,
  92924. simpleClose,
  92925. simpleNext,
  92926. };
  92927. /*
  92928. ** Allocate a new simple tokenizer. Return a pointer to the new
  92929. ** tokenizer in *ppModule
  92930. */
  92931. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  92932. sqlite3_tokenizer_module const**ppModule
  92933. ){
  92934. *ppModule = &simpleTokenizerModule;
  92935. }
  92936. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  92937. /************** End of fts3_tokenizer1.c *************************************/
  92938. /************** Begin file rtree.c *******************************************/
  92939. /*
  92940. ** 2001 September 15
  92941. **
  92942. ** The author disclaims copyright to this source code. In place of
  92943. ** a legal notice, here is a blessing:
  92944. **
  92945. ** May you do good and not evil.
  92946. ** May you find forgiveness for yourself and forgive others.
  92947. ** May you share freely, never taking more than you give.
  92948. **
  92949. *************************************************************************
  92950. ** This file contains code for implementations of the r-tree and r*-tree
  92951. ** algorithms packaged as an SQLite virtual table module.
  92952. **
  92953. ** $Id: rtree.c,v 1.12 2008/12/22 15:04:32 danielk1977 Exp $
  92954. */
  92955. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  92956. /*
  92957. ** This file contains an implementation of a couple of different variants
  92958. ** of the r-tree algorithm. See the README file for further details. The
  92959. ** same data-structure is used for all, but the algorithms for insert and
  92960. ** delete operations vary. The variants used are selected at compile time
  92961. ** by defining the following symbols:
  92962. */
  92963. /* Either, both or none of the following may be set to activate
  92964. ** r*tree variant algorithms.
  92965. */
  92966. #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
  92967. #define VARIANT_RSTARTREE_REINSERT 1
  92968. /*
  92969. ** Exactly one of the following must be set to 1.
  92970. */
  92971. #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
  92972. #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
  92973. #define VARIANT_RSTARTREE_SPLIT 1
  92974. #define VARIANT_GUTTMAN_SPLIT \
  92975. (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
  92976. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  92977. #define PickNext QuadraticPickNext
  92978. #define PickSeeds QuadraticPickSeeds
  92979. #define AssignCells splitNodeGuttman
  92980. #endif
  92981. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  92982. #define PickNext LinearPickNext
  92983. #define PickSeeds LinearPickSeeds
  92984. #define AssignCells splitNodeGuttman
  92985. #endif
  92986. #if VARIANT_RSTARTREE_SPLIT
  92987. #define AssignCells splitNodeStartree
  92988. #endif
  92989. #ifndef SQLITE_CORE
  92990. SQLITE_EXTENSION_INIT1
  92991. #else
  92992. #endif
  92993. #ifndef SQLITE_AMALGAMATION
  92994. typedef sqlite3_int64 i64;
  92995. typedef unsigned char u8;
  92996. typedef unsigned int u32;
  92997. #endif
  92998. typedef struct Rtree Rtree;
  92999. typedef struct RtreeCursor RtreeCursor;
  93000. typedef struct RtreeNode RtreeNode;
  93001. typedef struct RtreeCell RtreeCell;
  93002. typedef struct RtreeConstraint RtreeConstraint;
  93003. typedef union RtreeCoord RtreeCoord;
  93004. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  93005. #define RTREE_MAX_DIMENSIONS 5
  93006. /* Size of hash table Rtree.aHash. This hash table is not expected to
  93007. ** ever contain very many entries, so a fixed number of buckets is
  93008. ** used.
  93009. */
  93010. #define HASHSIZE 128
  93011. /*
  93012. ** An rtree virtual-table object.
  93013. */
  93014. struct Rtree {
  93015. sqlite3_vtab base;
  93016. sqlite3 *db; /* Host database connection */
  93017. int iNodeSize; /* Size in bytes of each node in the node table */
  93018. int nDim; /* Number of dimensions */
  93019. int nBytesPerCell; /* Bytes consumed per cell */
  93020. int iDepth; /* Current depth of the r-tree structure */
  93021. char *zDb; /* Name of database containing r-tree table */
  93022. char *zName; /* Name of r-tree table */
  93023. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  93024. int nBusy; /* Current number of users of this structure */
  93025. /* List of nodes removed during a CondenseTree operation. List is
  93026. ** linked together via the pointer normally used for hash chains -
  93027. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  93028. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  93029. */
  93030. RtreeNode *pDeleted;
  93031. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  93032. /* Statements to read/write/delete a record from xxx_node */
  93033. sqlite3_stmt *pReadNode;
  93034. sqlite3_stmt *pWriteNode;
  93035. sqlite3_stmt *pDeleteNode;
  93036. /* Statements to read/write/delete a record from xxx_rowid */
  93037. sqlite3_stmt *pReadRowid;
  93038. sqlite3_stmt *pWriteRowid;
  93039. sqlite3_stmt *pDeleteRowid;
  93040. /* Statements to read/write/delete a record from xxx_parent */
  93041. sqlite3_stmt *pReadParent;
  93042. sqlite3_stmt *pWriteParent;
  93043. sqlite3_stmt *pDeleteParent;
  93044. int eCoordType;
  93045. };
  93046. /* Possible values for eCoordType: */
  93047. #define RTREE_COORD_REAL32 0
  93048. #define RTREE_COORD_INT32 1
  93049. /*
  93050. ** The minimum number of cells allowed for a node is a third of the
  93051. ** maximum. In Gutman's notation:
  93052. **
  93053. ** m = M/3
  93054. **
  93055. ** If an R*-tree "Reinsert" operation is required, the same number of
  93056. ** cells are removed from the overfull node and reinserted into the tree.
  93057. */
  93058. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  93059. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  93060. #define RTREE_MAXCELLS 51
  93061. /*
  93062. ** An rtree cursor object.
  93063. */
  93064. struct RtreeCursor {
  93065. sqlite3_vtab_cursor base;
  93066. RtreeNode *pNode; /* Node cursor is currently pointing at */
  93067. int iCell; /* Index of current cell in pNode */
  93068. int iStrategy; /* Copy of idxNum search parameter */
  93069. int nConstraint; /* Number of entries in aConstraint */
  93070. RtreeConstraint *aConstraint; /* Search constraints. */
  93071. };
  93072. union RtreeCoord {
  93073. float f;
  93074. int i;
  93075. };
  93076. /*
  93077. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  93078. ** formatted as a double. This macro assumes that local variable pRtree points
  93079. ** to the Rtree structure associated with the RtreeCoord.
  93080. */
  93081. #define DCOORD(coord) ( \
  93082. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  93083. ((double)coord.f) : \
  93084. ((double)coord.i) \
  93085. )
  93086. /*
  93087. ** A search constraint.
  93088. */
  93089. struct RtreeConstraint {
  93090. int iCoord; /* Index of constrained coordinate */
  93091. int op; /* Constraining operation */
  93092. double rValue; /* Constraint value. */
  93093. };
  93094. /* Possible values for RtreeConstraint.op */
  93095. #define RTREE_EQ 0x41
  93096. #define RTREE_LE 0x42
  93097. #define RTREE_LT 0x43
  93098. #define RTREE_GE 0x44
  93099. #define RTREE_GT 0x45
  93100. /*
  93101. ** An rtree structure node.
  93102. **
  93103. ** Data format (RtreeNode.zData):
  93104. **
  93105. ** 1. If the node is the root node (node 1), then the first 2 bytes
  93106. ** of the node contain the tree depth as a big-endian integer.
  93107. ** For non-root nodes, the first 2 bytes are left unused.
  93108. **
  93109. ** 2. The next 2 bytes contain the number of entries currently
  93110. ** stored in the node.
  93111. **
  93112. ** 3. The remainder of the node contains the node entries. Each entry
  93113. ** consists of a single 8-byte integer followed by an even number
  93114. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  93115. ** of a record. For internal nodes it is the node number of a
  93116. ** child page.
  93117. */
  93118. struct RtreeNode {
  93119. RtreeNode *pParent; /* Parent node */
  93120. i64 iNode;
  93121. int nRef;
  93122. int isDirty;
  93123. u8 *zData;
  93124. RtreeNode *pNext; /* Next node in this hash chain */
  93125. };
  93126. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  93127. /*
  93128. ** Structure to store a deserialized rtree record.
  93129. */
  93130. struct RtreeCell {
  93131. i64 iRowid;
  93132. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
  93133. };
  93134. #ifndef MAX
  93135. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  93136. #endif
  93137. #ifndef MIN
  93138. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  93139. #endif
  93140. /*
  93141. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  93142. ** 64 bit integer. The deserialized value is returned.
  93143. */
  93144. static int readInt16(u8 *p){
  93145. return (p[0]<<8) + p[1];
  93146. }
  93147. static void readCoord(u8 *p, RtreeCoord *pCoord){
  93148. u32 i = (
  93149. (((u32)p[0]) << 24) +
  93150. (((u32)p[1]) << 16) +
  93151. (((u32)p[2]) << 8) +
  93152. (((u32)p[3]) << 0)
  93153. );
  93154. *(u32 *)pCoord = i;
  93155. }
  93156. static i64 readInt64(u8 *p){
  93157. return (
  93158. (((i64)p[0]) << 56) +
  93159. (((i64)p[1]) << 48) +
  93160. (((i64)p[2]) << 40) +
  93161. (((i64)p[3]) << 32) +
  93162. (((i64)p[4]) << 24) +
  93163. (((i64)p[5]) << 16) +
  93164. (((i64)p[6]) << 8) +
  93165. (((i64)p[7]) << 0)
  93166. );
  93167. }
  93168. /*
  93169. ** Functions to serialize a 16 bit integer, 32 bit real number and
  93170. ** 64 bit integer. The value returned is the number of bytes written
  93171. ** to the argument buffer (always 2, 4 and 8 respectively).
  93172. */
  93173. static int writeInt16(u8 *p, int i){
  93174. p[0] = (i>> 8)&0xFF;
  93175. p[1] = (i>> 0)&0xFF;
  93176. return 2;
  93177. }
  93178. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  93179. u32 i;
  93180. assert( sizeof(RtreeCoord)==4 );
  93181. assert( sizeof(u32)==4 );
  93182. i = *(u32 *)pCoord;
  93183. p[0] = (i>>24)&0xFF;
  93184. p[1] = (i>>16)&0xFF;
  93185. p[2] = (i>> 8)&0xFF;
  93186. p[3] = (i>> 0)&0xFF;
  93187. return 4;
  93188. }
  93189. static int writeInt64(u8 *p, i64 i){
  93190. p[0] = (i>>56)&0xFF;
  93191. p[1] = (i>>48)&0xFF;
  93192. p[2] = (i>>40)&0xFF;
  93193. p[3] = (i>>32)&0xFF;
  93194. p[4] = (i>>24)&0xFF;
  93195. p[5] = (i>>16)&0xFF;
  93196. p[6] = (i>> 8)&0xFF;
  93197. p[7] = (i>> 0)&0xFF;
  93198. return 8;
  93199. }
  93200. /*
  93201. ** Increment the reference count of node p.
  93202. */
  93203. static void nodeReference(RtreeNode *p){
  93204. if( p ){
  93205. p->nRef++;
  93206. }
  93207. }
  93208. /*
  93209. ** Clear the content of node p (set all bytes to 0x00).
  93210. */
  93211. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  93212. if( p ){
  93213. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  93214. p->isDirty = 1;
  93215. }
  93216. }
  93217. /*
  93218. ** Given a node number iNode, return the corresponding key to use
  93219. ** in the Rtree.aHash table.
  93220. */
  93221. static int nodeHash(i64 iNode){
  93222. return (
  93223. (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
  93224. (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  93225. ) % HASHSIZE;
  93226. }
  93227. /*
  93228. ** Search the node hash table for node iNode. If found, return a pointer
  93229. ** to it. Otherwise, return 0.
  93230. */
  93231. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  93232. RtreeNode *p;
  93233. assert( iNode!=0 );
  93234. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  93235. return p;
  93236. }
  93237. /*
  93238. ** Add node pNode to the node hash table.
  93239. */
  93240. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  93241. if( pNode ){
  93242. int iHash;
  93243. assert( pNode->pNext==0 );
  93244. iHash = nodeHash(pNode->iNode);
  93245. pNode->pNext = pRtree->aHash[iHash];
  93246. pRtree->aHash[iHash] = pNode;
  93247. }
  93248. }
  93249. /*
  93250. ** Remove node pNode from the node hash table.
  93251. */
  93252. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  93253. RtreeNode **pp;
  93254. if( pNode->iNode!=0 ){
  93255. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  93256. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  93257. *pp = pNode->pNext;
  93258. pNode->pNext = 0;
  93259. }
  93260. }
  93261. /*
  93262. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  93263. ** indicating that node has not yet been assigned a node number. It is
  93264. ** assigned a node number when nodeWrite() is called to write the
  93265. ** node contents out to the database.
  93266. */
  93267. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
  93268. RtreeNode *pNode;
  93269. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  93270. if( pNode ){
  93271. memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
  93272. pNode->zData = (u8 *)&pNode[1];
  93273. pNode->nRef = 1;
  93274. pNode->pParent = pParent;
  93275. pNode->isDirty = 1;
  93276. nodeReference(pParent);
  93277. }
  93278. return pNode;
  93279. }
  93280. /*
  93281. ** Obtain a reference to an r-tree node.
  93282. */
  93283. static int
  93284. nodeAcquire(
  93285. Rtree *pRtree, /* R-tree structure */
  93286. i64 iNode, /* Node number to load */
  93287. RtreeNode *pParent, /* Either the parent node or NULL */
  93288. RtreeNode **ppNode /* OUT: Acquired node */
  93289. ){
  93290. int rc;
  93291. RtreeNode *pNode;
  93292. /* Check if the requested node is already in the hash table. If so,
  93293. ** increase its reference count and return it.
  93294. */
  93295. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  93296. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  93297. if( pParent && !pNode->pParent ){
  93298. nodeReference(pParent);
  93299. pNode->pParent = pParent;
  93300. }
  93301. pNode->nRef++;
  93302. *ppNode = pNode;
  93303. return SQLITE_OK;
  93304. }
  93305. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  93306. if( !pNode ){
  93307. *ppNode = 0;
  93308. return SQLITE_NOMEM;
  93309. }
  93310. pNode->pParent = pParent;
  93311. pNode->zData = (u8 *)&pNode[1];
  93312. pNode->nRef = 1;
  93313. pNode->iNode = iNode;
  93314. pNode->isDirty = 0;
  93315. pNode->pNext = 0;
  93316. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  93317. rc = sqlite3_step(pRtree->pReadNode);
  93318. if( rc==SQLITE_ROW ){
  93319. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  93320. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  93321. nodeReference(pParent);
  93322. }else{
  93323. sqlite3_free(pNode);
  93324. pNode = 0;
  93325. }
  93326. *ppNode = pNode;
  93327. rc = sqlite3_reset(pRtree->pReadNode);
  93328. if( rc==SQLITE_OK && iNode==1 ){
  93329. pRtree->iDepth = readInt16(pNode->zData);
  93330. }
  93331. assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
  93332. nodeHashInsert(pRtree, pNode);
  93333. return rc;
  93334. }
  93335. /*
  93336. ** Overwrite cell iCell of node pNode with the contents of pCell.
  93337. */
  93338. static void nodeOverwriteCell(
  93339. Rtree *pRtree,
  93340. RtreeNode *pNode,
  93341. RtreeCell *pCell,
  93342. int iCell
  93343. ){
  93344. int ii;
  93345. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  93346. p += writeInt64(p, pCell->iRowid);
  93347. for(ii=0; ii<(pRtree->nDim*2); ii++){
  93348. p += writeCoord(p, &pCell->aCoord[ii]);
  93349. }
  93350. pNode->isDirty = 1;
  93351. }
  93352. /*
  93353. ** Remove cell the cell with index iCell from node pNode.
  93354. */
  93355. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  93356. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  93357. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  93358. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  93359. memmove(pDst, pSrc, nByte);
  93360. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  93361. pNode->isDirty = 1;
  93362. }
  93363. /*
  93364. ** Insert the contents of cell pCell into node pNode. If the insert
  93365. ** is successful, return SQLITE_OK.
  93366. **
  93367. ** If there is not enough free space in pNode, return SQLITE_FULL.
  93368. */
  93369. static int
  93370. nodeInsertCell(
  93371. Rtree *pRtree,
  93372. RtreeNode *pNode,
  93373. RtreeCell *pCell
  93374. ){
  93375. int nCell; /* Current number of cells in pNode */
  93376. int nMaxCell; /* Maximum number of cells for pNode */
  93377. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  93378. nCell = NCELL(pNode);
  93379. assert(nCell<=nMaxCell);
  93380. if( nCell<nMaxCell ){
  93381. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  93382. writeInt16(&pNode->zData[2], nCell+1);
  93383. pNode->isDirty = 1;
  93384. }
  93385. return (nCell==nMaxCell);
  93386. }
  93387. /*
  93388. ** If the node is dirty, write it out to the database.
  93389. */
  93390. static int
  93391. nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  93392. int rc = SQLITE_OK;
  93393. if( pNode->isDirty ){
  93394. sqlite3_stmt *p = pRtree->pWriteNode;
  93395. if( pNode->iNode ){
  93396. sqlite3_bind_int64(p, 1, pNode->iNode);
  93397. }else{
  93398. sqlite3_bind_null(p, 1);
  93399. }
  93400. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  93401. sqlite3_step(p);
  93402. pNode->isDirty = 0;
  93403. rc = sqlite3_reset(p);
  93404. if( pNode->iNode==0 && rc==SQLITE_OK ){
  93405. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  93406. nodeHashInsert(pRtree, pNode);
  93407. }
  93408. }
  93409. return rc;
  93410. }
  93411. /*
  93412. ** Release a reference to a node. If the node is dirty and the reference
  93413. ** count drops to zero, the node data is written to the database.
  93414. */
  93415. static int
  93416. nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  93417. int rc = SQLITE_OK;
  93418. if( pNode ){
  93419. assert( pNode->nRef>0 );
  93420. pNode->nRef--;
  93421. if( pNode->nRef==0 ){
  93422. if( pNode->iNode==1 ){
  93423. pRtree->iDepth = -1;
  93424. }
  93425. if( pNode->pParent ){
  93426. rc = nodeRelease(pRtree, pNode->pParent);
  93427. }
  93428. if( rc==SQLITE_OK ){
  93429. rc = nodeWrite(pRtree, pNode);
  93430. }
  93431. nodeHashDelete(pRtree, pNode);
  93432. sqlite3_free(pNode);
  93433. }
  93434. }
  93435. return rc;
  93436. }
  93437. /*
  93438. ** Return the 64-bit integer value associated with cell iCell of
  93439. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  93440. ** an internal node, then the 64-bit integer is a child page number.
  93441. */
  93442. static i64 nodeGetRowid(
  93443. Rtree *pRtree,
  93444. RtreeNode *pNode,
  93445. int iCell
  93446. ){
  93447. assert( iCell<NCELL(pNode) );
  93448. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  93449. }
  93450. /*
  93451. ** Return coordinate iCoord from cell iCell in node pNode.
  93452. */
  93453. static void nodeGetCoord(
  93454. Rtree *pRtree,
  93455. RtreeNode *pNode,
  93456. int iCell,
  93457. int iCoord,
  93458. RtreeCoord *pCoord /* Space to write result to */
  93459. ){
  93460. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  93461. }
  93462. /*
  93463. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  93464. ** to by pCell with the results.
  93465. */
  93466. static void nodeGetCell(
  93467. Rtree *pRtree,
  93468. RtreeNode *pNode,
  93469. int iCell,
  93470. RtreeCell *pCell
  93471. ){
  93472. int ii;
  93473. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  93474. for(ii=0; ii<pRtree->nDim*2; ii++){
  93475. nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  93476. }
  93477. }
  93478. /* Forward declaration for the function that does the work of
  93479. ** the virtual table module xCreate() and xConnect() methods.
  93480. */
  93481. static int rtreeInit(
  93482. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  93483. );
  93484. /*
  93485. ** Rtree virtual table module xCreate method.
  93486. */
  93487. static int rtreeCreate(
  93488. sqlite3 *db,
  93489. void *pAux,
  93490. int argc, const char *const*argv,
  93491. sqlite3_vtab **ppVtab,
  93492. char **pzErr
  93493. ){
  93494. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  93495. }
  93496. /*
  93497. ** Rtree virtual table module xConnect method.
  93498. */
  93499. static int rtreeConnect(
  93500. sqlite3 *db,
  93501. void *pAux,
  93502. int argc, const char *const*argv,
  93503. sqlite3_vtab **ppVtab,
  93504. char **pzErr
  93505. ){
  93506. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  93507. }
  93508. /*
  93509. ** Increment the r-tree reference count.
  93510. */
  93511. static void rtreeReference(Rtree *pRtree){
  93512. pRtree->nBusy++;
  93513. }
  93514. /*
  93515. ** Decrement the r-tree reference count. When the reference count reaches
  93516. ** zero the structure is deleted.
  93517. */
  93518. static void rtreeRelease(Rtree *pRtree){
  93519. pRtree->nBusy--;
  93520. if( pRtree->nBusy==0 ){
  93521. sqlite3_finalize(pRtree->pReadNode);
  93522. sqlite3_finalize(pRtree->pWriteNode);
  93523. sqlite3_finalize(pRtree->pDeleteNode);
  93524. sqlite3_finalize(pRtree->pReadRowid);
  93525. sqlite3_finalize(pRtree->pWriteRowid);
  93526. sqlite3_finalize(pRtree->pDeleteRowid);
  93527. sqlite3_finalize(pRtree->pReadParent);
  93528. sqlite3_finalize(pRtree->pWriteParent);
  93529. sqlite3_finalize(pRtree->pDeleteParent);
  93530. sqlite3_free(pRtree);
  93531. }
  93532. }
  93533. /*
  93534. ** Rtree virtual table module xDisconnect method.
  93535. */
  93536. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  93537. rtreeRelease((Rtree *)pVtab);
  93538. return SQLITE_OK;
  93539. }
  93540. /*
  93541. ** Rtree virtual table module xDestroy method.
  93542. */
  93543. static int rtreeDestroy(sqlite3_vtab *pVtab){
  93544. Rtree *pRtree = (Rtree *)pVtab;
  93545. int rc;
  93546. char *zCreate = sqlite3_mprintf(
  93547. "DROP TABLE '%q'.'%q_node';"
  93548. "DROP TABLE '%q'.'%q_rowid';"
  93549. "DROP TABLE '%q'.'%q_parent';",
  93550. pRtree->zDb, pRtree->zName,
  93551. pRtree->zDb, pRtree->zName,
  93552. pRtree->zDb, pRtree->zName
  93553. );
  93554. if( !zCreate ){
  93555. rc = SQLITE_NOMEM;
  93556. }else{
  93557. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  93558. sqlite3_free(zCreate);
  93559. }
  93560. if( rc==SQLITE_OK ){
  93561. rtreeRelease(pRtree);
  93562. }
  93563. return rc;
  93564. }
  93565. /*
  93566. ** Rtree virtual table module xOpen method.
  93567. */
  93568. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  93569. int rc = SQLITE_NOMEM;
  93570. RtreeCursor *pCsr;
  93571. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  93572. if( pCsr ){
  93573. memset(pCsr, 0, sizeof(RtreeCursor));
  93574. pCsr->base.pVtab = pVTab;
  93575. rc = SQLITE_OK;
  93576. }
  93577. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  93578. return rc;
  93579. }
  93580. /*
  93581. ** Rtree virtual table module xClose method.
  93582. */
  93583. static int rtreeClose(sqlite3_vtab_cursor *cur){
  93584. Rtree *pRtree = (Rtree *)(cur->pVtab);
  93585. int rc;
  93586. RtreeCursor *pCsr = (RtreeCursor *)cur;
  93587. sqlite3_free(pCsr->aConstraint);
  93588. rc = nodeRelease(pRtree, pCsr->pNode);
  93589. sqlite3_free(pCsr);
  93590. return rc;
  93591. }
  93592. /*
  93593. ** Rtree virtual table module xEof method.
  93594. **
  93595. ** Return non-zero if the cursor does not currently point to a valid
  93596. ** record (i.e if the scan has finished), or zero otherwise.
  93597. */
  93598. static int rtreeEof(sqlite3_vtab_cursor *cur){
  93599. RtreeCursor *pCsr = (RtreeCursor *)cur;
  93600. return (pCsr->pNode==0);
  93601. }
  93602. /*
  93603. ** Cursor pCursor currently points to a cell in a non-leaf page.
  93604. ** Return true if the sub-tree headed by the cell is filtered
  93605. ** (excluded) by the constraints in the pCursor->aConstraint[]
  93606. ** array, or false otherwise.
  93607. */
  93608. static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
  93609. RtreeCell cell;
  93610. int ii;
  93611. int bRes = 0;
  93612. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  93613. for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
  93614. RtreeConstraint *p = &pCursor->aConstraint[ii];
  93615. double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
  93616. double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
  93617. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  93618. || p->op==RTREE_GT || p->op==RTREE_EQ
  93619. );
  93620. switch( p->op ){
  93621. case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
  93622. case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
  93623. case RTREE_EQ:
  93624. bRes = (p->rValue>cell_max || p->rValue<cell_min);
  93625. break;
  93626. }
  93627. }
  93628. return bRes;
  93629. }
  93630. /*
  93631. ** Return true if the cell that cursor pCursor currently points to
  93632. ** would be filtered (excluded) by the constraints in the
  93633. ** pCursor->aConstraint[] array, or false otherwise.
  93634. **
  93635. ** This function assumes that the cell is part of a leaf node.
  93636. */
  93637. static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
  93638. RtreeCell cell;
  93639. int ii;
  93640. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  93641. for(ii=0; ii<pCursor->nConstraint; ii++){
  93642. RtreeConstraint *p = &pCursor->aConstraint[ii];
  93643. double coord = DCOORD(cell.aCoord[p->iCoord]);
  93644. int res;
  93645. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  93646. || p->op==RTREE_GT || p->op==RTREE_EQ
  93647. );
  93648. switch( p->op ){
  93649. case RTREE_LE: res = (coord<=p->rValue); break;
  93650. case RTREE_LT: res = (coord<p->rValue); break;
  93651. case RTREE_GE: res = (coord>=p->rValue); break;
  93652. case RTREE_GT: res = (coord>p->rValue); break;
  93653. case RTREE_EQ: res = (coord==p->rValue); break;
  93654. }
  93655. if( !res ) return 1;
  93656. }
  93657. return 0;
  93658. }
  93659. /*
  93660. ** Cursor pCursor currently points at a node that heads a sub-tree of
  93661. ** height iHeight (if iHeight==0, then the node is a leaf). Descend
  93662. ** to point to the left-most cell of the sub-tree that matches the
  93663. ** configured constraints.
  93664. */
  93665. static int descendToCell(
  93666. Rtree *pRtree,
  93667. RtreeCursor *pCursor,
  93668. int iHeight,
  93669. int *pEof /* OUT: Set to true if cannot descend */
  93670. ){
  93671. int isEof;
  93672. int rc;
  93673. int ii;
  93674. RtreeNode *pChild;
  93675. sqlite3_int64 iRowid;
  93676. RtreeNode *pSavedNode = pCursor->pNode;
  93677. int iSavedCell = pCursor->iCell;
  93678. assert( iHeight>=0 );
  93679. if( iHeight==0 ){
  93680. isEof = testRtreeEntry(pRtree, pCursor);
  93681. }else{
  93682. isEof = testRtreeCell(pRtree, pCursor);
  93683. }
  93684. if( isEof || iHeight==0 ){
  93685. *pEof = isEof;
  93686. return SQLITE_OK;
  93687. }
  93688. iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  93689. rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  93690. if( rc!=SQLITE_OK ){
  93691. return rc;
  93692. }
  93693. nodeRelease(pRtree, pCursor->pNode);
  93694. pCursor->pNode = pChild;
  93695. isEof = 1;
  93696. for(ii=0; isEof && ii<NCELL(pChild); ii++){
  93697. pCursor->iCell = ii;
  93698. rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
  93699. if( rc!=SQLITE_OK ){
  93700. return rc;
  93701. }
  93702. }
  93703. if( isEof ){
  93704. assert( pCursor->pNode==pChild );
  93705. nodeReference(pSavedNode);
  93706. nodeRelease(pRtree, pChild);
  93707. pCursor->pNode = pSavedNode;
  93708. pCursor->iCell = iSavedCell;
  93709. }
  93710. *pEof = isEof;
  93711. return SQLITE_OK;
  93712. }
  93713. /*
  93714. ** One of the cells in node pNode is guaranteed to have a 64-bit
  93715. ** integer value equal to iRowid. Return the index of this cell.
  93716. */
  93717. static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
  93718. int ii;
  93719. for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
  93720. assert( ii<(NCELL(pNode)-1) );
  93721. }
  93722. return ii;
  93723. }
  93724. /*
  93725. ** Return the index of the cell containing a pointer to node pNode
  93726. ** in its parent. If pNode is the root node, return -1.
  93727. */
  93728. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
  93729. RtreeNode *pParent = pNode->pParent;
  93730. if( pParent ){
  93731. return nodeRowidIndex(pRtree, pParent, pNode->iNode);
  93732. }
  93733. return -1;
  93734. }
  93735. /*
  93736. ** Rtree virtual table module xNext method.
  93737. */
  93738. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  93739. Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  93740. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  93741. int rc = SQLITE_OK;
  93742. if( pCsr->iStrategy==1 ){
  93743. /* This "scan" is a direct lookup by rowid. There is no next entry. */
  93744. nodeRelease(pRtree, pCsr->pNode);
  93745. pCsr->pNode = 0;
  93746. }
  93747. else if( pCsr->pNode ){
  93748. /* Move to the next entry that matches the configured constraints. */
  93749. int iHeight = 0;
  93750. while( pCsr->pNode ){
  93751. RtreeNode *pNode = pCsr->pNode;
  93752. int nCell = NCELL(pNode);
  93753. for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
  93754. int isEof;
  93755. rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
  93756. if( rc!=SQLITE_OK || !isEof ){
  93757. return rc;
  93758. }
  93759. }
  93760. pCsr->pNode = pNode->pParent;
  93761. pCsr->iCell = nodeParentIndex(pRtree, pNode);
  93762. nodeReference(pCsr->pNode);
  93763. nodeRelease(pRtree, pNode);
  93764. iHeight++;
  93765. }
  93766. }
  93767. return rc;
  93768. }
  93769. /*
  93770. ** Rtree virtual table module xRowid method.
  93771. */
  93772. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  93773. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  93774. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  93775. assert(pCsr->pNode);
  93776. *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  93777. return SQLITE_OK;
  93778. }
  93779. /*
  93780. ** Rtree virtual table module xColumn method.
  93781. */
  93782. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  93783. Rtree *pRtree = (Rtree *)cur->pVtab;
  93784. RtreeCursor *pCsr = (RtreeCursor *)cur;
  93785. if( i==0 ){
  93786. i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  93787. sqlite3_result_int64(ctx, iRowid);
  93788. }else{
  93789. RtreeCoord c;
  93790. nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
  93791. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  93792. sqlite3_result_double(ctx, c.f);
  93793. }else{
  93794. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  93795. sqlite3_result_int(ctx, c.i);
  93796. }
  93797. }
  93798. return SQLITE_OK;
  93799. }
  93800. /*
  93801. ** Use nodeAcquire() to obtain the leaf node containing the record with
  93802. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  93803. ** return SQLITE_OK. If there is no such record in the table, set
  93804. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  93805. ** to zero and return an SQLite error code.
  93806. */
  93807. static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  93808. int rc;
  93809. *ppLeaf = 0;
  93810. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  93811. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  93812. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  93813. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  93814. sqlite3_reset(pRtree->pReadRowid);
  93815. }else{
  93816. rc = sqlite3_reset(pRtree->pReadRowid);
  93817. }
  93818. return rc;
  93819. }
  93820. /*
  93821. ** Rtree virtual table module xFilter method.
  93822. */
  93823. static int rtreeFilter(
  93824. sqlite3_vtab_cursor *pVtabCursor,
  93825. int idxNum, const char *idxStr,
  93826. int argc, sqlite3_value **argv
  93827. ){
  93828. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  93829. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  93830. RtreeNode *pRoot = 0;
  93831. int ii;
  93832. int rc = SQLITE_OK;
  93833. rtreeReference(pRtree);
  93834. sqlite3_free(pCsr->aConstraint);
  93835. pCsr->aConstraint = 0;
  93836. pCsr->iStrategy = idxNum;
  93837. if( idxNum==1 ){
  93838. /* Special case - lookup by rowid. */
  93839. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  93840. i64 iRowid = sqlite3_value_int64(argv[0]);
  93841. rc = findLeafNode(pRtree, iRowid, &pLeaf);
  93842. pCsr->pNode = pLeaf;
  93843. if( pLeaf && rc==SQLITE_OK ){
  93844. pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
  93845. }
  93846. }else{
  93847. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  93848. ** with the configured constraints.
  93849. */
  93850. if( argc>0 ){
  93851. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  93852. pCsr->nConstraint = argc;
  93853. if( !pCsr->aConstraint ){
  93854. rc = SQLITE_NOMEM;
  93855. }else{
  93856. assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
  93857. for(ii=0; ii<argc; ii++){
  93858. RtreeConstraint *p = &pCsr->aConstraint[ii];
  93859. p->op = idxStr[ii*2];
  93860. p->iCoord = idxStr[ii*2+1]-'a';
  93861. p->rValue = sqlite3_value_double(argv[ii]);
  93862. }
  93863. }
  93864. }
  93865. if( rc==SQLITE_OK ){
  93866. pCsr->pNode = 0;
  93867. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  93868. }
  93869. if( rc==SQLITE_OK ){
  93870. int isEof = 1;
  93871. int nCell = NCELL(pRoot);
  93872. pCsr->pNode = pRoot;
  93873. for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
  93874. assert( pCsr->pNode==pRoot );
  93875. rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
  93876. if( !isEof ){
  93877. break;
  93878. }
  93879. }
  93880. if( rc==SQLITE_OK && isEof ){
  93881. assert( pCsr->pNode==pRoot );
  93882. nodeRelease(pRtree, pRoot);
  93883. pCsr->pNode = 0;
  93884. }
  93885. assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
  93886. }
  93887. }
  93888. rtreeRelease(pRtree);
  93889. return rc;
  93890. }
  93891. /*
  93892. ** Rtree virtual table module xBestIndex method. There are three
  93893. ** table scan strategies to choose from (in order from most to
  93894. ** least desirable):
  93895. **
  93896. ** idxNum idxStr Strategy
  93897. ** ------------------------------------------------
  93898. ** 1 Unused Direct lookup by rowid.
  93899. ** 2 See below R-tree query.
  93900. ** 3 Unused Full table scan.
  93901. ** ------------------------------------------------
  93902. **
  93903. ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
  93904. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  93905. ** constraint used. The first two bytes of idxStr correspond to
  93906. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  93907. ** (argvIndex==1) etc.
  93908. **
  93909. ** The first of each pair of bytes in idxStr identifies the constraint
  93910. ** operator as follows:
  93911. **
  93912. ** Operator Byte Value
  93913. ** ----------------------
  93914. ** = 0x41 ('A')
  93915. ** <= 0x42 ('B')
  93916. ** < 0x43 ('C')
  93917. ** >= 0x44 ('D')
  93918. ** > 0x45 ('E')
  93919. ** ----------------------
  93920. **
  93921. ** The second of each pair of bytes identifies the coordinate column
  93922. ** to which the constraint applies. The leftmost coordinate column
  93923. ** is 'a', the second from the left 'b' etc.
  93924. */
  93925. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  93926. int rc = SQLITE_OK;
  93927. int ii, cCol;
  93928. int iIdx = 0;
  93929. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  93930. memset(zIdxStr, 0, sizeof(zIdxStr));
  93931. assert( pIdxInfo->idxStr==0 );
  93932. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  93933. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  93934. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  93935. /* We have an equality constraint on the rowid. Use strategy 1. */
  93936. int jj;
  93937. for(jj=0; jj<ii; jj++){
  93938. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  93939. pIdxInfo->aConstraintUsage[jj].omit = 0;
  93940. }
  93941. pIdxInfo->idxNum = 1;
  93942. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  93943. pIdxInfo->aConstraintUsage[jj].omit = 1;
  93944. /* This strategy involves a two rowid lookups on an B-Tree structures
  93945. ** and then a linear search of an R-Tree node. This should be
  93946. ** considered almost as quick as a direct rowid lookup (for which
  93947. ** sqlite uses an internal cost of 0.0).
  93948. */
  93949. pIdxInfo->estimatedCost = 10.0;
  93950. return SQLITE_OK;
  93951. }
  93952. if( p->usable && p->iColumn>0 ){
  93953. u8 op = 0;
  93954. switch( p->op ){
  93955. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  93956. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  93957. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  93958. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  93959. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  93960. }
  93961. if( op ){
  93962. /* Make sure this particular constraint has not been used before.
  93963. ** If it has been used before, ignore it.
  93964. **
  93965. ** A <= or < can be used if there is a prior >= or >.
  93966. ** A >= or > can be used if there is a prior < or <=.
  93967. ** A <= or < is disqualified if there is a prior <=, <, or ==.
  93968. ** A >= or > is disqualified if there is a prior >=, >, or ==.
  93969. ** A == is disqualifed if there is any prior constraint.
  93970. */
  93971. int j, opmsk;
  93972. static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
  93973. assert( compatible[RTREE_EQ & 7]==0 );
  93974. assert( compatible[RTREE_LT & 7]==1 );
  93975. assert( compatible[RTREE_LE & 7]==1 );
  93976. assert( compatible[RTREE_GT & 7]==2 );
  93977. assert( compatible[RTREE_GE & 7]==2 );
  93978. cCol = p->iColumn - 1 + 'a';
  93979. opmsk = compatible[op & 7];
  93980. for(j=0; j<iIdx; j+=2){
  93981. if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
  93982. op = 0;
  93983. break;
  93984. }
  93985. }
  93986. }
  93987. if( op ){
  93988. assert( iIdx<sizeof(zIdxStr)-1 );
  93989. zIdxStr[iIdx++] = op;
  93990. zIdxStr[iIdx++] = cCol;
  93991. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  93992. pIdxInfo->aConstraintUsage[ii].omit = 1;
  93993. }
  93994. }
  93995. }
  93996. pIdxInfo->idxNum = 2;
  93997. pIdxInfo->needToFreeIdxStr = 1;
  93998. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  93999. return SQLITE_NOMEM;
  94000. }
  94001. assert( iIdx>=0 );
  94002. pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  94003. return rc;
  94004. }
  94005. /*
  94006. ** Return the N-dimensional volumn of the cell stored in *p.
  94007. */
  94008. static float cellArea(Rtree *pRtree, RtreeCell *p){
  94009. float area = 1.0;
  94010. int ii;
  94011. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  94012. area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  94013. }
  94014. return area;
  94015. }
  94016. /*
  94017. ** Return the margin length of cell p. The margin length is the sum
  94018. ** of the objects size in each dimension.
  94019. */
  94020. static float cellMargin(Rtree *pRtree, RtreeCell *p){
  94021. float margin = 0.0;
  94022. int ii;
  94023. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  94024. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  94025. }
  94026. return margin;
  94027. }
  94028. /*
  94029. ** Store the union of cells p1 and p2 in p1.
  94030. */
  94031. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  94032. int ii;
  94033. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  94034. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  94035. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  94036. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  94037. }
  94038. }else{
  94039. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  94040. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  94041. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  94042. }
  94043. }
  94044. }
  94045. /*
  94046. ** Return true if the area covered by p2 is a subset of the area covered
  94047. ** by p1. False otherwise.
  94048. */
  94049. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  94050. int ii;
  94051. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  94052. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  94053. RtreeCoord *a1 = &p1->aCoord[ii];
  94054. RtreeCoord *a2 = &p2->aCoord[ii];
  94055. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  94056. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  94057. ){
  94058. return 0;
  94059. }
  94060. }
  94061. return 1;
  94062. }
  94063. /*
  94064. ** Return the amount cell p would grow by if it were unioned with pCell.
  94065. */
  94066. static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  94067. float area;
  94068. RtreeCell cell;
  94069. memcpy(&cell, p, sizeof(RtreeCell));
  94070. area = cellArea(pRtree, &cell);
  94071. cellUnion(pRtree, &cell, pCell);
  94072. return (cellArea(pRtree, &cell)-area);
  94073. }
  94074. #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
  94075. static float cellOverlap(
  94076. Rtree *pRtree,
  94077. RtreeCell *p,
  94078. RtreeCell *aCell,
  94079. int nCell,
  94080. int iExclude
  94081. ){
  94082. int ii;
  94083. float overlap = 0.0;
  94084. for(ii=0; ii<nCell; ii++){
  94085. if( ii!=iExclude ){
  94086. int jj;
  94087. float o = 1.0;
  94088. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  94089. double x1;
  94090. double x2;
  94091. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  94092. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  94093. if( x2<x1 ){
  94094. o = 0.0;
  94095. break;
  94096. }else{
  94097. o = o * (x2-x1);
  94098. }
  94099. }
  94100. overlap += o;
  94101. }
  94102. }
  94103. return overlap;
  94104. }
  94105. #endif
  94106. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  94107. static float cellOverlapEnlargement(
  94108. Rtree *pRtree,
  94109. RtreeCell *p,
  94110. RtreeCell *pInsert,
  94111. RtreeCell *aCell,
  94112. int nCell,
  94113. int iExclude
  94114. ){
  94115. float before;
  94116. float after;
  94117. before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  94118. cellUnion(pRtree, p, pInsert);
  94119. after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  94120. return after-before;
  94121. }
  94122. #endif
  94123. /*
  94124. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  94125. ** ChooseSubTree in r*tree terminology.
  94126. */
  94127. static int ChooseLeaf(
  94128. Rtree *pRtree, /* Rtree table */
  94129. RtreeCell *pCell, /* Cell to insert into rtree */
  94130. int iHeight, /* Height of sub-tree rooted at pCell */
  94131. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  94132. ){
  94133. int rc;
  94134. int ii;
  94135. RtreeNode *pNode;
  94136. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  94137. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  94138. int iCell;
  94139. sqlite3_int64 iBest;
  94140. float fMinGrowth;
  94141. float fMinArea;
  94142. float fMinOverlap;
  94143. int nCell = NCELL(pNode);
  94144. RtreeCell cell;
  94145. RtreeNode *pChild;
  94146. RtreeCell *aCell = 0;
  94147. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  94148. if( ii==(pRtree->iDepth-1) ){
  94149. int jj;
  94150. aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
  94151. if( !aCell ){
  94152. rc = SQLITE_NOMEM;
  94153. nodeRelease(pRtree, pNode);
  94154. pNode = 0;
  94155. continue;
  94156. }
  94157. for(jj=0; jj<nCell; jj++){
  94158. nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
  94159. }
  94160. }
  94161. #endif
  94162. /* Select the child node which will be enlarged the least if pCell
  94163. ** is inserted into it. Resolve ties by choosing the entry with
  94164. ** the smallest area.
  94165. */
  94166. for(iCell=0; iCell<nCell; iCell++){
  94167. float growth;
  94168. float area;
  94169. float overlap = 0.0;
  94170. nodeGetCell(pRtree, pNode, iCell, &cell);
  94171. growth = cellGrowth(pRtree, &cell, pCell);
  94172. area = cellArea(pRtree, &cell);
  94173. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  94174. if( ii==(pRtree->iDepth-1) ){
  94175. overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
  94176. }
  94177. #endif
  94178. if( (iCell==0)
  94179. || (overlap<fMinOverlap)
  94180. || (overlap==fMinOverlap && growth<fMinGrowth)
  94181. || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
  94182. ){
  94183. fMinOverlap = overlap;
  94184. fMinGrowth = growth;
  94185. fMinArea = area;
  94186. iBest = cell.iRowid;
  94187. }
  94188. }
  94189. sqlite3_free(aCell);
  94190. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  94191. nodeRelease(pRtree, pNode);
  94192. pNode = pChild;
  94193. }
  94194. *ppLeaf = pNode;
  94195. return rc;
  94196. }
  94197. /*
  94198. ** A cell with the same content as pCell has just been inserted into
  94199. ** the node pNode. This function updates the bounding box cells in
  94200. ** all ancestor elements.
  94201. */
  94202. static void AdjustTree(
  94203. Rtree *pRtree, /* Rtree table */
  94204. RtreeNode *pNode, /* Adjust ancestry of this node. */
  94205. RtreeCell *pCell /* This cell was just inserted */
  94206. ){
  94207. RtreeNode *p = pNode;
  94208. while( p->pParent ){
  94209. RtreeCell cell;
  94210. RtreeNode *pParent = p->pParent;
  94211. int iCell = nodeParentIndex(pRtree, p);
  94212. nodeGetCell(pRtree, pParent, iCell, &cell);
  94213. if( !cellContains(pRtree, &cell, pCell) ){
  94214. cellUnion(pRtree, &cell, pCell);
  94215. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  94216. }
  94217. p = pParent;
  94218. }
  94219. }
  94220. /*
  94221. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  94222. */
  94223. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  94224. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  94225. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  94226. sqlite3_step(pRtree->pWriteRowid);
  94227. return sqlite3_reset(pRtree->pWriteRowid);
  94228. }
  94229. /*
  94230. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  94231. */
  94232. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  94233. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  94234. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  94235. sqlite3_step(pRtree->pWriteParent);
  94236. return sqlite3_reset(pRtree->pWriteParent);
  94237. }
  94238. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  94239. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  94240. /*
  94241. ** Implementation of the linear variant of the PickNext() function from
  94242. ** Guttman[84].
  94243. */
  94244. static RtreeCell *LinearPickNext(
  94245. Rtree *pRtree,
  94246. RtreeCell *aCell,
  94247. int nCell,
  94248. RtreeCell *pLeftBox,
  94249. RtreeCell *pRightBox,
  94250. int *aiUsed
  94251. ){
  94252. int ii;
  94253. for(ii=0; aiUsed[ii]; ii++);
  94254. aiUsed[ii] = 1;
  94255. return &aCell[ii];
  94256. }
  94257. /*
  94258. ** Implementation of the linear variant of the PickSeeds() function from
  94259. ** Guttman[84].
  94260. */
  94261. static void LinearPickSeeds(
  94262. Rtree *pRtree,
  94263. RtreeCell *aCell,
  94264. int nCell,
  94265. int *piLeftSeed,
  94266. int *piRightSeed
  94267. ){
  94268. int i;
  94269. int iLeftSeed = 0;
  94270. int iRightSeed = 1;
  94271. float maxNormalInnerWidth = 0.0;
  94272. /* Pick two "seed" cells from the array of cells. The algorithm used
  94273. ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
  94274. ** indices of the two seed cells in the array are stored in local
  94275. ** variables iLeftSeek and iRightSeed.
  94276. */
  94277. for(i=0; i<pRtree->nDim; i++){
  94278. float x1 = aCell[0].aCoord[i*2];
  94279. float x2 = aCell[0].aCoord[i*2+1];
  94280. float x3 = x1;
  94281. float x4 = x2;
  94282. int jj;
  94283. int iCellLeft = 0;
  94284. int iCellRight = 0;
  94285. for(jj=1; jj<nCell; jj++){
  94286. float left = aCell[jj].aCoord[i*2];
  94287. float right = aCell[jj].aCoord[i*2+1];
  94288. if( left<x1 ) x1 = left;
  94289. if( right>x4 ) x4 = right;
  94290. if( left>x3 ){
  94291. x3 = left;
  94292. iCellRight = jj;
  94293. }
  94294. if( right<x2 ){
  94295. x2 = right;
  94296. iCellLeft = jj;
  94297. }
  94298. }
  94299. if( x4!=x1 ){
  94300. float normalwidth = (x3 - x2) / (x4 - x1);
  94301. if( normalwidth>maxNormalInnerWidth ){
  94302. iLeftSeed = iCellLeft;
  94303. iRightSeed = iCellRight;
  94304. }
  94305. }
  94306. }
  94307. *piLeftSeed = iLeftSeed;
  94308. *piRightSeed = iRightSeed;
  94309. }
  94310. #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
  94311. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  94312. /*
  94313. ** Implementation of the quadratic variant of the PickNext() function from
  94314. ** Guttman[84].
  94315. */
  94316. static RtreeCell *QuadraticPickNext(
  94317. Rtree *pRtree,
  94318. RtreeCell *aCell,
  94319. int nCell,
  94320. RtreeCell *pLeftBox,
  94321. RtreeCell *pRightBox,
  94322. int *aiUsed
  94323. ){
  94324. #define FABS(a) ((a)<0.0?-1.0*(a):(a))
  94325. int iSelect = -1;
  94326. float fDiff;
  94327. int ii;
  94328. for(ii=0; ii<nCell; ii++){
  94329. if( aiUsed[ii]==0 ){
  94330. float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  94331. float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  94332. float diff = FABS(right-left);
  94333. if( iSelect<0 || diff>fDiff ){
  94334. fDiff = diff;
  94335. iSelect = ii;
  94336. }
  94337. }
  94338. }
  94339. aiUsed[iSelect] = 1;
  94340. return &aCell[iSelect];
  94341. }
  94342. /*
  94343. ** Implementation of the quadratic variant of the PickSeeds() function from
  94344. ** Guttman[84].
  94345. */
  94346. static void QuadraticPickSeeds(
  94347. Rtree *pRtree,
  94348. RtreeCell *aCell,
  94349. int nCell,
  94350. int *piLeftSeed,
  94351. int *piRightSeed
  94352. ){
  94353. int ii;
  94354. int jj;
  94355. int iLeftSeed = 0;
  94356. int iRightSeed = 1;
  94357. float fWaste = 0.0;
  94358. for(ii=0; ii<nCell; ii++){
  94359. for(jj=ii+1; jj<nCell; jj++){
  94360. float right = cellArea(pRtree, &aCell[jj]);
  94361. float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
  94362. float waste = growth - right;
  94363. if( waste>fWaste ){
  94364. iLeftSeed = ii;
  94365. iRightSeed = jj;
  94366. fWaste = waste;
  94367. }
  94368. }
  94369. }
  94370. *piLeftSeed = iLeftSeed;
  94371. *piRightSeed = iRightSeed;
  94372. }
  94373. #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
  94374. /*
  94375. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  94376. ** nIdx. The aIdx array contains the set of integers from 0 to
  94377. ** (nIdx-1) in no particular order. This function sorts the values
  94378. ** in aIdx according to the indexed values in aDistance. For
  94379. ** example, assuming the inputs:
  94380. **
  94381. ** aIdx = { 0, 1, 2, 3 }
  94382. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  94383. **
  94384. ** this function sets the aIdx array to contain:
  94385. **
  94386. ** aIdx = { 0, 1, 2, 3 }
  94387. **
  94388. ** The aSpare array is used as temporary working space by the
  94389. ** sorting algorithm.
  94390. */
  94391. static void SortByDistance(
  94392. int *aIdx,
  94393. int nIdx,
  94394. float *aDistance,
  94395. int *aSpare
  94396. ){
  94397. if( nIdx>1 ){
  94398. int iLeft = 0;
  94399. int iRight = 0;
  94400. int nLeft = nIdx/2;
  94401. int nRight = nIdx-nLeft;
  94402. int *aLeft = aIdx;
  94403. int *aRight = &aIdx[nLeft];
  94404. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  94405. SortByDistance(aRight, nRight, aDistance, aSpare);
  94406. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  94407. aLeft = aSpare;
  94408. while( iLeft<nLeft || iRight<nRight ){
  94409. if( iLeft==nLeft ){
  94410. aIdx[iLeft+iRight] = aRight[iRight];
  94411. iRight++;
  94412. }else if( iRight==nRight ){
  94413. aIdx[iLeft+iRight] = aLeft[iLeft];
  94414. iLeft++;
  94415. }else{
  94416. float fLeft = aDistance[aLeft[iLeft]];
  94417. float fRight = aDistance[aRight[iRight]];
  94418. if( fLeft<fRight ){
  94419. aIdx[iLeft+iRight] = aLeft[iLeft];
  94420. iLeft++;
  94421. }else{
  94422. aIdx[iLeft+iRight] = aRight[iRight];
  94423. iRight++;
  94424. }
  94425. }
  94426. }
  94427. #if 0
  94428. /* Check that the sort worked */
  94429. {
  94430. int jj;
  94431. for(jj=1; jj<nIdx; jj++){
  94432. float left = aDistance[aIdx[jj-1]];
  94433. float right = aDistance[aIdx[jj]];
  94434. assert( left<=right );
  94435. }
  94436. }
  94437. #endif
  94438. }
  94439. }
  94440. /*
  94441. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  94442. ** nIdx. The aIdx array contains the set of integers from 0 to
  94443. ** (nIdx-1) in no particular order. This function sorts the values
  94444. ** in aIdx according to dimension iDim of the cells in aCell. The
  94445. ** minimum value of dimension iDim is considered first, the
  94446. ** maximum used to break ties.
  94447. **
  94448. ** The aSpare array is used as temporary working space by the
  94449. ** sorting algorithm.
  94450. */
  94451. static void SortByDimension(
  94452. Rtree *pRtree,
  94453. int *aIdx,
  94454. int nIdx,
  94455. int iDim,
  94456. RtreeCell *aCell,
  94457. int *aSpare
  94458. ){
  94459. if( nIdx>1 ){
  94460. int iLeft = 0;
  94461. int iRight = 0;
  94462. int nLeft = nIdx/2;
  94463. int nRight = nIdx-nLeft;
  94464. int *aLeft = aIdx;
  94465. int *aRight = &aIdx[nLeft];
  94466. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  94467. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  94468. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  94469. aLeft = aSpare;
  94470. while( iLeft<nLeft || iRight<nRight ){
  94471. double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  94472. double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  94473. double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  94474. double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  94475. if( (iLeft!=nLeft) && ((iRight==nRight)
  94476. || (xleft1<xright1)
  94477. || (xleft1==xright1 && xleft2<xright2)
  94478. )){
  94479. aIdx[iLeft+iRight] = aLeft[iLeft];
  94480. iLeft++;
  94481. }else{
  94482. aIdx[iLeft+iRight] = aRight[iRight];
  94483. iRight++;
  94484. }
  94485. }
  94486. #if 0
  94487. /* Check that the sort worked */
  94488. {
  94489. int jj;
  94490. for(jj=1; jj<nIdx; jj++){
  94491. float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  94492. float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  94493. float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  94494. float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  94495. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  94496. }
  94497. }
  94498. #endif
  94499. }
  94500. }
  94501. #if VARIANT_RSTARTREE_SPLIT
  94502. /*
  94503. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  94504. */
  94505. static int splitNodeStartree(
  94506. Rtree *pRtree,
  94507. RtreeCell *aCell,
  94508. int nCell,
  94509. RtreeNode *pLeft,
  94510. RtreeNode *pRight,
  94511. RtreeCell *pBboxLeft,
  94512. RtreeCell *pBboxRight
  94513. ){
  94514. int **aaSorted;
  94515. int *aSpare;
  94516. int ii;
  94517. int iBestDim;
  94518. int iBestSplit;
  94519. float fBestMargin;
  94520. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  94521. aaSorted = (int **)sqlite3_malloc(nByte);
  94522. if( !aaSorted ){
  94523. return SQLITE_NOMEM;
  94524. }
  94525. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  94526. memset(aaSorted, 0, nByte);
  94527. for(ii=0; ii<pRtree->nDim; ii++){
  94528. int jj;
  94529. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  94530. for(jj=0; jj<nCell; jj++){
  94531. aaSorted[ii][jj] = jj;
  94532. }
  94533. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  94534. }
  94535. for(ii=0; ii<pRtree->nDim; ii++){
  94536. float margin = 0.0;
  94537. float fBestOverlap;
  94538. float fBestArea;
  94539. int iBestLeft;
  94540. int nLeft;
  94541. for(
  94542. nLeft=RTREE_MINCELLS(pRtree);
  94543. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  94544. nLeft++
  94545. ){
  94546. RtreeCell left;
  94547. RtreeCell right;
  94548. int kk;
  94549. float overlap;
  94550. float area;
  94551. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  94552. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  94553. for(kk=1; kk<(nCell-1); kk++){
  94554. if( kk<nLeft ){
  94555. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  94556. }else{
  94557. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  94558. }
  94559. }
  94560. margin += cellMargin(pRtree, &left);
  94561. margin += cellMargin(pRtree, &right);
  94562. overlap = cellOverlap(pRtree, &left, &right, 1, -1);
  94563. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  94564. if( (nLeft==RTREE_MINCELLS(pRtree))
  94565. || (overlap<fBestOverlap)
  94566. || (overlap==fBestOverlap && area<fBestArea)
  94567. ){
  94568. iBestLeft = nLeft;
  94569. fBestOverlap = overlap;
  94570. fBestArea = area;
  94571. }
  94572. }
  94573. if( ii==0 || margin<fBestMargin ){
  94574. iBestDim = ii;
  94575. fBestMargin = margin;
  94576. iBestSplit = iBestLeft;
  94577. }
  94578. }
  94579. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  94580. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  94581. for(ii=0; ii<nCell; ii++){
  94582. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  94583. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  94584. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  94585. nodeInsertCell(pRtree, pTarget, pCell);
  94586. cellUnion(pRtree, pBbox, pCell);
  94587. }
  94588. sqlite3_free(aaSorted);
  94589. return SQLITE_OK;
  94590. }
  94591. #endif
  94592. #if VARIANT_GUTTMAN_SPLIT
  94593. /*
  94594. ** Implementation of the regular R-tree SplitNode from Guttman[1984].
  94595. */
  94596. static int splitNodeGuttman(
  94597. Rtree *pRtree,
  94598. RtreeCell *aCell,
  94599. int nCell,
  94600. RtreeNode *pLeft,
  94601. RtreeNode *pRight,
  94602. RtreeCell *pBboxLeft,
  94603. RtreeCell *pBboxRight
  94604. ){
  94605. int iLeftSeed = 0;
  94606. int iRightSeed = 1;
  94607. int *aiUsed;
  94608. int i;
  94609. aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  94610. memset(aiUsed, 0, sizeof(int)*nCell);
  94611. PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
  94612. memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  94613. memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  94614. nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  94615. nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  94616. aiUsed[iLeftSeed] = 1;
  94617. aiUsed[iRightSeed] = 1;
  94618. for(i=nCell-2; i>0; i--){
  94619. RtreeCell *pNext;
  94620. pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
  94621. float diff =
  94622. cellGrowth(pRtree, pBboxLeft, pNext) -
  94623. cellGrowth(pRtree, pBboxRight, pNext)
  94624. ;
  94625. if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
  94626. || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
  94627. ){
  94628. nodeInsertCell(pRtree, pRight, pNext);
  94629. cellUnion(pRtree, pBboxRight, pNext);
  94630. }else{
  94631. nodeInsertCell(pRtree, pLeft, pNext);
  94632. cellUnion(pRtree, pBboxLeft, pNext);
  94633. }
  94634. }
  94635. sqlite3_free(aiUsed);
  94636. return SQLITE_OK;
  94637. }
  94638. #endif
  94639. static int updateMapping(
  94640. Rtree *pRtree,
  94641. i64 iRowid,
  94642. RtreeNode *pNode,
  94643. int iHeight
  94644. ){
  94645. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  94646. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  94647. if( iHeight>0 ){
  94648. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  94649. if( pChild ){
  94650. nodeRelease(pRtree, pChild->pParent);
  94651. nodeReference(pNode);
  94652. pChild->pParent = pNode;
  94653. }
  94654. }
  94655. return xSetMapping(pRtree, iRowid, pNode->iNode);
  94656. }
  94657. static int SplitNode(
  94658. Rtree *pRtree,
  94659. RtreeNode *pNode,
  94660. RtreeCell *pCell,
  94661. int iHeight
  94662. ){
  94663. int i;
  94664. int newCellIsRight = 0;
  94665. int rc = SQLITE_OK;
  94666. int nCell = NCELL(pNode);
  94667. RtreeCell *aCell;
  94668. int *aiUsed;
  94669. RtreeNode *pLeft = 0;
  94670. RtreeNode *pRight = 0;
  94671. RtreeCell leftbbox;
  94672. RtreeCell rightbbox;
  94673. /* Allocate an array and populate it with a copy of pCell and
  94674. ** all cells from node pLeft. Then zero the original node.
  94675. */
  94676. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  94677. if( !aCell ){
  94678. rc = SQLITE_NOMEM;
  94679. goto splitnode_out;
  94680. }
  94681. aiUsed = (int *)&aCell[nCell+1];
  94682. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  94683. for(i=0; i<nCell; i++){
  94684. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  94685. }
  94686. nodeZero(pRtree, pNode);
  94687. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  94688. nCell++;
  94689. if( pNode->iNode==1 ){
  94690. pRight = nodeNew(pRtree, pNode, 1);
  94691. pLeft = nodeNew(pRtree, pNode, 1);
  94692. pRtree->iDepth++;
  94693. pNode->isDirty = 1;
  94694. writeInt16(pNode->zData, pRtree->iDepth);
  94695. }else{
  94696. pLeft = pNode;
  94697. pRight = nodeNew(pRtree, pLeft->pParent, 1);
  94698. nodeReference(pLeft);
  94699. }
  94700. if( !pLeft || !pRight ){
  94701. rc = SQLITE_NOMEM;
  94702. goto splitnode_out;
  94703. }
  94704. memset(pLeft->zData, 0, pRtree->iNodeSize);
  94705. memset(pRight->zData, 0, pRtree->iNodeSize);
  94706. rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  94707. if( rc!=SQLITE_OK ){
  94708. goto splitnode_out;
  94709. }
  94710. /* Ensure both child nodes have node numbers assigned to them. */
  94711. if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
  94712. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  94713. ){
  94714. goto splitnode_out;
  94715. }
  94716. rightbbox.iRowid = pRight->iNode;
  94717. leftbbox.iRowid = pLeft->iNode;
  94718. if( pNode->iNode==1 ){
  94719. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  94720. if( rc!=SQLITE_OK ){
  94721. goto splitnode_out;
  94722. }
  94723. }else{
  94724. RtreeNode *pParent = pLeft->pParent;
  94725. int iCell = nodeParentIndex(pRtree, pLeft);
  94726. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  94727. AdjustTree(pRtree, pParent, &leftbbox);
  94728. }
  94729. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  94730. goto splitnode_out;
  94731. }
  94732. for(i=0; i<NCELL(pRight); i++){
  94733. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  94734. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  94735. if( iRowid==pCell->iRowid ){
  94736. newCellIsRight = 1;
  94737. }
  94738. if( rc!=SQLITE_OK ){
  94739. goto splitnode_out;
  94740. }
  94741. }
  94742. if( pNode->iNode==1 ){
  94743. for(i=0; i<NCELL(pLeft); i++){
  94744. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  94745. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  94746. if( rc!=SQLITE_OK ){
  94747. goto splitnode_out;
  94748. }
  94749. }
  94750. }else if( newCellIsRight==0 ){
  94751. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  94752. }
  94753. if( rc==SQLITE_OK ){
  94754. rc = nodeRelease(pRtree, pRight);
  94755. pRight = 0;
  94756. }
  94757. if( rc==SQLITE_OK ){
  94758. rc = nodeRelease(pRtree, pLeft);
  94759. pLeft = 0;
  94760. }
  94761. splitnode_out:
  94762. nodeRelease(pRtree, pRight);
  94763. nodeRelease(pRtree, pLeft);
  94764. sqlite3_free(aCell);
  94765. return rc;
  94766. }
  94767. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  94768. int rc = SQLITE_OK;
  94769. if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
  94770. sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
  94771. if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
  94772. i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  94773. rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
  94774. }else{
  94775. rc = SQLITE_ERROR;
  94776. }
  94777. sqlite3_reset(pRtree->pReadParent);
  94778. if( rc==SQLITE_OK ){
  94779. rc = fixLeafParent(pRtree, pLeaf->pParent);
  94780. }
  94781. }
  94782. return rc;
  94783. }
  94784. static int deleteCell(Rtree *, RtreeNode *, int, int);
  94785. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  94786. int rc;
  94787. RtreeNode *pParent;
  94788. int iCell;
  94789. assert( pNode->nRef==1 );
  94790. /* Remove the entry in the parent cell. */
  94791. iCell = nodeParentIndex(pRtree, pNode);
  94792. pParent = pNode->pParent;
  94793. pNode->pParent = 0;
  94794. if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
  94795. || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
  94796. ){
  94797. return rc;
  94798. }
  94799. /* Remove the xxx_node entry. */
  94800. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  94801. sqlite3_step(pRtree->pDeleteNode);
  94802. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  94803. return rc;
  94804. }
  94805. /* Remove the xxx_parent entry. */
  94806. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  94807. sqlite3_step(pRtree->pDeleteParent);
  94808. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  94809. return rc;
  94810. }
  94811. /* Remove the node from the in-memory hash table and link it into
  94812. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  94813. */
  94814. nodeHashDelete(pRtree, pNode);
  94815. pNode->iNode = iHeight;
  94816. pNode->pNext = pRtree->pDeleted;
  94817. pNode->nRef++;
  94818. pRtree->pDeleted = pNode;
  94819. return SQLITE_OK;
  94820. }
  94821. static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  94822. RtreeNode *pParent = pNode->pParent;
  94823. if( pParent ){
  94824. int ii;
  94825. int nCell = NCELL(pNode);
  94826. RtreeCell box; /* Bounding box for pNode */
  94827. nodeGetCell(pRtree, pNode, 0, &box);
  94828. for(ii=1; ii<nCell; ii++){
  94829. RtreeCell cell;
  94830. nodeGetCell(pRtree, pNode, ii, &cell);
  94831. cellUnion(pRtree, &box, &cell);
  94832. }
  94833. box.iRowid = pNode->iNode;
  94834. ii = nodeParentIndex(pRtree, pNode);
  94835. nodeOverwriteCell(pRtree, pParent, &box, ii);
  94836. fixBoundingBox(pRtree, pParent);
  94837. }
  94838. }
  94839. /*
  94840. ** Delete the cell at index iCell of node pNode. After removing the
  94841. ** cell, adjust the r-tree data structure if required.
  94842. */
  94843. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  94844. int rc;
  94845. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  94846. return rc;
  94847. }
  94848. /* Remove the cell from the node. This call just moves bytes around
  94849. ** the in-memory node image, so it cannot fail.
  94850. */
  94851. nodeDeleteCell(pRtree, pNode, iCell);
  94852. /* If the node is not the tree root and now has less than the minimum
  94853. ** number of cells, remove it from the tree. Otherwise, update the
  94854. ** cell in the parent node so that it tightly contains the updated
  94855. ** node.
  94856. */
  94857. if( pNode->iNode!=1 ){
  94858. RtreeNode *pParent = pNode->pParent;
  94859. if( (pParent->iNode!=1 || NCELL(pParent)!=1)
  94860. && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
  94861. ){
  94862. rc = removeNode(pRtree, pNode, iHeight);
  94863. }else{
  94864. fixBoundingBox(pRtree, pNode);
  94865. }
  94866. }
  94867. return rc;
  94868. }
  94869. static int Reinsert(
  94870. Rtree *pRtree,
  94871. RtreeNode *pNode,
  94872. RtreeCell *pCell,
  94873. int iHeight
  94874. ){
  94875. int *aOrder;
  94876. int *aSpare;
  94877. RtreeCell *aCell;
  94878. float *aDistance;
  94879. int nCell;
  94880. float aCenterCoord[RTREE_MAX_DIMENSIONS];
  94881. int iDim;
  94882. int ii;
  94883. int rc = SQLITE_OK;
  94884. memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
  94885. nCell = NCELL(pNode)+1;
  94886. /* Allocate the buffers used by this operation. The allocation is
  94887. ** relinquished before this function returns.
  94888. */
  94889. aCell = (RtreeCell *)sqlite3_malloc(nCell * (
  94890. sizeof(RtreeCell) + /* aCell array */
  94891. sizeof(int) + /* aOrder array */
  94892. sizeof(int) + /* aSpare array */
  94893. sizeof(float) /* aDistance array */
  94894. ));
  94895. if( !aCell ){
  94896. return SQLITE_NOMEM;
  94897. }
  94898. aOrder = (int *)&aCell[nCell];
  94899. aSpare = (int *)&aOrder[nCell];
  94900. aDistance = (float *)&aSpare[nCell];
  94901. for(ii=0; ii<nCell; ii++){
  94902. if( ii==(nCell-1) ){
  94903. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  94904. }else{
  94905. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  94906. }
  94907. aOrder[ii] = ii;
  94908. for(iDim=0; iDim<pRtree->nDim; iDim++){
  94909. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  94910. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  94911. }
  94912. }
  94913. for(iDim=0; iDim<pRtree->nDim; iDim++){
  94914. aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
  94915. }
  94916. for(ii=0; ii<nCell; ii++){
  94917. aDistance[ii] = 0.0;
  94918. for(iDim=0; iDim<pRtree->nDim; iDim++){
  94919. float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  94920. DCOORD(aCell[ii].aCoord[iDim*2]);
  94921. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  94922. }
  94923. }
  94924. SortByDistance(aOrder, nCell, aDistance, aSpare);
  94925. nodeZero(pRtree, pNode);
  94926. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  94927. RtreeCell *p = &aCell[aOrder[ii]];
  94928. nodeInsertCell(pRtree, pNode, p);
  94929. if( p->iRowid==pCell->iRowid ){
  94930. if( iHeight==0 ){
  94931. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  94932. }else{
  94933. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  94934. }
  94935. }
  94936. }
  94937. if( rc==SQLITE_OK ){
  94938. fixBoundingBox(pRtree, pNode);
  94939. }
  94940. for(; rc==SQLITE_OK && ii<nCell; ii++){
  94941. /* Find a node to store this cell in. pNode->iNode currently contains
  94942. ** the height of the sub-tree headed by the cell.
  94943. */
  94944. RtreeNode *pInsert;
  94945. RtreeCell *p = &aCell[aOrder[ii]];
  94946. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  94947. if( rc==SQLITE_OK ){
  94948. int rc2;
  94949. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  94950. rc2 = nodeRelease(pRtree, pInsert);
  94951. if( rc==SQLITE_OK ){
  94952. rc = rc2;
  94953. }
  94954. }
  94955. }
  94956. sqlite3_free(aCell);
  94957. return rc;
  94958. }
  94959. /*
  94960. ** Insert cell pCell into node pNode. Node pNode is the head of a
  94961. ** subtree iHeight high (leaf nodes have iHeight==0).
  94962. */
  94963. static int rtreeInsertCell(
  94964. Rtree *pRtree,
  94965. RtreeNode *pNode,
  94966. RtreeCell *pCell,
  94967. int iHeight
  94968. ){
  94969. int rc = SQLITE_OK;
  94970. if( iHeight>0 ){
  94971. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  94972. if( pChild ){
  94973. nodeRelease(pRtree, pChild->pParent);
  94974. nodeReference(pNode);
  94975. pChild->pParent = pNode;
  94976. }
  94977. }
  94978. if( nodeInsertCell(pRtree, pNode, pCell) ){
  94979. #if VARIANT_RSTARTREE_REINSERT
  94980. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  94981. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  94982. }else{
  94983. pRtree->iReinsertHeight = iHeight;
  94984. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  94985. }
  94986. #else
  94987. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  94988. #endif
  94989. }else{
  94990. AdjustTree(pRtree, pNode, pCell);
  94991. if( iHeight==0 ){
  94992. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  94993. }else{
  94994. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  94995. }
  94996. }
  94997. return rc;
  94998. }
  94999. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  95000. int ii;
  95001. int rc = SQLITE_OK;
  95002. int nCell = NCELL(pNode);
  95003. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  95004. RtreeNode *pInsert;
  95005. RtreeCell cell;
  95006. nodeGetCell(pRtree, pNode, ii, &cell);
  95007. /* Find a node to store this cell in. pNode->iNode currently contains
  95008. ** the height of the sub-tree headed by the cell.
  95009. */
  95010. rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
  95011. if( rc==SQLITE_OK ){
  95012. int rc2;
  95013. rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
  95014. rc2 = nodeRelease(pRtree, pInsert);
  95015. if( rc==SQLITE_OK ){
  95016. rc = rc2;
  95017. }
  95018. }
  95019. }
  95020. return rc;
  95021. }
  95022. /*
  95023. ** Select a currently unused rowid for a new r-tree record.
  95024. */
  95025. static int newRowid(Rtree *pRtree, i64 *piRowid){
  95026. int rc;
  95027. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  95028. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  95029. sqlite3_step(pRtree->pWriteRowid);
  95030. rc = sqlite3_reset(pRtree->pWriteRowid);
  95031. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  95032. return rc;
  95033. }
  95034. #ifndef NDEBUG
  95035. static int hashIsEmpty(Rtree *pRtree){
  95036. int ii;
  95037. for(ii=0; ii<HASHSIZE; ii++){
  95038. assert( !pRtree->aHash[ii] );
  95039. }
  95040. return 1;
  95041. }
  95042. #endif
  95043. /*
  95044. ** The xUpdate method for rtree module virtual tables.
  95045. */
  95046. int rtreeUpdate(
  95047. sqlite3_vtab *pVtab,
  95048. int nData,
  95049. sqlite3_value **azData,
  95050. sqlite_int64 *pRowid
  95051. ){
  95052. Rtree *pRtree = (Rtree *)pVtab;
  95053. int rc = SQLITE_OK;
  95054. rtreeReference(pRtree);
  95055. assert(nData>=1);
  95056. assert(hashIsEmpty(pRtree));
  95057. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  95058. ** record to delete from the r-tree table. The following block does
  95059. ** just that.
  95060. */
  95061. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  95062. i64 iDelete; /* The rowid to delete */
  95063. RtreeNode *pLeaf; /* Leaf node containing record iDelete */
  95064. int iCell; /* Index of iDelete cell in pLeaf */
  95065. RtreeNode *pRoot;
  95066. /* Obtain a reference to the root node to initialise Rtree.iDepth */
  95067. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  95068. /* Obtain a reference to the leaf node that contains the entry
  95069. ** about to be deleted.
  95070. */
  95071. if( rc==SQLITE_OK ){
  95072. iDelete = sqlite3_value_int64(azData[0]);
  95073. rc = findLeafNode(pRtree, iDelete, &pLeaf);
  95074. }
  95075. /* Delete the cell in question from the leaf node. */
  95076. if( rc==SQLITE_OK ){
  95077. int rc2;
  95078. iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
  95079. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  95080. rc2 = nodeRelease(pRtree, pLeaf);
  95081. if( rc==SQLITE_OK ){
  95082. rc = rc2;
  95083. }
  95084. }
  95085. /* Delete the corresponding entry in the <rtree>_rowid table. */
  95086. if( rc==SQLITE_OK ){
  95087. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  95088. sqlite3_step(pRtree->pDeleteRowid);
  95089. rc = sqlite3_reset(pRtree->pDeleteRowid);
  95090. }
  95091. /* Check if the root node now has exactly one child. If so, remove
  95092. ** it, schedule the contents of the child for reinsertion and
  95093. ** reduce the tree height by one.
  95094. **
  95095. ** This is equivalent to copying the contents of the child into
  95096. ** the root node (the operation that Gutman's paper says to perform
  95097. ** in this scenario).
  95098. */
  95099. if( rc==SQLITE_OK && pRtree->iDepth>0 ){
  95100. if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
  95101. RtreeNode *pChild;
  95102. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  95103. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  95104. if( rc==SQLITE_OK ){
  95105. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  95106. }
  95107. if( rc==SQLITE_OK ){
  95108. pRtree->iDepth--;
  95109. writeInt16(pRoot->zData, pRtree->iDepth);
  95110. pRoot->isDirty = 1;
  95111. }
  95112. }
  95113. }
  95114. /* Re-insert the contents of any underfull nodes removed from the tree. */
  95115. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  95116. if( rc==SQLITE_OK ){
  95117. rc = reinsertNodeContent(pRtree, pLeaf);
  95118. }
  95119. pRtree->pDeleted = pLeaf->pNext;
  95120. sqlite3_free(pLeaf);
  95121. }
  95122. /* Release the reference to the root node. */
  95123. if( rc==SQLITE_OK ){
  95124. rc = nodeRelease(pRtree, pRoot);
  95125. }else{
  95126. nodeRelease(pRtree, pRoot);
  95127. }
  95128. }
  95129. /* If the azData[] array contains more than one element, elements
  95130. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  95131. ** the r-tree structure.
  95132. */
  95133. if( rc==SQLITE_OK && nData>1 ){
  95134. /* Insert a new record into the r-tree */
  95135. RtreeCell cell;
  95136. int ii;
  95137. RtreeNode *pLeaf;
  95138. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  95139. assert( nData==(pRtree->nDim*2 + 3) );
  95140. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  95141. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  95142. cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
  95143. cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
  95144. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  95145. rc = SQLITE_CONSTRAINT;
  95146. goto constraint;
  95147. }
  95148. }
  95149. }else{
  95150. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  95151. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  95152. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  95153. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  95154. rc = SQLITE_CONSTRAINT;
  95155. goto constraint;
  95156. }
  95157. }
  95158. }
  95159. /* Figure out the rowid of the new row. */
  95160. if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
  95161. rc = newRowid(pRtree, &cell.iRowid);
  95162. }else{
  95163. cell.iRowid = sqlite3_value_int64(azData[2]);
  95164. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  95165. if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
  95166. sqlite3_reset(pRtree->pReadRowid);
  95167. rc = SQLITE_CONSTRAINT;
  95168. goto constraint;
  95169. }
  95170. rc = sqlite3_reset(pRtree->pReadRowid);
  95171. }
  95172. if( rc==SQLITE_OK ){
  95173. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  95174. }
  95175. if( rc==SQLITE_OK ){
  95176. int rc2;
  95177. pRtree->iReinsertHeight = -1;
  95178. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  95179. rc2 = nodeRelease(pRtree, pLeaf);
  95180. if( rc==SQLITE_OK ){
  95181. rc = rc2;
  95182. }
  95183. }
  95184. }
  95185. constraint:
  95186. rtreeRelease(pRtree);
  95187. return rc;
  95188. }
  95189. /*
  95190. ** The xRename method for rtree module virtual tables.
  95191. */
  95192. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  95193. Rtree *pRtree = (Rtree *)pVtab;
  95194. int rc = SQLITE_NOMEM;
  95195. char *zSql = sqlite3_mprintf(
  95196. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  95197. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  95198. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  95199. , pRtree->zDb, pRtree->zName, zNewName
  95200. , pRtree->zDb, pRtree->zName, zNewName
  95201. , pRtree->zDb, pRtree->zName, zNewName
  95202. );
  95203. if( zSql ){
  95204. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  95205. sqlite3_free(zSql);
  95206. }
  95207. return rc;
  95208. }
  95209. static sqlite3_module rtreeModule = {
  95210. 0, /* iVersion */
  95211. rtreeCreate, /* xCreate - create a table */
  95212. rtreeConnect, /* xConnect - connect to an existing table */
  95213. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  95214. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  95215. rtreeDestroy, /* xDestroy - Drop a table */
  95216. rtreeOpen, /* xOpen - open a cursor */
  95217. rtreeClose, /* xClose - close a cursor */
  95218. rtreeFilter, /* xFilter - configure scan constraints */
  95219. rtreeNext, /* xNext - advance a cursor */
  95220. rtreeEof, /* xEof */
  95221. rtreeColumn, /* xColumn - read data */
  95222. rtreeRowid, /* xRowid - read data */
  95223. rtreeUpdate, /* xUpdate - write data */
  95224. 0, /* xBegin - begin transaction */
  95225. 0, /* xSync - sync transaction */
  95226. 0, /* xCommit - commit transaction */
  95227. 0, /* xRollback - rollback transaction */
  95228. 0, /* xFindFunction - function overloading */
  95229. rtreeRename /* xRename - rename the table */
  95230. };
  95231. static int rtreeSqlInit(
  95232. Rtree *pRtree,
  95233. sqlite3 *db,
  95234. const char *zDb,
  95235. const char *zPrefix,
  95236. int isCreate
  95237. ){
  95238. int rc = SQLITE_OK;
  95239. #define N_STATEMENT 9
  95240. static const char *azSql[N_STATEMENT] = {
  95241. /* Read and write the xxx_node table */
  95242. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  95243. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  95244. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  95245. /* Read and write the xxx_rowid table */
  95246. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  95247. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  95248. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  95249. /* Read and write the xxx_parent table */
  95250. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  95251. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  95252. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  95253. };
  95254. sqlite3_stmt **appStmt[N_STATEMENT];
  95255. int i;
  95256. pRtree->db = db;
  95257. if( isCreate ){
  95258. char *zCreate = sqlite3_mprintf(
  95259. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  95260. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  95261. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
  95262. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  95263. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  95264. );
  95265. if( !zCreate ){
  95266. return SQLITE_NOMEM;
  95267. }
  95268. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  95269. sqlite3_free(zCreate);
  95270. if( rc!=SQLITE_OK ){
  95271. return rc;
  95272. }
  95273. }
  95274. appStmt[0] = &pRtree->pReadNode;
  95275. appStmt[1] = &pRtree->pWriteNode;
  95276. appStmt[2] = &pRtree->pDeleteNode;
  95277. appStmt[3] = &pRtree->pReadRowid;
  95278. appStmt[4] = &pRtree->pWriteRowid;
  95279. appStmt[5] = &pRtree->pDeleteRowid;
  95280. appStmt[6] = &pRtree->pReadParent;
  95281. appStmt[7] = &pRtree->pWriteParent;
  95282. appStmt[8] = &pRtree->pDeleteParent;
  95283. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  95284. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  95285. if( zSql ){
  95286. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  95287. }else{
  95288. rc = SQLITE_NOMEM;
  95289. }
  95290. sqlite3_free(zSql);
  95291. }
  95292. return rc;
  95293. }
  95294. /*
  95295. ** This routine queries database handle db for the page-size used by
  95296. ** database zDb. If successful, the page-size in bytes is written to
  95297. ** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error
  95298. ** code is returned.
  95299. */
  95300. static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
  95301. int rc = SQLITE_NOMEM;
  95302. char *zSql;
  95303. sqlite3_stmt *pStmt = 0;
  95304. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
  95305. if( !zSql ){
  95306. return SQLITE_NOMEM;
  95307. }
  95308. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  95309. sqlite3_free(zSql);
  95310. if( rc!=SQLITE_OK ){
  95311. return rc;
  95312. }
  95313. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  95314. *piPageSize = sqlite3_column_int(pStmt, 0);
  95315. }
  95316. return sqlite3_finalize(pStmt);
  95317. }
  95318. /*
  95319. ** This function is the implementation of both the xConnect and xCreate
  95320. ** methods of the r-tree virtual table.
  95321. **
  95322. ** argv[0] -> module name
  95323. ** argv[1] -> database name
  95324. ** argv[2] -> table name
  95325. ** argv[...] -> column names...
  95326. */
  95327. static int rtreeInit(
  95328. sqlite3 *db, /* Database connection */
  95329. void *pAux, /* One of the RTREE_COORD_* constants */
  95330. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  95331. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  95332. char **pzErr, /* OUT: Error message, if any */
  95333. int isCreate /* True for xCreate, false for xConnect */
  95334. ){
  95335. int rc = SQLITE_OK;
  95336. int iPageSize = 0;
  95337. Rtree *pRtree;
  95338. int nDb; /* Length of string argv[1] */
  95339. int nName; /* Length of string argv[2] */
  95340. int eCoordType = (int)pAux;
  95341. const char *aErrMsg[] = {
  95342. 0, /* 0 */
  95343. "Wrong number of columns for an rtree table", /* 1 */
  95344. "Too few columns for an rtree table", /* 2 */
  95345. "Too many columns for an rtree table" /* 3 */
  95346. };
  95347. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  95348. if( aErrMsg[iErr] ){
  95349. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  95350. return SQLITE_ERROR;
  95351. }
  95352. rc = getPageSize(db, argv[1], &iPageSize);
  95353. if( rc!=SQLITE_OK ){
  95354. return rc;
  95355. }
  95356. /* Allocate the sqlite3_vtab structure */
  95357. nDb = strlen(argv[1]);
  95358. nName = strlen(argv[2]);
  95359. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  95360. if( !pRtree ){
  95361. return SQLITE_NOMEM;
  95362. }
  95363. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  95364. pRtree->nBusy = 1;
  95365. pRtree->base.pModule = &rtreeModule;
  95366. pRtree->zDb = (char *)&pRtree[1];
  95367. pRtree->zName = &pRtree->zDb[nDb+1];
  95368. pRtree->nDim = (argc-4)/2;
  95369. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  95370. pRtree->eCoordType = eCoordType;
  95371. memcpy(pRtree->zDb, argv[1], nDb);
  95372. memcpy(pRtree->zName, argv[2], nName);
  95373. /* Figure out the node size to use. By default, use 64 bytes less than
  95374. ** the database page-size. This ensures that each node is stored on
  95375. ** a single database page.
  95376. **
  95377. ** If the databasd page-size is so large that more than RTREE_MAXCELLS
  95378. ** entries would fit in a single node, use a smaller node-size.
  95379. */
  95380. pRtree->iNodeSize = iPageSize-64;
  95381. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  95382. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  95383. }
  95384. /* Create/Connect to the underlying relational database schema. If
  95385. ** that is successful, call sqlite3_declare_vtab() to configure
  95386. ** the r-tree table schema.
  95387. */
  95388. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  95389. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  95390. }else{
  95391. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  95392. char *zTmp;
  95393. int ii;
  95394. for(ii=4; zSql && ii<argc; ii++){
  95395. zTmp = zSql;
  95396. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  95397. sqlite3_free(zTmp);
  95398. }
  95399. if( zSql ){
  95400. zTmp = zSql;
  95401. zSql = sqlite3_mprintf("%s);", zTmp);
  95402. sqlite3_free(zTmp);
  95403. }
  95404. if( !zSql || sqlite3_declare_vtab(db, zSql) ){
  95405. rc = SQLITE_NOMEM;
  95406. }
  95407. sqlite3_free(zSql);
  95408. }
  95409. if( rc==SQLITE_OK ){
  95410. *ppVtab = (sqlite3_vtab *)pRtree;
  95411. }else{
  95412. rtreeRelease(pRtree);
  95413. }
  95414. return rc;
  95415. }
  95416. /*
  95417. ** Implementation of a scalar function that decodes r-tree nodes to
  95418. ** human readable strings. This can be used for debugging and analysis.
  95419. **
  95420. ** The scalar function takes two arguments, a blob of data containing
  95421. ** an r-tree node, and the number of dimensions the r-tree indexes.
  95422. ** For a two-dimensional r-tree structure called "rt", to deserialize
  95423. ** all nodes, a statement like:
  95424. **
  95425. ** SELECT rtreenode(2, data) FROM rt_node;
  95426. **
  95427. ** The human readable string takes the form of a Tcl list with one
  95428. ** entry for each cell in the r-tree node. Each entry is itself a
  95429. ** list, containing the 8-byte rowid/pageno followed by the
  95430. ** <num-dimension>*2 coordinates.
  95431. */
  95432. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  95433. char *zText = 0;
  95434. RtreeNode node;
  95435. Rtree tree;
  95436. int ii;
  95437. memset(&node, 0, sizeof(RtreeNode));
  95438. memset(&tree, 0, sizeof(Rtree));
  95439. tree.nDim = sqlite3_value_int(apArg[0]);
  95440. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  95441. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  95442. for(ii=0; ii<NCELL(&node); ii++){
  95443. char zCell[512];
  95444. int nCell = 0;
  95445. RtreeCell cell;
  95446. int jj;
  95447. nodeGetCell(&tree, &node, ii, &cell);
  95448. sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
  95449. nCell = strlen(zCell);
  95450. for(jj=0; jj<tree.nDim*2; jj++){
  95451. sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
  95452. nCell = strlen(zCell);
  95453. }
  95454. if( zText ){
  95455. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  95456. sqlite3_free(zText);
  95457. zText = zTextNew;
  95458. }else{
  95459. zText = sqlite3_mprintf("{%s}", zCell);
  95460. }
  95461. }
  95462. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  95463. }
  95464. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  95465. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  95466. || sqlite3_value_bytes(apArg[0])<2
  95467. ){
  95468. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  95469. }else{
  95470. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  95471. sqlite3_result_int(ctx, readInt16(zBlob));
  95472. }
  95473. }
  95474. /*
  95475. ** Register the r-tree module with database handle db. This creates the
  95476. ** virtual table module "rtree" and the debugging/analysis scalar
  95477. ** function "rtreenode".
  95478. */
  95479. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  95480. int rc = SQLITE_OK;
  95481. if( rc==SQLITE_OK ){
  95482. int utf8 = SQLITE_UTF8;
  95483. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  95484. }
  95485. if( rc==SQLITE_OK ){
  95486. int utf8 = SQLITE_UTF8;
  95487. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  95488. }
  95489. if( rc==SQLITE_OK ){
  95490. void *c = (void *)RTREE_COORD_REAL32;
  95491. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  95492. }
  95493. if( rc==SQLITE_OK ){
  95494. void *c = (void *)RTREE_COORD_INT32;
  95495. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  95496. }
  95497. return rc;
  95498. }
  95499. #if !SQLITE_CORE
  95500. SQLITE_API int sqlite3_extension_init(
  95501. sqlite3 *db,
  95502. char **pzErrMsg,
  95503. const sqlite3_api_routines *pApi
  95504. ){
  95505. SQLITE_EXTENSION_INIT2(pApi)
  95506. return sqlite3RtreeInit(db);
  95507. }
  95508. #endif
  95509. #endif
  95510. /************** End of rtree.c ***********************************************/
  95511. /************** Begin file icu.c *********************************************/
  95512. /*
  95513. ** 2007 May 6
  95514. **
  95515. ** The author disclaims copyright to this source code. In place of
  95516. ** a legal notice, here is a blessing:
  95517. **
  95518. ** May you do good and not evil.
  95519. ** May you find forgiveness for yourself and forgive others.
  95520. ** May you share freely, never taking more than you give.
  95521. **
  95522. *************************************************************************
  95523. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  95524. **
  95525. ** This file implements an integration between the ICU library
  95526. ** ("International Components for Unicode", an open-source library
  95527. ** for handling unicode data) and SQLite. The integration uses
  95528. ** ICU to provide the following to SQLite:
  95529. **
  95530. ** * An implementation of the SQL regexp() function (and hence REGEXP
  95531. ** operator) using the ICU uregex_XX() APIs.
  95532. **
  95533. ** * Implementations of the SQL scalar upper() and lower() functions
  95534. ** for case mapping.
  95535. **
  95536. ** * Integration of ICU and SQLite collation seqences.
  95537. **
  95538. ** * An implementation of the LIKE operator that uses ICU to
  95539. ** provide case-independent matching.
  95540. */
  95541. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  95542. /* Include ICU headers */
  95543. #include <unicode/utypes.h>
  95544. #include <unicode/uregex.h>
  95545. #include <unicode/ustring.h>
  95546. #include <unicode/ucol.h>
  95547. #ifndef SQLITE_CORE
  95548. SQLITE_EXTENSION_INIT1
  95549. #else
  95550. #endif
  95551. /*
  95552. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  95553. ** operator.
  95554. */
  95555. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  95556. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  95557. #endif
  95558. /*
  95559. ** Version of sqlite3_free() that is always a function, never a macro.
  95560. */
  95561. static void xFree(void *p){
  95562. sqlite3_free(p);
  95563. }
  95564. /*
  95565. ** Compare two UTF-8 strings for equality where the first string is
  95566. ** a "LIKE" expression. Return true (1) if they are the same and
  95567. ** false (0) if they are different.
  95568. */
  95569. static int icuLikeCompare(
  95570. const uint8_t *zPattern, /* LIKE pattern */
  95571. const uint8_t *zString, /* The UTF-8 string to compare against */
  95572. const UChar32 uEsc /* The escape character */
  95573. ){
  95574. static const int MATCH_ONE = (UChar32)'_';
  95575. static const int MATCH_ALL = (UChar32)'%';
  95576. int iPattern = 0; /* Current byte index in zPattern */
  95577. int iString = 0; /* Current byte index in zString */
  95578. int prevEscape = 0; /* True if the previous character was uEsc */
  95579. while( zPattern[iPattern]!=0 ){
  95580. /* Read (and consume) the next character from the input pattern. */
  95581. UChar32 uPattern;
  95582. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  95583. assert(uPattern!=0);
  95584. /* There are now 4 possibilities:
  95585. **
  95586. ** 1. uPattern is an unescaped match-all character "%",
  95587. ** 2. uPattern is an unescaped match-one character "_",
  95588. ** 3. uPattern is an unescaped escape character, or
  95589. ** 4. uPattern is to be handled as an ordinary character
  95590. */
  95591. if( !prevEscape && uPattern==MATCH_ALL ){
  95592. /* Case 1. */
  95593. uint8_t c;
  95594. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  95595. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  95596. ** test string.
  95597. */
  95598. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  95599. if( c==MATCH_ONE ){
  95600. if( zString[iString]==0 ) return 0;
  95601. U8_FWD_1_UNSAFE(zString, iString);
  95602. }
  95603. iPattern++;
  95604. }
  95605. if( zPattern[iPattern]==0 ) return 1;
  95606. while( zString[iString] ){
  95607. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  95608. return 1;
  95609. }
  95610. U8_FWD_1_UNSAFE(zString, iString);
  95611. }
  95612. return 0;
  95613. }else if( !prevEscape && uPattern==MATCH_ONE ){
  95614. /* Case 2. */
  95615. if( zString[iString]==0 ) return 0;
  95616. U8_FWD_1_UNSAFE(zString, iString);
  95617. }else if( !prevEscape && uPattern==uEsc){
  95618. /* Case 3. */
  95619. prevEscape = 1;
  95620. }else{
  95621. /* Case 4. */
  95622. UChar32 uString;
  95623. U8_NEXT_UNSAFE(zString, iString, uString);
  95624. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  95625. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  95626. if( uString!=uPattern ){
  95627. return 0;
  95628. }
  95629. prevEscape = 0;
  95630. }
  95631. }
  95632. return zString[iString]==0;
  95633. }
  95634. /*
  95635. ** Implementation of the like() SQL function. This function implements
  95636. ** the build-in LIKE operator. The first argument to the function is the
  95637. ** pattern and the second argument is the string. So, the SQL statements:
  95638. **
  95639. ** A LIKE B
  95640. **
  95641. ** is implemented as like(B, A). If there is an escape character E,
  95642. **
  95643. ** A LIKE B ESCAPE E
  95644. **
  95645. ** is mapped to like(B, A, E).
  95646. */
  95647. static void icuLikeFunc(
  95648. sqlite3_context *context,
  95649. int argc,
  95650. sqlite3_value **argv
  95651. ){
  95652. const unsigned char *zA = sqlite3_value_text(argv[0]);
  95653. const unsigned char *zB = sqlite3_value_text(argv[1]);
  95654. UChar32 uEsc = 0;
  95655. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  95656. ** of deep recursion and N*N behavior in patternCompare().
  95657. */
  95658. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  95659. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  95660. return;
  95661. }
  95662. if( argc==3 ){
  95663. /* The escape character string must consist of a single UTF-8 character.
  95664. ** Otherwise, return an error.
  95665. */
  95666. int nE= sqlite3_value_bytes(argv[2]);
  95667. const unsigned char *zE = sqlite3_value_text(argv[2]);
  95668. int i = 0;
  95669. if( zE==0 ) return;
  95670. U8_NEXT(zE, i, nE, uEsc);
  95671. if( i!=nE){
  95672. sqlite3_result_error(context,
  95673. "ESCAPE expression must be a single character", -1);
  95674. return;
  95675. }
  95676. }
  95677. if( zA && zB ){
  95678. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  95679. }
  95680. }
  95681. /*
  95682. ** This function is called when an ICU function called from within
  95683. ** the implementation of an SQL scalar function returns an error.
  95684. **
  95685. ** The scalar function context passed as the first argument is
  95686. ** loaded with an error message based on the following two args.
  95687. */
  95688. static void icuFunctionError(
  95689. sqlite3_context *pCtx, /* SQLite scalar function context */
  95690. const char *zName, /* Name of ICU function that failed */
  95691. UErrorCode e /* Error code returned by ICU function */
  95692. ){
  95693. char zBuf[128];
  95694. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  95695. zBuf[127] = '\0';
  95696. sqlite3_result_error(pCtx, zBuf, -1);
  95697. }
  95698. /*
  95699. ** Function to delete compiled regexp objects. Registered as
  95700. ** a destructor function with sqlite3_set_auxdata().
  95701. */
  95702. static void icuRegexpDelete(void *p){
  95703. URegularExpression *pExpr = (URegularExpression *)p;
  95704. uregex_close(pExpr);
  95705. }
  95706. /*
  95707. ** Implementation of SQLite REGEXP operator. This scalar function takes
  95708. ** two arguments. The first is a regular expression pattern to compile
  95709. ** the second is a string to match against that pattern. If either
  95710. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  95711. ** is 1 if the string matches the pattern, or 0 otherwise.
  95712. **
  95713. ** SQLite maps the regexp() function to the regexp() operator such
  95714. ** that the following two are equivalent:
  95715. **
  95716. ** zString REGEXP zPattern
  95717. ** regexp(zPattern, zString)
  95718. **
  95719. ** Uses the following ICU regexp APIs:
  95720. **
  95721. ** uregex_open()
  95722. ** uregex_matches()
  95723. ** uregex_close()
  95724. */
  95725. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  95726. UErrorCode status = U_ZERO_ERROR;
  95727. URegularExpression *pExpr;
  95728. UBool res;
  95729. const UChar *zString = sqlite3_value_text16(apArg[1]);
  95730. /* If the left hand side of the regexp operator is NULL,
  95731. ** then the result is also NULL.
  95732. */
  95733. if( !zString ){
  95734. return;
  95735. }
  95736. pExpr = sqlite3_get_auxdata(p, 0);
  95737. if( !pExpr ){
  95738. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  95739. if( !zPattern ){
  95740. return;
  95741. }
  95742. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  95743. if( U_SUCCESS(status) ){
  95744. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  95745. }else{
  95746. assert(!pExpr);
  95747. icuFunctionError(p, "uregex_open", status);
  95748. return;
  95749. }
  95750. }
  95751. /* Configure the text that the regular expression operates on. */
  95752. uregex_setText(pExpr, zString, -1, &status);
  95753. if( !U_SUCCESS(status) ){
  95754. icuFunctionError(p, "uregex_setText", status);
  95755. return;
  95756. }
  95757. /* Attempt the match */
  95758. res = uregex_matches(pExpr, 0, &status);
  95759. if( !U_SUCCESS(status) ){
  95760. icuFunctionError(p, "uregex_matches", status);
  95761. return;
  95762. }
  95763. /* Set the text that the regular expression operates on to a NULL
  95764. ** pointer. This is not really necessary, but it is tidier than
  95765. ** leaving the regular expression object configured with an invalid
  95766. ** pointer after this function returns.
  95767. */
  95768. uregex_setText(pExpr, 0, 0, &status);
  95769. /* Return 1 or 0. */
  95770. sqlite3_result_int(p, res ? 1 : 0);
  95771. }
  95772. /*
  95773. ** Implementations of scalar functions for case mapping - upper() and
  95774. ** lower(). Function upper() converts its input to upper-case (ABC).
  95775. ** Function lower() converts to lower-case (abc).
  95776. **
  95777. ** ICU provides two types of case mapping, "general" case mapping and
  95778. ** "language specific". Refer to ICU documentation for the differences
  95779. ** between the two.
  95780. **
  95781. ** To utilise "general" case mapping, the upper() or lower() scalar
  95782. ** functions are invoked with one argument:
  95783. **
  95784. ** upper('ABC') -> 'abc'
  95785. ** lower('abc') -> 'ABC'
  95786. **
  95787. ** To access ICU "language specific" case mapping, upper() or lower()
  95788. ** should be invoked with two arguments. The second argument is the name
  95789. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  95790. ** as the second argument is the same as invoking the 1 argument version
  95791. ** of upper() or lower().
  95792. **
  95793. ** lower('I', 'en_us') -> 'i'
  95794. ** lower('I', 'tr_tr') -> '?' (small dotless i)
  95795. **
  95796. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  95797. */
  95798. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  95799. const UChar *zInput;
  95800. UChar *zOutput;
  95801. int nInput;
  95802. int nOutput;
  95803. UErrorCode status = U_ZERO_ERROR;
  95804. const char *zLocale = 0;
  95805. assert(nArg==1 || nArg==2);
  95806. if( nArg==2 ){
  95807. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  95808. }
  95809. zInput = sqlite3_value_text16(apArg[0]);
  95810. if( !zInput ){
  95811. return;
  95812. }
  95813. nInput = sqlite3_value_bytes16(apArg[0]);
  95814. nOutput = nInput * 2 + 2;
  95815. zOutput = sqlite3_malloc(nOutput);
  95816. if( !zOutput ){
  95817. return;
  95818. }
  95819. if( sqlite3_user_data(p) ){
  95820. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  95821. }else{
  95822. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  95823. }
  95824. if( !U_SUCCESS(status) ){
  95825. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  95826. return;
  95827. }
  95828. sqlite3_result_text16(p, zOutput, -1, xFree);
  95829. }
  95830. /*
  95831. ** Collation sequence destructor function. The pCtx argument points to
  95832. ** a UCollator structure previously allocated using ucol_open().
  95833. */
  95834. static void icuCollationDel(void *pCtx){
  95835. UCollator *p = (UCollator *)pCtx;
  95836. ucol_close(p);
  95837. }
  95838. /*
  95839. ** Collation sequence comparison function. The pCtx argument points to
  95840. ** a UCollator structure previously allocated using ucol_open().
  95841. */
  95842. static int icuCollationColl(
  95843. void *pCtx,
  95844. int nLeft,
  95845. const void *zLeft,
  95846. int nRight,
  95847. const void *zRight
  95848. ){
  95849. UCollationResult res;
  95850. UCollator *p = (UCollator *)pCtx;
  95851. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  95852. switch( res ){
  95853. case UCOL_LESS: return -1;
  95854. case UCOL_GREATER: return +1;
  95855. case UCOL_EQUAL: return 0;
  95856. }
  95857. assert(!"Unexpected return value from ucol_strcoll()");
  95858. return 0;
  95859. }
  95860. /*
  95861. ** Implementation of the scalar function icu_load_collation().
  95862. **
  95863. ** This scalar function is used to add ICU collation based collation
  95864. ** types to an SQLite database connection. It is intended to be called
  95865. ** as follows:
  95866. **
  95867. ** SELECT icu_load_collation(<locale>, <collation-name>);
  95868. **
  95869. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  95870. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  95871. ** collation sequence to create.
  95872. */
  95873. static void icuLoadCollation(
  95874. sqlite3_context *p,
  95875. int nArg,
  95876. sqlite3_value **apArg
  95877. ){
  95878. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  95879. UErrorCode status = U_ZERO_ERROR;
  95880. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  95881. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  95882. UCollator *pUCollator; /* ICU library collation object */
  95883. int rc; /* Return code from sqlite3_create_collation_x() */
  95884. assert(nArg==2);
  95885. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  95886. zName = (const char *)sqlite3_value_text(apArg[1]);
  95887. if( !zLocale || !zName ){
  95888. return;
  95889. }
  95890. pUCollator = ucol_open(zLocale, &status);
  95891. if( !U_SUCCESS(status) ){
  95892. icuFunctionError(p, "ucol_open", status);
  95893. return;
  95894. }
  95895. assert(p);
  95896. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  95897. icuCollationColl, icuCollationDel
  95898. );
  95899. if( rc!=SQLITE_OK ){
  95900. ucol_close(pUCollator);
  95901. sqlite3_result_error(p, "Error registering collation function", -1);
  95902. }
  95903. }
  95904. /*
  95905. ** Register the ICU extension functions with database db.
  95906. */
  95907. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  95908. struct IcuScalar {
  95909. const char *zName; /* Function name */
  95910. int nArg; /* Number of arguments */
  95911. int enc; /* Optimal text encoding */
  95912. void *pContext; /* sqlite3_user_data() context */
  95913. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  95914. } scalars[] = {
  95915. {"regexp",-1, SQLITE_ANY, 0, icuRegexpFunc},
  95916. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  95917. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  95918. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  95919. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  95920. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  95921. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  95922. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  95923. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  95924. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  95925. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  95926. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  95927. };
  95928. int rc = SQLITE_OK;
  95929. int i;
  95930. for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
  95931. struct IcuScalar *p = &scalars[i];
  95932. rc = sqlite3_create_function(
  95933. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  95934. );
  95935. }
  95936. return rc;
  95937. }
  95938. #if !SQLITE_CORE
  95939. SQLITE_API int sqlite3_extension_init(
  95940. sqlite3 *db,
  95941. char **pzErrMsg,
  95942. const sqlite3_api_routines *pApi
  95943. ){
  95944. SQLITE_EXTENSION_INIT2(pApi)
  95945. return sqlite3IcuInit(db);
  95946. }
  95947. #endif
  95948. #endif
  95949. /************** End of icu.c *************************************************/
  95950. /************** Begin file fts3_icu.c ****************************************/
  95951. /*
  95952. ** 2007 June 22
  95953. **
  95954. ** The author disclaims copyright to this source code. In place of
  95955. ** a legal notice, here is a blessing:
  95956. **
  95957. ** May you do good and not evil.
  95958. ** May you find forgiveness for yourself and forgive others.
  95959. ** May you share freely, never taking more than you give.
  95960. **
  95961. *************************************************************************
  95962. ** This file implements a tokenizer for fts3 based on the ICU library.
  95963. **
  95964. ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
  95965. */
  95966. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  95967. #ifdef SQLITE_ENABLE_ICU
  95968. #include <unicode/ubrk.h>
  95969. #include <unicode/utf16.h>
  95970. typedef struct IcuTokenizer IcuTokenizer;
  95971. typedef struct IcuCursor IcuCursor;
  95972. struct IcuTokenizer {
  95973. sqlite3_tokenizer base;
  95974. char *zLocale;
  95975. };
  95976. struct IcuCursor {
  95977. sqlite3_tokenizer_cursor base;
  95978. UBreakIterator *pIter; /* ICU break-iterator object */
  95979. int nChar; /* Number of UChar elements in pInput */
  95980. UChar *aChar; /* Copy of input using utf-16 encoding */
  95981. int *aOffset; /* Offsets of each character in utf-8 input */
  95982. int nBuffer;
  95983. char *zBuffer;
  95984. int iToken;
  95985. };
  95986. /*
  95987. ** Create a new tokenizer instance.
  95988. */
  95989. static int icuCreate(
  95990. int argc, /* Number of entries in argv[] */
  95991. const char * const *argv, /* Tokenizer creation arguments */
  95992. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  95993. ){
  95994. IcuTokenizer *p;
  95995. int n = 0;
  95996. if( argc>0 ){
  95997. n = strlen(argv[0])+1;
  95998. }
  95999. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  96000. if( !p ){
  96001. return SQLITE_NOMEM;
  96002. }
  96003. memset(p, 0, sizeof(IcuTokenizer));
  96004. if( n ){
  96005. p->zLocale = (char *)&p[1];
  96006. memcpy(p->zLocale, argv[0], n);
  96007. }
  96008. *ppTokenizer = (sqlite3_tokenizer *)p;
  96009. return SQLITE_OK;
  96010. }
  96011. /*
  96012. ** Destroy a tokenizer
  96013. */
  96014. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  96015. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  96016. sqlite3_free(p);
  96017. return SQLITE_OK;
  96018. }
  96019. /*
  96020. ** Prepare to begin tokenizing a particular string. The input
  96021. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  96022. ** used to incrementally tokenize this string is returned in
  96023. ** *ppCursor.
  96024. */
  96025. static int icuOpen(
  96026. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  96027. const char *zInput, /* Input string */
  96028. int nInput, /* Length of zInput in bytes */
  96029. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  96030. ){
  96031. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  96032. IcuCursor *pCsr;
  96033. const int32_t opt = U_FOLD_CASE_DEFAULT;
  96034. UErrorCode status = U_ZERO_ERROR;
  96035. int nChar;
  96036. UChar32 c;
  96037. int iInput = 0;
  96038. int iOut = 0;
  96039. *ppCursor = 0;
  96040. if( nInput<0 ){
  96041. nInput = strlen(zInput);
  96042. }
  96043. nChar = nInput+1;
  96044. pCsr = (IcuCursor *)sqlite3_malloc(
  96045. sizeof(IcuCursor) + /* IcuCursor */
  96046. nChar * sizeof(UChar) + /* IcuCursor.aChar[] */
  96047. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  96048. );
  96049. if( !pCsr ){
  96050. return SQLITE_NOMEM;
  96051. }
  96052. memset(pCsr, 0, sizeof(IcuCursor));
  96053. pCsr->aChar = (UChar *)&pCsr[1];
  96054. pCsr->aOffset = (int *)&pCsr->aChar[nChar];
  96055. pCsr->aOffset[iOut] = iInput;
  96056. U8_NEXT(zInput, iInput, nInput, c);
  96057. while( c>0 ){
  96058. int isError = 0;
  96059. c = u_foldCase(c, opt);
  96060. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  96061. if( isError ){
  96062. sqlite3_free(pCsr);
  96063. return SQLITE_ERROR;
  96064. }
  96065. pCsr->aOffset[iOut] = iInput;
  96066. if( iInput<nInput ){
  96067. U8_NEXT(zInput, iInput, nInput, c);
  96068. }else{
  96069. c = 0;
  96070. }
  96071. }
  96072. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  96073. if( !U_SUCCESS(status) ){
  96074. sqlite3_free(pCsr);
  96075. return SQLITE_ERROR;
  96076. }
  96077. pCsr->nChar = iOut;
  96078. ubrk_first(pCsr->pIter);
  96079. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  96080. return SQLITE_OK;
  96081. }
  96082. /*
  96083. ** Close a tokenization cursor previously opened by a call to icuOpen().
  96084. */
  96085. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  96086. IcuCursor *pCsr = (IcuCursor *)pCursor;
  96087. ubrk_close(pCsr->pIter);
  96088. sqlite3_free(pCsr->zBuffer);
  96089. sqlite3_free(pCsr);
  96090. return SQLITE_OK;
  96091. }
  96092. /*
  96093. ** Extract the next token from a tokenization cursor.
  96094. */
  96095. static int icuNext(
  96096. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  96097. const char **ppToken, /* OUT: *ppToken is the token text */
  96098. int *pnBytes, /* OUT: Number of bytes in token */
  96099. int *piStartOffset, /* OUT: Starting offset of token */
  96100. int *piEndOffset, /* OUT: Ending offset of token */
  96101. int *piPosition /* OUT: Position integer of token */
  96102. ){
  96103. IcuCursor *pCsr = (IcuCursor *)pCursor;
  96104. int iStart = 0;
  96105. int iEnd = 0;
  96106. int nByte = 0;
  96107. while( iStart==iEnd ){
  96108. UChar32 c;
  96109. iStart = ubrk_current(pCsr->pIter);
  96110. iEnd = ubrk_next(pCsr->pIter);
  96111. if( iEnd==UBRK_DONE ){
  96112. return SQLITE_DONE;
  96113. }
  96114. while( iStart<iEnd ){
  96115. int iWhite = iStart;
  96116. U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  96117. if( u_isspace(c) ){
  96118. iStart = iWhite;
  96119. }else{
  96120. break;
  96121. }
  96122. }
  96123. assert(iStart<=iEnd);
  96124. }
  96125. do {
  96126. UErrorCode status = U_ZERO_ERROR;
  96127. if( nByte ){
  96128. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  96129. if( !zNew ){
  96130. return SQLITE_NOMEM;
  96131. }
  96132. pCsr->zBuffer = zNew;
  96133. pCsr->nBuffer = nByte;
  96134. }
  96135. u_strToUTF8(
  96136. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  96137. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  96138. &status /* Output success/failure */
  96139. );
  96140. } while( nByte>pCsr->nBuffer );
  96141. *ppToken = pCsr->zBuffer;
  96142. *pnBytes = nByte;
  96143. *piStartOffset = pCsr->aOffset[iStart];
  96144. *piEndOffset = pCsr->aOffset[iEnd];
  96145. *piPosition = pCsr->iToken++;
  96146. return SQLITE_OK;
  96147. }
  96148. /*
  96149. ** The set of routines that implement the simple tokenizer
  96150. */
  96151. static const sqlite3_tokenizer_module icuTokenizerModule = {
  96152. 0, /* iVersion */
  96153. icuCreate, /* xCreate */
  96154. icuDestroy, /* xCreate */
  96155. icuOpen, /* xOpen */
  96156. icuClose, /* xClose */
  96157. icuNext, /* xNext */
  96158. };
  96159. /*
  96160. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  96161. */
  96162. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  96163. sqlite3_tokenizer_module const**ppModule
  96164. ){
  96165. *ppModule = &icuTokenizerModule;
  96166. }
  96167. #endif /* defined(SQLITE_ENABLE_ICU) */
  96168. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  96169. /************** End of fts3_icu.c ********************************************/